diff --git a/.editorconfig b/.editorconfig index f59dc4b3..49a5b99e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,4 +5,13 @@ indent_size = 2 [*.sql] indent_style = tab -indent_size = 16 \ No newline at end of file +indent_size = 16 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:warning + +# CA1859: Use concrete types when possible for improved performance +# Interface usage in this codebase is deliberate—e.g., to express a shared +# dependency's contract, or to scope a test to the interface under test—so +# this suggestion is not adopted. +dotnet_diagnostic.CA1859.severity = none \ No newline at end of file diff --git a/Directory.Packages.props b/Directory.Packages.props index 930d020a..1e23afc0 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,7 +3,7 @@ true - + diff --git a/GitVersion.yml b/GitVersion.yml index b84f148d..f847ccb9 100644 --- a/GitVersion.yml +++ b/GitVersion.yml @@ -1,7 +1,16 @@ assembly-versioning-scheme: MajorMinorPatch -mode: ContinuousDeployment +mode: ContinuousDelivery branches: master: + regex: ^master$|^main$ + mode: ManualDeployment + release: + mode: ContinuousDelivery + feature: + mode: ContinuousDelivery + hotfix: + mode: ContinuousDelivery + unknown: mode: ContinuousDelivery ignore: sha: [] \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Host/Components/MenuViewComponent.cs b/OnTopic.AspNetCore.Mvc.Host/Components/MenuViewComponent.cs index 2628264d..fe6bceff 100644 --- a/OnTopic.AspNetCore.Mvc.Host/Components/MenuViewComponent.cs +++ b/OnTopic.AspNetCore.Mvc.Host/Components/MenuViewComponent.cs @@ -12,40 +12,39 @@ using OnTopic.Repositories; using OnTopic.ViewModels; -namespace OnTopic.AspNetCore.Mvc.Host.Components { +namespace OnTopic.AspNetCore.Mvc.Host.Components; + +/*============================================================================================================================== +| CLASS: MENU VIEW COMPONENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a which provides access to a menu of +/// instances. +/// +/// +/// +/// As a best practice, global data required by the layout view are requested independent of the current page. This +/// allows each layout element to be provided with its own layout data, in the form of s, instead of needing to add this data to every view model returned by . +/// +/// +[ExcludeFromCodeCoverage] +public class MenuViewComponent : MenuViewComponentBase { /*============================================================================================================================ - | CLASS: MENU VIEW COMPONENT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines a which provides access to a menu of - /// instances. + /// Initializes a new instance of a with necessary dependencies. /// - /// - /// - /// As a best practice, global data required by the layout view are requested independent of the current page. This - /// allows each layout element to be provided with its own layout data, in the form of s, instead of needing to add this data to every view model returned by . - /// - /// - [ExcludeFromCodeCoverage] - public class MenuViewComponent : MenuViewComponentBase { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - /// A topic controller for loading OnTopic views. - public MenuViewComponent( - ITopicRepository topicRepository, - IHierarchicalTopicMappingService hierarchicalTopicMappingService - ) : base( - topicRepository, - hierarchicalTopicMappingService - ) {} + /// A topic controller for loading OnTopic views. + public MenuViewComponent( + ITopicRepository topicRepository, + IHierarchicalTopicMappingService hierarchicalTopicMappingService + ) : base( + topicRepository, + hierarchicalTopicMappingService + ) {} - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Host/Components/PageLevelNavigationViewComponent.cs b/OnTopic.AspNetCore.Mvc.Host/Components/PageLevelNavigationViewComponent.cs index 9b24f1b1..92609c69 100644 --- a/OnTopic.AspNetCore.Mvc.Host/Components/PageLevelNavigationViewComponent.cs +++ b/OnTopic.AspNetCore.Mvc.Host/Components/PageLevelNavigationViewComponent.cs @@ -12,39 +12,38 @@ using OnTopic.Repositories; using OnTopic.ViewModels; -namespace OnTopic.AspNetCore.Mvc.Host.Components { +namespace OnTopic.AspNetCore.Mvc.Host.Components; + +/*============================================================================================================================== +| CLASS: PAGE-LEVEL NAVIGATION VIEW COMPONENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a which provides access to a menu of +/// instances representing the nearest page-level navigation. +/// +/// +/// +/// As a best practice, global data required by the layout view are requested independent of the current page. This +/// allows each layout element to be provided with its own layout data, in the form of s, instead of needing to add this data to every view model returned by . +/// +/// +[ExcludeFromCodeCoverage] +public class PageLevelNavigationViewComponent : PageLevelNavigationViewComponentBase { /*============================================================================================================================ - | CLASS: PAGE-LEVEL NAVIGATION VIEW COMPONENT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines a which provides access to a menu of - /// instances representing the nearest page-level navigation. + /// Initializes a new instance of a with necessary dependencies. /// - /// - /// - /// As a best practice, global data required by the layout view are requested independent of the current page. This - /// allows each layout element to be provided with its own layout data, in the form of s, instead of needing to add this data to every view model returned by . - /// - /// - [ExcludeFromCodeCoverage] - public class PageLevelNavigationViewComponent : PageLevelNavigationViewComponentBase { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - /// A topic controller for loading OnTopic views. - public PageLevelNavigationViewComponent( - ITopicRepository topicRepository, - IHierarchicalTopicMappingService hierarchicalTopicMappingService - ) : base( - topicRepository, - hierarchicalTopicMappingService - ) {} + /// A topic controller for loading OnTopic views. + public PageLevelNavigationViewComponent( + ITopicRepository topicRepository, + IHierarchicalTopicMappingService hierarchicalTopicMappingService + ) : base( + topicRepository, + hierarchicalTopicMappingService + ) {} - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Host/OnTopic.AspNetCore.Mvc.Host.csproj b/OnTopic.AspNetCore.Mvc.Host/OnTopic.AspNetCore.Mvc.Host.csproj index 37afb35e..11e27c2d 100644 --- a/OnTopic.AspNetCore.Mvc.Host/OnTopic.AspNetCore.Mvc.Host.csproj +++ b/OnTopic.AspNetCore.Mvc.Host/OnTopic.AspNetCore.Mvc.Host.csproj @@ -4,6 +4,7 @@ net8.0 62eb85bf-f802-4afd-8bec-3d344e1cfc79 false + CA1515 diff --git a/OnTopic.AspNetCore.Mvc.Host/Program.cs b/OnTopic.AspNetCore.Mvc.Host/Program.cs index b3e9cb9c..15bb5613 100644 --- a/OnTopic.AspNetCore.Mvc.Host/Program.cs +++ b/OnTopic.AspNetCore.Mvc.Host/Program.cs @@ -9,7 +9,7 @@ using OnTopic.AspNetCore.Mvc.Host; using OnTopic.Internal.Diagnostics; -#pragma warning disable CA1812 // Avoid uninstantiated internal classes +#pragma warning disable CA1812 // Avoid uninstantiated internal classes /*============================================================================================================================== | CONFIGURE SERVICES @@ -21,7 +21,7 @@ \-----------------------------------------------------------------------------------------------------------------------------*/ builder.Services.Configure(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. - options.CheckConsentNeeded = context => true; + options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); @@ -95,4 +95,4 @@ \-----------------------------------------------------------------------------------------------------------------------------*/ app.Run(); -#pragma warning restore CA1812 // Avoid uninstantiated internal classes \ No newline at end of file +#pragma warning restore CA1812 // Avoid uninstantiated internal classes \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Host/SampleActivator.cs b/OnTopic.AspNetCore.Mvc.Host/SampleActivator.cs index 3bc1849a..11ca0b89 100644 --- a/OnTopic.AspNetCore.Mvc.Host/SampleActivator.cs +++ b/OnTopic.AspNetCore.Mvc.Host/SampleActivator.cs @@ -18,162 +18,161 @@ using OnTopic.Repositories; using OnTopic.ViewModels; -namespace OnTopic.AspNetCore.Mvc.Host { +namespace OnTopic.AspNetCore.Mvc.Host; + +/*============================================================================================================================== +| CLASS: SAMPLE ACTIVATOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Responsible for creating instances of factories in response to web requests. Represents the Composition Root for +/// Dependency Injection. +/// +[ExcludeFromCodeCoverage] +public class SampleActivator : IControllerActivator, IViewComponentActivator { /*============================================================================================================================ - | CLASS: SAMPLE ACTIVATOR + | PRIVATE INSTANCES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ITypeLookupService _typeLookupService; + private readonly ITopicMappingService _topicMappingService; + private readonly ITopicRepository _topicRepository; + private DateTime _cacheLastUpdated = DateTime.UtcNow; + + /*============================================================================================================================ + | HIERARCHICAL TOPIC MAPPING SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Responsible for creating instances of factories in response to web requests. Represents the Composition Root for - /// Dependency Injection. + /// Establishes a new instance of the , including any shared dependencies to be used across + /// instances of controllers. /// - [ExcludeFromCodeCoverage] - public class SampleActivator : IControllerActivator, IViewComponentActivator { + /// + /// The constructor is responsible for establishing dependencies with the singleton lifestyle so that they are available + /// to all requests. + /// + public SampleActivator(string connectionString) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate dependencies + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(connectionString); - /*========================================================================================================================== - | PRIVATE INSTANCES + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize Topic Repository \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITypeLookupService _typeLookupService; - private readonly ITopicMappingService _topicMappingService; - private readonly ITopicRepository _topicRepository; - private DateTime _cacheLastUpdated = DateTime.UtcNow; + var sqlTopicRepository = new SqlTopicRepository(connectionString); + var cachedTopicRepository = new CachedTopicRepository(sqlTopicRepository); + _ = new PageTopicViewModel(); - /*========================================================================================================================== - | HIERARCHICAL TOPIC MAPPING SERVICE + /*-------------------------------------------------------------------------------------------------------------------------- + | Preload repository \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + _topicRepository = cachedTopicRepository; + _typeLookupService = new DynamicTopicViewModelLookupService(); + _topicMappingService = new TopicMappingService(_topicRepository, _typeLookupService); + _ = _topicRepository.Load(); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish hierarchical topic mapping service \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of the , including any shared dependencies to be used across - /// instances of controllers. - /// - /// - /// The constructor is responsible for establishing dependencies with the singleton lifestyle so that they are available - /// to all requests. - /// - public SampleActivator(string connectionString) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(connectionString); - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize Topic Repository - \-----------------------------------------------------------------------------------------------------------------------*/ - var sqlTopicRepository = new SqlTopicRepository(connectionString); - var cachedTopicRepository = new CachedTopicRepository(sqlTopicRepository); - _ = new PageTopicViewModel(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Preload repository - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = cachedTopicRepository; - _typeLookupService = new DynamicTopicViewModelLookupService(); - _topicMappingService = new TopicMappingService(_topicRepository, _typeLookupService); - _ = _topicRepository.Load(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish hierarchical topic mapping service - \-----------------------------------------------------------------------------------------------------------------------*/ - _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( - new HierarchicalTopicMappingService( - _topicRepository, - _topicMappingService - ) - ); + _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( + new HierarchicalTopicMappingService( + _topicRepository, + _topicMappingService + ) + ); - } + } - /*========================================================================================================================== - | METHOD: CREATE + /*============================================================================================================================ + | METHOD: CREATE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Registers dependencies, and injects them into new instances of controllers in response to each request. + /// + /// A concrete instance of an . + public object Create(ControllerContext context) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Registers dependencies, and injects them into new instances of controllers in response to each request. - /// - /// A concrete instance of an . - public object Create(ControllerContext context) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Determine controller type - \-----------------------------------------------------------------------------------------------------------------------*/ - var type = context.ActionDescriptor.ControllerTypeInfo.AsType(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Periodically update cache - \-----------------------------------------------------------------------------------------------------------------------*/ - if (DateTime.UtcNow > _cacheLastUpdated.AddMinutes(1)) { - var currentUpdate = DateTime.UtcNow; - _topicRepository.Refresh(_topicRepository.Load()!, _cacheLastUpdated); - _cacheLastUpdated = currentUpdate; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure and return appropriate controller - \-----------------------------------------------------------------------------------------------------------------------*/ - return type.Name switch { - nameof(TopicController) => - new TopicController(_topicRepository, _topicMappingService), - nameof(ErrorController) => - new ErrorController(_topicRepository, _topicMappingService), - nameof(SitemapController) => - new SitemapController(_topicRepository), - nameof(RedirectController) => - new RedirectController(_topicRepository), - _ => throw new InvalidOperationException($"Unknown controller {type.Name}") - }; + Contract.Requires(context, nameof(context)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine controller type + \-------------------------------------------------------------------------------------------------------------------------*/ + var type = context.ActionDescriptor.ControllerTypeInfo.AsType(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Periodically update cache + \-------------------------------------------------------------------------------------------------------------------------*/ + if (DateTime.UtcNow > _cacheLastUpdated.AddMinutes(1)) { + var currentUpdate = DateTime.UtcNow; + _topicRepository.Refresh(_topicRepository.Load()!, _cacheLastUpdated); + _cacheLastUpdated = currentUpdate; } - /// - /// Registers dependencies, and injects them into new instances of view components in response to each request. - /// - /// A concrete instance of an . - public object Create(ViewComponentContext context) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Determine view component type - \-----------------------------------------------------------------------------------------------------------------------*/ - var type = context.ViewComponentDescriptor.TypeInfo.AsType(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure and return appropriate view component - \-----------------------------------------------------------------------------------------------------------------------*/ - return type.Name switch { - nameof(MenuViewComponent) => - new MenuViewComponent(_topicRepository, _hierarchicalMappingService), - nameof(PageLevelNavigationViewComponent) => - new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService), - _ => throw new InvalidOperationException($"Unknown view component {type.Name}") - }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure and return appropriate controller + \-------------------------------------------------------------------------------------------------------------------------*/ + return type.Name switch { + nameof(TopicController) => + new TopicController(_topicRepository, _topicMappingService), + nameof(ErrorController) => + new ErrorController(_topicRepository, _topicMappingService), + nameof(SitemapController) => + new SitemapController(_topicRepository), + nameof(RedirectController) => + new RedirectController(_topicRepository), + _ => throw new InvalidOperationException($"Unknown controller {type.Name}") + }; + + } + + /// + /// Registers dependencies, and injects them into new instances of view components in response to each request. + /// + /// A concrete instance of an . + public object Create(ViewComponentContext context) { - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(context, nameof(context)); - /*========================================================================================================================== - | METHOD: RELEASE + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine view component type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Responds to a request to release resources associated with a particular controller. - /// - public void Release(ControllerContext context, object controller) { } - - /// - /// Responds to a request to release resources associated with a particular view component. - /// - public void Release(ViewComponentContext context, object viewComponent) { } - - } //Class -} //Namespace \ No newline at end of file + var type = context.ViewComponentDescriptor.TypeInfo.AsType(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure and return appropriate view component + \-------------------------------------------------------------------------------------------------------------------------*/ + return type.Name switch { + nameof(MenuViewComponent) => + new MenuViewComponent(_topicRepository, _hierarchicalMappingService), + nameof(PageLevelNavigationViewComponent) => + new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService), + _ => throw new InvalidOperationException($"Unknown view component {type.Name}") + }; + + } + + /*============================================================================================================================ + | METHOD: RELEASE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Responds to a request to release resources associated with a particular controller. + /// + public void Release(ControllerContext context, object controller) { } + + /// + /// Responds to a request to release resources associated with a particular view component. + /// + public void Release(ViewComponentContext context, object viewComponent) { } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/AreaController.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/AreaController.cs index 218c88e1..fa08c284 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/AreaController.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/AreaController.cs @@ -7,39 +7,38 @@ using OnTopic.AspNetCore.Mvc.Controllers; using OnTopic.Mapping; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Areas.Area.Controllers { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Areas.Area.Controllers; + +/*============================================================================================================================== +| CLASS: AREA CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The establishes a controller with the same name as the current area—i.e., Area—as a +/// means of testing the +/// extension method, and its underlying . +/// +[Area("Area")] +public class AreaController: TopicController { /*============================================================================================================================ - | CLASS: AREA CONTROLLER + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The establishes a controller with the same name as the current area—i.e., Area—as a - /// means of testing the - /// extension method, and its underlying . + /// Initializes a new instance of a with necessary dependencies. /// - [Area("Area")] - public class AreaController: TopicController { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - /// A for loading OnTopic views. - public AreaController( - ITopicRepository topicRepository, - ITopicMappingService topicMappingService - ): base(topicRepository, topicMappingService) {} + /// A for loading OnTopic views. + public AreaController( + ITopicRepository topicRepository, + ITopicMappingService topicMappingService + ): base(topicRepository, topicMappingService) {} - /*========================================================================================================================== - | GET: ACCORDION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named Accordion. - /// - /// A view associated with the Accordion action. - public IActionResult Accordion() => TopicView(new(), CurrentTopic!.View); + /*============================================================================================================================ + | GET: ACCORDION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named Accordion. + /// + /// A view associated with the Accordion action. + public IActionResult Accordion() => TopicView(new(), CurrentTopic!.View); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/ControllerController.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/ControllerController.cs index 5b4f2eae..63c189e7 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/ControllerController.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Areas/Area/Controllers/ControllerController.cs @@ -5,100 +5,99 @@ \=============================================================================================================================*/ using Microsoft.AspNetCore.Mvc; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Areas.Area.Controllers { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Areas.Area.Controllers; + +/*============================================================================================================================== +| CLASS: CONTROLLER CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The establishes a controller named Controller which will be used to look for +/// views located in e.g. /Views/Controller/{Action}.cshtml. The name Controller helps reinforce that it is +/// acting as a stand-in for an actual , as would be implemented in a non-test application. +/// +[Area("Area")] +public class ControllerController: Controller { /*============================================================================================================================ - | CLASS: CONTROLLER CONTROLLER + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The establishes a controller named Controller which will be used to look for - /// views located in e.g. /Views/Controller/{Action}.cshtml. The name Controller helps reinforce that it is - /// acting as a stand-in for an actual , as would be implemented in a non-test application. + /// Initializes a new instance of a . /// - [Area("Area")] - public class ControllerController: Controller { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a . - /// - /// A for exposing specific actions. - public ControllerController() {} + /// A for exposing specific actions. + public ControllerController() {} - /*========================================================================================================================== - | GET: ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named Action. - /// - /// A view associated with the Action action. - public IActionResult Action() => View(); + /*============================================================================================================================ + | GET: ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named Action. + /// + /// A view associated with the Action action. + public IActionResult Action() => View(); - /*========================================================================================================================== - | GET: FALLBACK ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named FallbackAction. - /// - /// A view associated with the FallbackAction action. - public IActionResult FallbackAction() => View(); + /*============================================================================================================================ + | GET: FALLBACK ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named FallbackAction. + /// + /// A view associated with the FallbackAction action. + public IActionResult FallbackAction() => View(); - /*========================================================================================================================== - | GET: SHARED ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named SharedAction. - /// - /// A view associated with the SharedAction action. - public IActionResult SharedAction() => View(); + /*============================================================================================================================ + | GET: SHARED ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named SharedAction. + /// + /// A view associated with the SharedAction action. + public IActionResult SharedAction() => View(); - /*========================================================================================================================== - | GET: SHARED FALLBACK ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named SharedFallbackAction. - /// - /// A view associated with the SharedFallbackAction action. - public IActionResult SharedFallbackAction() => View(); + /*============================================================================================================================ + | GET: SHARED FALLBACK ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named SharedFallbackAction. + /// + /// A view associated with the SharedFallbackAction action. + public IActionResult SharedFallbackAction() => View(); - /*========================================================================================================================== - | GET: AREA ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named AreaAction. - /// - /// A view associated with the AreaAction action. - public IActionResult AreaAction() => View(); + /*============================================================================================================================ + | GET: AREA ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named AreaAction. + /// + /// A view associated with the AreaAction action. + public IActionResult AreaAction() => View(); - /*========================================================================================================================== - | GET: AREA FALLBACK ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named AreaFallbackAction. - /// - /// A view associated with the AreaFallbackAction action. - public IActionResult AreaFallbackAction() => View(); + /*============================================================================================================================ + | GET: AREA FALLBACK ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named AreaFallbackAction. + /// + /// A view associated with the AreaFallbackAction action. + public IActionResult AreaFallbackAction() => View(); - /*========================================================================================================================== - | GET: AREA SHARED ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named AreaSharedAction. - /// - /// A view associated with the AreaSharedAction action. - public IActionResult AreaSharedAction() => View(); + /*============================================================================================================================ + | GET: AREA SHARED ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named AreaSharedAction. + /// + /// A view associated with the AreaSharedAction action. + public IActionResult AreaSharedAction() => View(); - /*========================================================================================================================== - | GET: AREA SHARED FALLBACK ACTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Exposes a method which will, by default, be associated with views named AreaSharedFallbackAction. - /// - /// A view associated with the AreaSharedFallbackAction action. - public IActionResult AreaSharedFallbackAction() => View(); + /*============================================================================================================================ + | GET: AREA SHARED FALLBACK ACTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Exposes a method which will, by default, be associated with views named AreaSharedFallbackAction. + /// + /// A view associated with the AreaSharedFallbackAction action. + public IActionResult AreaSharedFallbackAction() => View(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/AreaContentTypesViewModel.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/AreaContentTypesViewModel.cs index ae9b33bc..e9ac1d3f 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/AreaContentTypesViewModel.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/AreaContentTypesViewModel.cs @@ -4,20 +4,19 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Models { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Models; - /*============================================================================================================================ - | VIEW MODEL: AREA CONTENT TYPES - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly typed view model for a topic with the of AreaContentTypes. - /// - /// - /// This is used by the test to differentiate between content types placed in - /// /Areas/Area/ContentType/ and /Area/Area/ContentTypes/. If they used the same - /// then there would be no way to distinguish between these placements. - /// - public class AreaContentTypesViewModel { +/*============================================================================================================================== +| VIEW MODEL: AREA CONTENT TYPES +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly typed view model for a topic with the of AreaContentTypes. +/// +/// +/// This is used by the test to differentiate between content types placed in +/// /Areas/Area/ContentType/ and /Area/Area/ContentTypes/. If they used the same +/// then there would be no way to distinguish between these placements. +/// +public class AreaContentTypesViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/ContentTypeViewModel.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/ContentTypeViewModel.cs index 30b398c6..7e5ea494 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/ContentTypeViewModel.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/ContentTypeViewModel.cs @@ -4,20 +4,19 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Models { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Models; - /*============================================================================================================================ - | VIEW MODEL: CONTENT TYPE - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly typed view model for a topic with the of ContentType. - /// - /// - /// The is set to ContentType for integration tests for the purpose of reinforcing - /// the relationship between the and views; views will be named e.g. ContentType.cshtml - /// for places where they would typically use the . - /// - public class ContentTypeViewModel { +/*============================================================================================================================== +| VIEW MODEL: CONTENT TYPE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly typed view model for a topic with the of ContentType. +/// +/// +/// The is set to ContentType for integration tests for the purpose of reinforcing +/// the relationship between the and views; views will be named e.g. ContentType.cshtml +/// for places where they would typically use the . +/// +public class ContentTypeViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/MissingViewModel.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/MissingViewModel.cs index 1b90dd47..bbd98b05 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/MissingViewModel.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Models/MissingViewModel.cs @@ -4,18 +4,17 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Models { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Models; - /*============================================================================================================================ - | VIEW MODEL: MISSING - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly typed view model for a topic with the of Missing. - /// - /// - /// This is intended to test a scenario where a valid doesn't correspond to a valid view. - /// - public class MissingViewModel { +/*============================================================================================================================== +| VIEW MODEL: MISSING +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly typed view model for a topic with the of Missing. +/// +/// +/// This is intended to test a scenario where a valid doesn't correspond to a valid view. +/// +public class MissingViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/OnTopic.AspNetCore.Mvc.IntegrationTests.Host.csproj b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/OnTopic.AspNetCore.Mvc.IntegrationTests.Host.csproj index 309783aa..dce9490f 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/OnTopic.AspNetCore.Mvc.IntegrationTests.Host.csproj +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/OnTopic.AspNetCore.Mvc.IntegrationTests.Host.csproj @@ -3,6 +3,7 @@ net8.0 false + CA1515 diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Program.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Program.cs index ec3f48ca..d3a1d5a2 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Program.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Program.cs @@ -4,38 +4,37 @@ | Project Integration Tests Host \=============================================================================================================================*/ -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host; + +/*============================================================================================================================== +| CLASS: PROGRAM +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The class�and it's method�represent the entry point into the +/// ASP.NET Core web application. +/// +[ExcludeFromCodeCoverage] +public static class Program { /*============================================================================================================================ - | CLASS: PROGRAM + | METHOD: MAIN \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The class—and it's method—represent the entry point into the - /// ASP.NET Core web application. + /// Responsible for bootstrapping the web application. /// - [ExcludeFromCodeCoverage] - public static class Program { + public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); - /*========================================================================================================================== - | METHOD: MAIN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Responsible for bootstrapping the web application. - /// - public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); - - /*========================================================================================================================== - | METHOD: CREATE WEB HOST BUILDER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Configures a new with the default options. - /// - public static IHostBuilder CreateHostBuilder(string[] args) => - Microsoft.Extensions.Hosting.Host - .CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => { - webBuilder.UseStartup(); - }); + /*============================================================================================================================ + | METHOD: CREATE WEB HOST BUILDER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Configures a new with the default options. + /// + public static IHostBuilder CreateHostBuilder(string[] args) => + Microsoft.Extensions.Hosting.Host + .CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => { + webBuilder.UseStartup(); + }); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Repositories/StubTopicRepository.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Repositories/StubTopicRepository.cs index 17906860..b4fd5ab1 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Repositories/StubTopicRepository.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Repositories/StubTopicRepository.cs @@ -5,192 +5,191 @@ \=============================================================================================================================*/ using OnTopic.Querying; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host.Repositories { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host.Repositories; + +/*============================================================================================================================== +| CLASS: STUB TOPIC DATA REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides data access to topics hard-coded in this stub implementation of a . +/// +/// +/// Allows testing of services that depend on without maintaining a dependency on a live +/// database, or working against actual data. This is faster and safer for test methods since it doesn't maintain a +/// dependency on a live database or persistent data. +/// +[ExcludeFromCodeCoverage] +public class StubTopicRepository : TopicRepository, ITopicRepository { /*============================================================================================================================ - | CLASS: STUB TOPIC DATA REPOSITORY + | VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly Topic _cache; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides data access to topics hard-coded in this stub implementation of a . + /// Instantiates a new instance of the StubTopicRepository. /// - /// - /// Allows testing of services that depend on without maintaining a dependency on a live - /// database, or working against actual data. This is faster and safer for test methods since it doesn't maintain a - /// dependency on a live database or persistent data. - /// - [ExcludeFromCodeCoverage] - public class StubTopicRepository : TopicRepository, ITopicRepository { - - /*========================================================================================================================== - | VARIABLES + /// A new instance of the StubTopicRepository. + public StubTopicRepository() : base() { + _cache = CreateFakeData(); + Contract.Assume(_cache); + } + + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup by TopicId \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly Topic _cache; + var topic = _cache; + + if (topicId > 0) { + topic = _cache.FindFirst(t => t.Id.Equals(topicId)); + } - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the StubTopicRepository. - /// - /// A new instance of the StubTopicRepository. - public StubTopicRepository() : base() { - _cache = CreateFakeData(); - Contract.Assume(_cache); + if (topic != null) { + OnTopicLoaded(new(topic, isRecursive)); } - /*========================================================================================================================== - | METHOD: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup by TopicId - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = _cache; - - if (topicId > 0) { - topic = _cache.FindFirst(t => t.Id.Equals(topicId)); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic != null) { - OnTopicLoaded(new(topic, isRecursive)); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Return value - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic; + return topic; + + } + + /// + public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + if (String.IsNullOrEmpty(uniqueKey)) { + return null; } - /// - public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - if (String.IsNullOrEmpty(uniqueKey)) { - return null; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup by TopicKey - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = _cache.GetByUniqueKey(uniqueKey); - - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic != null) { - OnTopicLoaded(new(topic, isRecursive)); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Return topic - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic; + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup by TopicKey + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = _cache.GetByUniqueKey(uniqueKey); + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic != null) { + OnTopicLoaded(new(topic, isRecursive)); } - /// - public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) => - throw new NotImplementedException(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return topic + \-------------------------------------------------------------------------------------------------------------------------*/ + return topic; + + } + + /// + public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) => + throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: REFRESH + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Refresh(Topic referenceTopic, DateTime since) => + throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void SaveTopic([NotNull]Topic topic, DateTime version, bool persistRelationships) => + throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void MoveTopic(Topic topic, Topic target, Topic? sibling = null) => + throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void DeleteTopic(Topic topic) => + throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: CREATE FAKE DATA + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a collection of fake data that loosely mimics a bare bones database. + /// + private static Topic CreateFakeData() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish root \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Refresh(Topic referenceTopic, DateTime since) => - throw new NotImplementedException(); + var currentAttributeId = 1; + var rootTopic = new Topic("Root", "Container", null, currentAttributeId++); - /*========================================================================================================================== - | METHOD: SAVE + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void SaveTopic([NotNull]Topic topic, DateTime version, bool persistRelationships) => - throw new NotImplementedException(); + var web = new Topic("Web", "Page", rootTopic, currentAttributeId++); + _ = new Topic("ContentList", "ContentList", web, currentAttributeId++); + _ = new Topic("MissingView", "Missing", web, currentAttributeId++); + _ = new Topic("Container", "Container", web, currentAttributeId++); - /*========================================================================================================================== - | METHOD: MOVE + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish area topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void MoveTopic(Topic topic, Topic target, Topic? sibling = null) => - throw new NotImplementedException(); + var area = new Topic("Area", "ContentType", rootTopic, currentAttributeId++); + + _ = new Topic("AreaContentTypes", "AreaContentTypes", area, currentAttributeId++); + _ = new Topic("Accordion", "ContentList", area, currentAttributeId++); + + _ = new Topic("TopicWithView", "ContentList", area, currentAttributeId++) { + View = "Accordion" + }; - /*========================================================================================================================== - | METHOD: DELETE + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish error topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void DeleteTopic(Topic topic) => - throw new NotImplementedException(); + var error = new Topic("Error", "Page", rootTopic, currentAttributeId++); - /*========================================================================================================================== - | METHOD: CREATE FAKE DATA + _ = new Topic("400", "Page", error, currentAttributeId++); + _ = new Topic("Unauthorized", "Page", error, currentAttributeId++); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish caching tests \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a collection of fake data that loosely mimics a bare bones database. - /// - private static Topic CreateFakeData() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish root - \-----------------------------------------------------------------------------------------------------------------------*/ - var currentAttributeId = 1; - var rootTopic = new Topic("Root", "Container", null, currentAttributeId++); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var web = new Topic("Web", "Page", rootTopic, currentAttributeId++); - _ = new Topic("ContentList", "ContentList", web, currentAttributeId++); - _ = new Topic("MissingView", "Missing", web, currentAttributeId++); - _ = new Topic("Container", "Container", web, currentAttributeId++); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish area topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var area = new Topic("Area", "ContentType", rootTopic, currentAttributeId++); - - _ = new Topic("AreaContentTypes", "AreaContentTypes", area, currentAttributeId++); - _ = new Topic("Accordion", "ContentList", area, currentAttributeId++); - - _ = new Topic("TopicWithView", "ContentList", area, currentAttributeId++) { - View = "Accordion" - }; - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish error topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var error = new Topic("Error", "Page", rootTopic, currentAttributeId++); - - _ = new Topic("400", "Page", error, currentAttributeId++); - _ = new Topic("Unauthorized", "Page", error, currentAttributeId++); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish caching tests - \-----------------------------------------------------------------------------------------------------------------------*/ - var cacheProfile = new Topic("CacheProfile", "CacheProfile", rootTopic, currentAttributeId++); - var cachedPage = new Topic("CachedPage", "Page", web, currentAttributeId++); - var uncachedPage = new Topic("UncachedPage", "Page", web, currentAttributeId++); - - cacheProfile.Attributes.SetValue("Duration", "10"); - cacheProfile.Attributes.SetValue("Location", "Any"); - - cachedPage.References.SetValue("CacheProfile", cacheProfile); - cachedPage.Attributes.SetValue("View", "Counter"); - - uncachedPage.Attributes.SetValue("View", "Counter"); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set to cache - \-----------------------------------------------------------------------------------------------------------------------*/ - return rootTopic; + var cacheProfile = new Topic("CacheProfile", "CacheProfile", rootTopic, currentAttributeId++); + var cachedPage = new Topic("CachedPage", "Page", web, currentAttributeId++); + var uncachedPage = new Topic("UncachedPage", "Page", web, currentAttributeId++); - } + cacheProfile.Attributes.SetValue("Duration", "10"); + cacheProfile.Attributes.SetValue("Location", "Any"); + + cachedPage.References.SetValue("CacheProfile", cacheProfile); + cachedPage.Attributes.SetValue("View", "Counter"); + + uncachedPage.Attributes.SetValue("View", "Counter"); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set to cache + \-------------------------------------------------------------------------------------------------------------------------*/ + return rootTopic; + + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/SampleActivator.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/SampleActivator.cs index 837dda39..93e19bff 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/SampleActivator.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/SampleActivator.cs @@ -15,147 +15,146 @@ using OnTopic.Mapping.Hierarchical; using OnTopic.ViewModels; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host; + +/*============================================================================================================================== +| CLASS: SAMPLE ACTIVATOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Responsible for creating instances of factories in response to web requests. Represents the Composition Root for +/// Dependency Injection. +/// +[ExcludeFromCodeCoverage] +public class SampleActivator : IControllerActivator, IViewComponentActivator { /*============================================================================================================================ - | CLASS: SAMPLE ACTIVATOR + | PRIVATE INSTANCES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ITypeLookupService _typeLookupService; + private readonly ITopicMappingService _topicMappingService; + private readonly ITopicRepository _topicRepository; + + /*============================================================================================================================ + | HIERARCHICAL TOPIC MAPPING SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new instance of the , including any shared dependencies to be used across + /// instances of controllers. + /// + /// + /// The constructor is responsible for establishing dependencies with the singleton lifestyle so that they are available + /// to all requests. + /// + public SampleActivator() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize Topic Repository + \-------------------------------------------------------------------------------------------------------------------------*/ + var sqlTopicRepository = new StubTopicRepository(); + var cachedTopicRepository = new CachedTopicRepository(sqlTopicRepository); + _ = new PageTopicViewModel(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Preload repository + \-------------------------------------------------------------------------------------------------------------------------*/ + _topicRepository = cachedTopicRepository; + _typeLookupService = new DynamicTopicViewModelLookupService(); + _topicMappingService = new TopicMappingService(_topicRepository, _typeLookupService); + _ = _topicRepository.Load(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish hierarchical topic mapping service + \-------------------------------------------------------------------------------------------------------------------------*/ + _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( + new HierarchicalTopicMappingService( + _topicRepository, + _topicMappingService + ) + ); + + } + + /*============================================================================================================================ + | METHOD: CREATE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Responsible for creating instances of factories in response to web requests. Represents the Composition Root for - /// Dependency Injection. + /// Registers dependencies, and injects them into new instances of controllers in response to each request. /// - [ExcludeFromCodeCoverage] - public class SampleActivator : IControllerActivator, IViewComponentActivator { + /// A concrete instance of an . + public object Create(ControllerContext context) { - /*========================================================================================================================== - | PRIVATE INSTANCES + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITypeLookupService _typeLookupService; - private readonly ITopicMappingService _topicMappingService; - private readonly ITopicRepository _topicRepository; + Contract.Requires(context, nameof(context)); - /*========================================================================================================================== - | HIERARCHICAL TOPIC MAPPING SERVICE + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine controller type \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + var type = context.ActionDescriptor.ControllerTypeInfo.AsType(); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure and return appropriate controller \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of the , including any shared dependencies to be used across - /// instances of controllers. - /// - /// - /// The constructor is responsible for establishing dependencies with the singleton lifestyle so that they are available - /// to all requests. - /// - public SampleActivator() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize Topic Repository - \-----------------------------------------------------------------------------------------------------------------------*/ - var sqlTopicRepository = new StubTopicRepository(); - var cachedTopicRepository = new CachedTopicRepository(sqlTopicRepository); - _ = new PageTopicViewModel(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Preload repository - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = cachedTopicRepository; - _typeLookupService = new DynamicTopicViewModelLookupService(); - _topicMappingService = new TopicMappingService(_topicRepository, _typeLookupService); - _ = _topicRepository.Load(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish hierarchical topic mapping service - \-----------------------------------------------------------------------------------------------------------------------*/ - _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( - new HierarchicalTopicMappingService( - _topicRepository, - _topicMappingService - ) - ); - - } - - /*========================================================================================================================== - | METHOD: CREATE + return type.Name switch { + nameof(TopicController) => + new TopicController(_topicRepository, _topicMappingService), + nameof(AreaController) => + new AreaController(_topicRepository, _topicMappingService), + nameof(ErrorController) => + new ErrorController(_topicRepository, _topicMappingService), + nameof(ControllerController) => + new ControllerController(), + nameof(SitemapController) => + new SitemapController(_topicRepository), + nameof(RedirectController) => + new RedirectController(_topicRepository), + _ => throw new InvalidOperationException($"Unknown controller {type.Name}") + }; + + } + + /// + /// Registers dependencies, and injects them into new instances of view components in response to each request. + /// + /// A concrete instance of an . + public object Create(ViewComponentContext context) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Registers dependencies, and injects them into new instances of controllers in response to each request. - /// - /// A concrete instance of an . - public object Create(ControllerContext context) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Determine controller type - \-----------------------------------------------------------------------------------------------------------------------*/ - var type = context.ActionDescriptor.ControllerTypeInfo.AsType(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure and return appropriate controller - \-----------------------------------------------------------------------------------------------------------------------*/ - return type.Name switch { - nameof(TopicController) => - new TopicController(_topicRepository, _topicMappingService), - nameof(AreaController) => - new AreaController(_topicRepository, _topicMappingService), - nameof(ErrorController) => - new ErrorController(_topicRepository, _topicMappingService), - nameof(ControllerController) => - new ControllerController(), - nameof(SitemapController) => - new SitemapController(_topicRepository), - nameof(RedirectController) => - new RedirectController(_topicRepository), - _ => throw new InvalidOperationException($"Unknown controller {type.Name}") - }; - - } - - /// - /// Registers dependencies, and injects them into new instances of view components in response to each request. - /// - /// A concrete instance of an . - public object Create(ViewComponentContext context) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Determine view component type - \-----------------------------------------------------------------------------------------------------------------------*/ - var type = context.ViewComponentDescriptor.TypeInfo.AsType(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure and return appropriate view component - \-----------------------------------------------------------------------------------------------------------------------*/ - return type.Name switch { - _ => throw new InvalidOperationException($"Unknown view component {type.Name}") - }; - - } - - /*========================================================================================================================== - | METHOD: RELEASE + Contract.Requires(context, nameof(context)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine view component type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Responds to a request to release resources associated with a particular controller. - /// - public void Release(ControllerContext context, object controller) { } - - /// - /// Responds to a request to release resources associated with a particular view component. - /// - public void Release(ViewComponentContext context, object viewComponent) { } - - } //Class -} //Namespace \ No newline at end of file + var type = context.ViewComponentDescriptor.TypeInfo.AsType(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure and return appropriate view component + \-------------------------------------------------------------------------------------------------------------------------*/ + return type.Name switch { + _ => throw new InvalidOperationException($"Unknown view component {type.Name}") + }; + + } + + /*============================================================================================================================ + | METHOD: RELEASE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Responds to a request to release resources associated with a particular controller. + /// + public void Release(ControllerContext context, object controller) { } + + /// + /// Responds to a request to release resources associated with a particular view component. + /// + public void Release(ViewComponentContext context, object viewComponent) { } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Startup.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Startup.cs index 69514be5..ecc309f8 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Startup.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests.Host/Startup.cs @@ -6,108 +6,107 @@ using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ViewComponents; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests.Host; + +/*============================================================================================================================== +| CLASS: STARTUP +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Configures the application and sets up dependencies. +/// +[ExcludeFromCodeCoverage] +public class Startup { /*============================================================================================================================ - | CLASS: STARTUP + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Configures the application and sets up dependencies. + /// Constructs a new instances of the class. Accepts an . /// - [ExcludeFromCodeCoverage] - public class Startup { + /// + /// The shared dependency. + /// + public Startup(IConfiguration configuration) { + Configuration = configuration; + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new instances of the class. Accepts an . - /// - /// - /// The shared dependency. - /// - public Startup(IConfiguration configuration) { - Configuration = configuration; - } - - /*========================================================================================================================== - | PROPERTY: CONFIGURATION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a (public) reference to the application's service. - /// - public IConfiguration Configuration { get; } + /*============================================================================================================================ + | PROPERTY: CONFIGURATION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a (public) reference to the application's service. + /// + public IConfiguration Configuration { get; } + + /*============================================================================================================================ + | METHOD: CONFIGURE SERVICES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides configuration of services. This method is called by the runtime to bootstrap the server configuration. + /// + public void ConfigureServices(IServiceCollection services) { + + /*------------------------------------------------------------------------------------------------------------------------------ + | Configure: Output Caching + \-----------------------------------------------------------------------------------------------------------------------------*/ + services.AddResponseCaching(); - /*========================================================================================================================== - | METHOD: CONFIGURE SERVICES + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure: MVC \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides configuration of services. This method is called by the runtime to bootstrap the server configuration. - /// - public void ConfigureServices(IServiceCollection services) { + services.AddControllersWithViews() - /*------------------------------------------------------------------------------------------------------------------------------ - | Configure: Output Caching - \-----------------------------------------------------------------------------------------------------------------------------*/ - services.AddResponseCaching(); + //Add OnTopic support + .AddTopicSupport(); - /*------------------------------------------------------------------------------------------------------------------------ - | Configure: MVC - \-----------------------------------------------------------------------------------------------------------------------*/ - services.AddControllersWithViews() + /*-------------------------------------------------------------------------------------------------------------------------- + | Register: Activators + \-------------------------------------------------------------------------------------------------------------------------*/ + var activator = new SampleActivator(); - //Add OnTopic support - .AddTopicSupport(); + services.AddSingleton(activator); + services.AddSingleton(activator); - /*------------------------------------------------------------------------------------------------------------------------ - | Register: Activators - \-----------------------------------------------------------------------------------------------------------------------*/ - var activator = new SampleActivator(); + } - services.AddSingleton(activator); - services.AddSingleton(activator); + /*============================================================================================================================ + | METHOD: CONFIGURE (APPLICATION) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides configuration the application. This method is called by the runtime to bootstrap the application + /// configuration, including the HTTP pipeline. + /// + public static void Configure(IApplicationBuilder app) { - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure: Error Pages + \-------------------------------------------------------------------------------------------------------------------------*/ + app.UseDeveloperExceptionPage(); + app.UseStatusCodePagesWithReExecute("/Error/{0}/"); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure: Server defaults + \-------------------------------------------------------------------------------------------------------------------------*/ + app.UseStaticFiles(); + app.UseRouting(); + app.UseResponseCaching(); - /*========================================================================================================================== - | METHOD: CONFIGURE (APPLICATION) + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure: MVC \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides configuration the application. This method is called by the runtime to bootstrap the application - /// configuration, including the HTTP pipeline. - /// - public static void Configure(IApplicationBuilder app) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure: Error Pages - \-----------------------------------------------------------------------------------------------------------------------*/ - app.UseDeveloperExceptionPage(); - app.UseStatusCodePagesWithReExecute("/Error/{0}/"); - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure: Server defaults - \-----------------------------------------------------------------------------------------------------------------------*/ - app.UseStaticFiles(); - app.UseRouting(); - app.UseResponseCaching(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure: MVC - \-----------------------------------------------------------------------------------------------------------------------*/ - app.UseEndpoints(endpoints => { - endpoints.MapTopicErrors(includeStaticFiles: false); - endpoints.MapDefaultAreaControllerRoute(); - endpoints.MapDefaultControllerRoute(); - endpoints.MapImplicitAreaControllerRoute(); - endpoints.MapTopicAreaRoute(); - endpoints.MapTopicRoute("Web"); - endpoints.MapTopicRoute("Error"); - endpoints.MapTopicSitemap(); - endpoints.MapTopicRedirect(); - endpoints.MapControllers(); - }); - - } - - } //Class -} //Namespace \ No newline at end of file + app.UseEndpoints(endpoints => { + endpoints.MapTopicErrors(includeStaticFiles: false); + endpoints.MapDefaultAreaControllerRoute(); + endpoints.MapDefaultControllerRoute(); + endpoints.MapImplicitAreaControllerRoute(); + endpoints.MapTopicAreaRoute(); + endpoints.MapTopicRoute("Web"); + endpoints.MapTopicRoute("Error"); + endpoints.MapTopicSitemap(); + endpoints.MapTopicRedirect(); + endpoints.MapControllers(); + }); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests/OnTopic.AspNetCore.Mvc.IntegrationTests.csproj b/OnTopic.AspNetCore.Mvc.IntegrationTests/OnTopic.AspNetCore.Mvc.IntegrationTests.csproj index fcd12aa9..3b6496f5 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests/OnTopic.AspNetCore.Mvc.IntegrationTests.csproj +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests/OnTopic.AspNetCore.Mvc.IntegrationTests.csproj @@ -4,6 +4,7 @@ net8.0 Exe false + CA1515 diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests/ServiceCollectionExtensionsTests.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests/ServiceCollectionExtensionsTests.cs index 2ca3fba4..04f3da61 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests/ServiceCollectionExtensionsTests.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests/ServiceCollectionExtensionsTests.cs @@ -7,146 +7,145 @@ using System.Net; using Microsoft.AspNetCore.Routing; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests; + +/*============================================================================================================================== +| TEST: SERVICE COLLECTION EXTENSIONS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The are responsible, primarily, for establishing routes based on the interface. These integration tests validate that those routes are operating as expected. +/// +[Collection("Web Application")] +public class ServiceCollectionExtensionsTests: IClassFixture> { /*============================================================================================================================ - | TEST: SERVICE COLLECTION EXTENSIONS + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly WebApplicationFactory _factory; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the . + /// + public ServiceCollectionExtensionsTests(WebApplicationFactory factory) { + _factory = factory; + } + + /*============================================================================================================================ + | TEST: REQUEST PAGE: EXPECTED RESULTS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Evaluates various routes enabled by the routing extension methods to ensure they correctly map to the expected + /// controllers, actions, and views. + /// + [Theory] + [InlineData("/Web/ContentList/", "~/Views/ContentList/ContentList.cshtml")] // MapTopicRoute() + [InlineData("/Area/Area/", "~/Areas/Area/Views/ContentType/ContentType.cshtml")] // MapTopicAreaRoute() + [InlineData("/Area/Controller/AreaAction/", "~/Areas/Area/Views/Controller/AreaAction.cshtml")] // MapTopicAreaRoute() + [InlineData("/Area/Accordion/", "~/Views/ContentList/Accordion.cshtml")] // MapImplicitAreaControllerRoute() + [InlineData("/Topic/3/", "~/Views/ContentList/ContentList.cshtml")] // MapTopicRedirect() + [InlineData("/Error/404", "400")] // MapTopicErrors() + [InlineData("/Error/Http/404", "400")] // MapDefaultControllerRoute() + [InlineData("/Error/Unauthorized/", "Unauthorized")] // MapTopicRoute() + public async Task RequestPage_ExpectedResults(string path, string expectedContent) { + + var client = _factory.CreateClient(); + var uri = new Uri(path, UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var actualContent = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + response.EnsureSuccessStatusCode(); + + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal(expectedContent, actualContent); + + } + + /*============================================================================================================================ + | TEST: MAP TOPIC SITEMAP: RESPONDS TO REQUEST + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Evaluates a route associated with and + /// confirms that it responds appropriately. + /// + [Fact] + public async Task MapTopicSitemap_RespondsToRequest() { + + var client = _factory.CreateClient(); + var uri = new Uri($"/Sitemap/", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + response.EnsureSuccessStatusCode(); + + Assert.Equal("text/xml", response.Content.Headers.ContentType?.ToString()); + Assert.True(content.Contains("/Web/ContentList/", StringComparison.OrdinalIgnoreCase)); + + } + + /*============================================================================================================================ + | TEST: USE STATUS CODE PAGES: RETURNS EXPECTED STATUS CODE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Evaluates a route with an error, and confirms that it returns a page with the expected status code. + /// + [Theory] + [InlineData("/MissingPage/", HttpStatusCode.NotFound, "400")] + [InlineData("/Web/MissingPage/", HttpStatusCode.NotFound, "400")] + [InlineData("/Web/Container/", HttpStatusCode.Forbidden, "400")] + [InlineData("/Scripts/ECMAScript.js", HttpStatusCode.NotFound, "The resource requested could not found.")] + public async Task UseStatusCodePages_ReturnsExpectedStatusCode(string path, HttpStatusCode statusCode, string expectedContent) { + + var client = _factory.CreateClient(); + var uri = new Uri(path, UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var actualContent = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + Assert.Equal(statusCode, response.StatusCode); + Assert.Equal(expectedContent, actualContent); + + } + + /*============================================================================================================================ + | TEST: USE RESPONSE CACHING: RETURNS CACHED PAGE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The are responsible, primarily, for establishing routes based on the interface. These integration tests validate that those routes are operating as expected. + /// Evaluates a route with response caching, and confirms that the page remains unchanged after subsequent calls. /// - [Collection("Web Application")] - public class ServiceCollectionExtensionsTests: IClassFixture> { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly WebApplicationFactory _factory; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - public ServiceCollectionExtensionsTests(WebApplicationFactory factory) { - _factory = factory; - } - - /*========================================================================================================================== - | TEST: REQUEST PAGE: EXPECTED RESULTS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates various routes enabled by the routing extension methods to ensure they correctly map to the expected - /// controllers, actions, and views. - /// - [Theory] - [InlineData("/Web/ContentList/", "~/Views/ContentList/ContentList.cshtml")] // MapTopicRoute() - [InlineData("/Area/Area/", "~/Areas/Area/Views/ContentType/ContentType.cshtml")] // MapTopicAreaRoute() - [InlineData("/Area/Controller/AreaAction/", "~/Areas/Area/Views/Controller/AreaAction.cshtml")] // MapTopicAreaRoute() - [InlineData("/Area/Accordion/", "~/Views/ContentList/Accordion.cshtml")] // MapImplicitAreaControllerRoute() - [InlineData("/Topic/3/", "~/Views/ContentList/ContentList.cshtml")] // MapTopicRedirect() - [InlineData("/Error/404", "400")] // MapTopicErrors() - [InlineData("/Error/Http/404", "400")] // MapDefaultControllerRoute() - [InlineData("/Error/Unauthorized/", "Unauthorized")] // MapTopicRoute() - public async Task RequestPage_ExpectedResults(string path, string expectedContent) { - - var client = _factory.CreateClient(); - var uri = new Uri(path, UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var actualContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - response.EnsureSuccessStatusCode(); - - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal(expectedContent, actualContent); - - } - - /*========================================================================================================================== - | TEST: MAP TOPIC SITEMAP: RESPONDS TO REQUEST - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates a route associated with and - /// confirms that it responds appropriately. - /// - [Fact] - public async Task MapTopicSitemap_RespondsToRequest() { - - var client = _factory.CreateClient(); - var uri = new Uri($"/Sitemap/", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - response.EnsureSuccessStatusCode(); - - Assert.Equal("text/xml", response.Content.Headers.ContentType?.ToString()); - Assert.True(content.Contains("/Web/ContentList/", StringComparison.OrdinalIgnoreCase)); - - } - - /*========================================================================================================================== - | TEST: USE STATUS CODE PAGES: RETURNS EXPECTED STATUS CODE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates a route with an error, and confirms that it returns a page with the expected status code. - /// - [Theory] - [InlineData("/MissingPage/", HttpStatusCode.NotFound, "400")] - [InlineData("/Web/MissingPage/", HttpStatusCode.NotFound, "400")] - [InlineData("/Web/Container/", HttpStatusCode.Forbidden, "400")] - [InlineData("/Scripts/ECMAScript.js", HttpStatusCode.NotFound, "The resource requested could not found.")] - public async Task UseStatusCodePages_ReturnsExpectedStatusCode(string path, HttpStatusCode statusCode, string expectedContent) { - - var client = _factory.CreateClient(); - var uri = new Uri(path, UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var actualContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - Assert.Equal(statusCode, response.StatusCode); - Assert.Equal(expectedContent, actualContent); - - } - - /*========================================================================================================================== - | TEST: USE RESPONSE CACHING: RETURNS CACHED PAGE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates a route with response caching, and confirms that the page remains unchanged after subsequent calls. - /// - /// - /// The Counter.cshtml page will increment a number output for every request to a given path. The CachedPage - /// request will not increment because the cached result is being returned; the UncachedPage will increment because - /// the results are not cached. - /// - [Theory] - [InlineData("/Web/CachedPage/", "1", "1", true)] - [InlineData("/Web/UncachedPage/", "1", "2", false)] - public async Task UseResponseCaching_ReturnsCachedPage( - string path, - string firstResult, - string secondResult, - bool validateHeaders - ) { - - var client = _factory.CreateClient(); - var uri = new Uri(path, UriKind.Relative); - - var response1 = await client.GetAsync(uri).ConfigureAwait(false); - var content1 = await response1.Content.ReadAsStringAsync().ConfigureAwait(false); - - var response2 = await client.GetAsync(uri).ConfigureAwait(false); - var content2 = await response2.Content.ReadAsStringAsync().ConfigureAwait(false); - - response1.EnsureSuccessStatusCode(); - - Assert.StartsWith(firstResult, content1, StringComparison.Ordinal); - Assert.StartsWith(secondResult, content2, StringComparison.Ordinal); - Assert.Equal(validateHeaders? true : null, response1.Headers.CacheControl?.Public); - Assert.Equal(validateHeaders? TimeSpan.FromSeconds(10) : null, response1?.Headers.CacheControl?.MaxAge); - - } - - } //Class -} //Namespace \ No newline at end of file + /// + /// The Counter.cshtml page will increment a number output for every request to a given path. The CachedPage + /// request will not increment because the cached result is being returned; the UncachedPage will increment because + /// the results are not cached. + /// + [Theory] + [InlineData("/Web/CachedPage/", "1", "1", true)] + [InlineData("/Web/UncachedPage/", "1", "2", false)] + public async Task UseResponseCaching_ReturnsCachedPage( + string path, + string firstResult, + string secondResult, + bool validateHeaders + ) { + + var client = _factory.CreateClient(); + var uri = new Uri(path, UriKind.Relative); + + var response1 = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content1 = await response1.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + var response2 = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content2 = await response2.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + response1.EnsureSuccessStatusCode(); + + Assert.StartsWith(firstResult, content1, StringComparison.Ordinal); + Assert.StartsWith(secondResult, content2, StringComparison.Ordinal); + Assert.Equal(validateHeaders? true : null, response1.Headers.CacheControl?.Public); + Assert.Equal(validateHeaders? TimeSpan.FromSeconds(10) : null, response1?.Headers.CacheControl?.MaxAge); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewLocationExpanderTest.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewLocationExpanderTest.cs index 5f7ab057..3328dabe 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewLocationExpanderTest.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewLocationExpanderTest.cs @@ -5,112 +5,111 @@ \=============================================================================================================================*/ using OnTopic.AspNetCore.Mvc.IntegrationTests.Areas.Area.Controllers; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests; + +/*============================================================================================================================== +| TEST: TOPIC VIEW LOCATION EXPANDER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The is responsible for locating whether a view exists based on a set of file +/// path conventions. This test evaluates those to ensure that view locations are being correctly evaluated based on those +/// conventions. +/// +[Collection("Web Application")] +public class TopicViewLocationExpanderTest: IClassFixture> { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly WebApplicationFactory _factory; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the . + /// + public TopicViewLocationExpanderTest(WebApplicationFactory factory) { + _factory = factory; + } /*============================================================================================================================ - | TEST: TOPIC VIEW LOCATION EXPANDER + | TEST: EXPAND VIEW LOCATIONS: VIEWS \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The is responsible for locating whether a view exists based on a set of file - /// path conventions. This test evaluates those to ensure that view locations are being correctly evaluated based on those - /// conventions. + /// Evaluates multiple views to ensure they fallback to the appropriate locations as defined in and . /// - [Collection("Web Application")] - public class TopicViewLocationExpanderTest: IClassFixture> { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly WebApplicationFactory _factory; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - public TopicViewLocationExpanderTest(WebApplicationFactory factory) { - _factory = factory; + [Theory] + [InlineData( "AreaContentTypeView", "ContentType/AreaContentTypeView.cshtml")] + [InlineData( "AreaContentTypeSharedView", "ContentType/Shared/AreaContentTypeSharedView.cshtml")] + [InlineData( "AreaContentTypesView", "ContentTypes/ContentType.AreaContentTypesView.cshtml")] + [InlineData( "AreaContentTypesSharedView", "ContentTypes/Shared/AreaContentTypesSharedView.cshtml")] + [InlineData( "AreaContentTypesFallbackView", "ContentTypes/AreaContentTypesFallbackView.cshtml")] + [InlineData( "AreaSharedView", "Shared/AreaSharedView.cshtml")] + [InlineData( "ContentTypeView", "ContentType/ContentTypeView.cshtml")] + [InlineData( "ContentTypeSharedView", "ContentType/Shared/ContentTypeSharedView.cshtml")] + [InlineData( "ContentTypesView", "ContentTypes/ContentType.ContentTypesView.cshtml")] + [InlineData( "ContentTypesSharedView", "ContentTypes/Shared/ContentTypesSharedView.cshtml")] + [InlineData( "ContentTypesFallbackView", "ContentTypes/ContentTypesFallbackView.cshtml")] + [InlineData( "SharedView", "Shared/SharedView.cshtml")] + public async Task ExpandViewLocations_Views(string viewName, string viewLocation) { + + if (viewName is not null && viewName.StartsWith("Area", StringComparison.OrdinalIgnoreCase)) { + viewLocation = $"~/Areas/Area/Views/{viewLocation}"; + } + else { + viewLocation = $"~/Views/{viewLocation}"; } - /*========================================================================================================================== - | TEST: EXPAND VIEW LOCATIONS: VIEWS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates multiple views to ensure they fallback to the appropriate locations as defined in and . - /// - [Theory] - [InlineData( "AreaContentTypeView", "ContentType/AreaContentTypeView.cshtml")] - [InlineData( "AreaContentTypeSharedView", "ContentType/Shared/AreaContentTypeSharedView.cshtml")] - [InlineData( "AreaContentTypesView", "ContentTypes/ContentType.AreaContentTypesView.cshtml")] - [InlineData( "AreaContentTypesSharedView", "ContentTypes/Shared/AreaContentTypesSharedView.cshtml")] - [InlineData( "AreaContentTypesFallbackView", "ContentTypes/AreaContentTypesFallbackView.cshtml")] - [InlineData( "AreaSharedView", "Shared/AreaSharedView.cshtml")] - [InlineData( "ContentTypeView", "ContentType/ContentTypeView.cshtml")] - [InlineData( "ContentTypeSharedView", "ContentType/Shared/ContentTypeSharedView.cshtml")] - [InlineData( "ContentTypesView", "ContentTypes/ContentType.ContentTypesView.cshtml")] - [InlineData( "ContentTypesSharedView", "ContentTypes/Shared/ContentTypesSharedView.cshtml")] - [InlineData( "ContentTypesFallbackView", "ContentTypes/ContentTypesFallbackView.cshtml")] - [InlineData( "SharedView", "Shared/SharedView.cshtml")] - public async Task ExpandViewLocations_Views(string viewName, string viewLocation) { - - if (viewName is not null && viewName.StartsWith("Area", StringComparison.OrdinalIgnoreCase)) { - viewLocation = $"~/Areas/Area/Views/{viewLocation}"; - } - else { - viewLocation = $"~/Views/{viewLocation}"; - } - - var client = _factory.CreateClient(); - var uri = new Uri($"/Area/?View={viewName}", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - response.EnsureSuccessStatusCode(); - - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal(viewLocation, content); + var client = _factory.CreateClient(); + var uri = new Uri($"/Area/?View={viewName}", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); - } + response.EnsureSuccessStatusCode(); + + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal(viewLocation, content); - /*========================================================================================================================== - | TEST: EXPAND VIEW LOCATIONS: ACTIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates multiple actions off of the to ensure they fallback to the appropriate - /// locations as defined in and . - /// - [Theory] - [InlineData( "AreaAction", "Controller/AreaAction.cshtml")] - [InlineData( "AreaFallbackAction", "AreaFallbackAction.cshtml")] - [InlineData( "AreaSharedAction", "Controller/Shared/AreaSharedAction.cshtml")] - [InlineData( "AreaSharedFallbackAction", "Shared/AreaSharedFallbackAction.cshtml")] - [InlineData( "Action", "Controller/Action.cshtml")] - [InlineData( "FallbackAction", "FallbackAction.cshtml")] - [InlineData( "SharedAction", "Controller/Shared/SharedAction.cshtml")] - [InlineData( "SharedFallbackAction", "Shared/SharedFallbackAction.cshtml")] - public async Task ExpandViewLocations_Actions(string viewName, string viewLocation) { - - if (viewName is not null && viewName.StartsWith("Area", StringComparison.OrdinalIgnoreCase)) { - viewLocation = $"~/Areas/Area/Views/{viewLocation}"; - } - else { - viewLocation = $"~/Views/{viewLocation}"; - } - - var client = _factory.CreateClient(); - var uri = new Uri($"/Area/Controller/{viewName}/", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - response.EnsureSuccessStatusCode(); - - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal(viewLocation, content); + } + /*============================================================================================================================ + | TEST: EXPAND VIEW LOCATIONS: ACTIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Evaluates multiple actions off of the to ensure they fallback to the appropriate + /// locations as defined in and . + /// + [Theory] + [InlineData( "AreaAction", "Controller/AreaAction.cshtml")] + [InlineData( "AreaFallbackAction", "AreaFallbackAction.cshtml")] + [InlineData( "AreaSharedAction", "Controller/Shared/AreaSharedAction.cshtml")] + [InlineData( "AreaSharedFallbackAction", "Shared/AreaSharedFallbackAction.cshtml")] + [InlineData( "Action", "Controller/Action.cshtml")] + [InlineData( "FallbackAction", "FallbackAction.cshtml")] + [InlineData( "SharedAction", "Controller/Shared/SharedAction.cshtml")] + [InlineData( "SharedFallbackAction", "Shared/SharedFallbackAction.cshtml")] + public async Task ExpandViewLocations_Actions(string viewName, string viewLocation) { + + if (viewName is not null && viewName.StartsWith("Area", StringComparison.OrdinalIgnoreCase)) { + viewLocation = $"~/Areas/Area/Views/{viewLocation}"; + } + else { + viewLocation = $"~/Views/{viewLocation}"; } + var client = _factory.CreateClient(); + var uri = new Uri($"/Area/Controller/{viewName}/", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + response.EnsureSuccessStatusCode(); + + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal(viewLocation, content); + } + } \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewResultExecutorTest.cs b/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewResultExecutorTest.cs index c0729621..439c4c1a 100644 --- a/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewResultExecutorTest.cs +++ b/OnTopic.AspNetCore.Mvc.IntegrationTests/TopicViewResultExecutorTest.cs @@ -5,162 +5,161 @@ \=============================================================================================================================*/ using System.Net; -namespace OnTopic.AspNetCore.Mvc.IntegrationTests { +namespace OnTopic.AspNetCore.Mvc.IntegrationTests; + +/*============================================================================================================================== +| TEST: TOPIC VIEW RESULT EXECUTOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The is responsible for identifying the view based on a variety of sources, +/// including the query string, HTTP request headers, , etc. This test evaluates those to ensure +/// that views are being correctly identified based on these criteria. +/// +[Collection("Web Application")] +public class TopicViewResultExecutorTest: IClassFixture> { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly WebApplicationFactory _factory; /*============================================================================================================================ - | TEST: TOPIC VIEW RESULT EXECUTOR + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The is responsible for identifying the view based on a variety of sources, - /// including the query string, HTTP request headers, , etc. This test evaluates those to ensure - /// that views are being correctly identified based on these criteria. + /// Initializes a new instance of the . /// - [Collection("Web Application")] - public class TopicViewResultExecutorTest: IClassFixture> { + public TopicViewResultExecutorTest(WebApplicationFactory factory) { + _factory = factory; + } - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly WebApplicationFactory _factory; + /*============================================================================================================================ + | TEST: QUERY STRING: RETURNS EXPECTED VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a test with a query string parameter to ensure that the expected view is returned. + /// + [Fact] + public async Task QueryString_ReturnsExpectedView() { - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - public TopicViewResultExecutorTest(WebApplicationFactory factory) { - _factory = factory; - } - - /*========================================================================================================================== - | TEST: QUERY STRING: RETURNS EXPECTED VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a test with a query string parameter to ensure that the expected view is returned. - /// - [Fact] - public async Task QueryString_ReturnsExpectedView() { + var client = _factory.CreateClient(); + var uri = new Uri("/Web/ContentList/?View=Accordion", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); - var client = _factory.CreateClient(); - var uri = new Uri("/Web/ContentList/?View=Accordion", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - response.EnsureSuccessStatusCode(); - - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); - - } - - /*========================================================================================================================== - | TEST: HEADER: RETURNS EXPECTED VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a test with a request header to ensure that the expected view is returned. - /// - [Fact] - public async Task Header_ReturnsExpectedView() { + response.EnsureSuccessStatusCode(); - var client = _factory.CreateClient(); + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); - client.DefaultRequestHeaders.Add("Accept", "application/json, string/Accordion;level=2;q=0.4, text/html"); + } - var uri = new Uri("/Web/ContentList/", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + /*============================================================================================================================ + | TEST: HEADER: RETURNS EXPECTED VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a test with a request header to ensure that the expected view is returned. + /// + [Fact] + public async Task Header_ReturnsExpectedView() { - response.EnsureSuccessStatusCode(); + var client = _factory.CreateClient(); - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); + client.DefaultRequestHeaders.Add("Accept", "application/json, string/Accordion;level=2;q=0.4, text/html"); - } + var uri = new Uri("/Web/ContentList/", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); - /*========================================================================================================================== - | TEST: ACTION: RETURNS EXPECTED VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a test with a specified action to ensure that the expected view is returned. - /// - [Fact] - public async Task Action_ReturnsExpectedView() { + response.EnsureSuccessStatusCode(); - var client = _factory.CreateClient(); + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); + + } + + /*============================================================================================================================ + | TEST: ACTION: RETURNS EXPECTED VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a test with a specified action to ensure that the expected view is returned. + /// + [Fact] + public async Task Action_ReturnsExpectedView() { - var uri = new Uri("/Area/Area/Accordion", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var client = _factory.CreateClient(); - response.EnsureSuccessStatusCode(); + var uri = new Uri("/Area/Area/Accordion", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); + response.EnsureSuccessStatusCode(); - } + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); - /*========================================================================================================================== - | TEST: TOPIC: RETURNS EXPECTED VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a test with a specified to ensure that the expected view is returned. - /// - [Fact] - public async Task Topic_ReturnsExpectedView() { + } - var client = _factory.CreateClient(); + /*============================================================================================================================ + | TEST: TOPIC: RETURNS EXPECTED VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a test with a specified to ensure that the expected view is returned. + /// + [Fact] + public async Task Topic_ReturnsExpectedView() { - var uri = new Uri("/Area/TopicWithView/", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var client = _factory.CreateClient(); - response.EnsureSuccessStatusCode(); + var uri = new Uri("/Area/TopicWithView/", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); + response.EnsureSuccessStatusCode(); - } + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal("~/Views/ContentList/Accordion.cshtml", content); - /*========================================================================================================================== - | TEST: CONTENT TYPE: RETURNS EXPECTED VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a test with without a view specified to ensure that the expected default view is returned based on the . - /// - [Fact] - public async Task ContentType_ReturnsExpectedView() { + } - var client = _factory.CreateClient(); - var uri = new Uri("/Web/ContentList/", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + /*============================================================================================================================ + | TEST: CONTENT TYPE: RETURNS EXPECTED VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a test with without a view specified to ensure that the expected default view is returned based on the . + /// + [Fact] + public async Task ContentType_ReturnsExpectedView() { - response.EnsureSuccessStatusCode(); + var client = _factory.CreateClient(); + var uri = new Uri("/Web/ContentList/", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); + var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); - Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); - Assert.Equal("~/Views/ContentList/ContentList.cshtml", content); + response.EnsureSuccessStatusCode(); - } + Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal("~/Views/ContentList/ContentList.cshtml", content); - /*========================================================================================================================== - | TEST: MISSING VIEW: RETURNS INTERNAL SERVER ERROR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a test without a view and without a default implementation for the and - /// ensures that an is returned. - /// - [Fact] - public async Task MissingView_ReturnsInternalServerError() { + } - var client = _factory.CreateClient(); - var uri = new Uri("/Web/MissingView/", UriKind.Relative); - var response = await client.GetAsync(uri).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MISSING VIEW: RETURNS INTERNAL SERVER ERROR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a test without a view and without a default implementation for the and + /// ensures that an is returned. + /// + [Fact] + public async Task MissingView_ReturnsInternalServerError() { - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + var client = _factory.CreateClient(); + var uri = new Uri("/Web/MissingView/", UriKind.Relative); + var response = await client.GetAsync(uri, TestContext.Current.CancellationToken); - } + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); } + } \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/Controllers/DummyController.cs b/OnTopic.AspNetCore.Mvc.Tests/Controllers/DummyController.cs index c946906f..aae0e046 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/Controllers/DummyController.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/Controllers/DummyController.cs @@ -5,15 +5,14 @@ \=============================================================================================================================*/ using Microsoft.AspNetCore.Mvc; -namespace OnTopic.AspNetCore.Mvc.Controllers { +namespace OnTopic.AspNetCore.Mvc.Controllers; - /*============================================================================================================================ - | CLASS: DUMMY CONTROLLER - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a barebones controller without any actions to act as a stand-in for unit tests. - /// - public class DummyController : Controller { +/*============================================================================================================================== +| CLASS: DUMMY CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a barebones controller without any actions to act as a stand-in for unit tests. +/// +public class DummyController : Controller { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/ErrorControllerTest.cs b/OnTopic.AspNetCore.Mvc.Tests/ErrorControllerTest.cs index 6ea9fa22..62a35077 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/ErrorControllerTest.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/ErrorControllerTest.cs @@ -12,73 +12,72 @@ using OnTopic.Repositories; using OnTopic.ViewModels; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: ERROR CONTROLLER TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the . +/// +[ExcludeFromCodeCoverage] +public class ErrorControllerTest: IClassFixture { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly ITopicMappingService _topicMappingService; + readonly ControllerContext _context; /*============================================================================================================================ - | CLASS: ERROR CONTROLLER TEST + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the . + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - public class ErrorControllerTest: IClassFixture { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ITopicMappingService _topicMappingService; - readonly ControllerContext _context; + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. In addition, it initializes a shared reference to use for the various + /// tests. + /// + public ErrorControllerTest(TestTopicRepository topicRepository) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. In addition, it initializes a shared reference to use for the various - /// tests. - /// - public ErrorControllerTest(TestTopicRepository topicRepository) { + _topicRepository = new CachedTopicRepository(topicRepository); + _topicMappingService = new TopicMappingService(_topicRepository, new TopicViewModelLookupService()); + _context = FakeControllerContext.GetControllerContext("Error"); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = new CachedTopicRepository(topicRepository); - _topicMappingService = new TopicMappingService(_topicRepository, new TopicViewModelLookupService()); - _context = FakeControllerContext.GetControllerContext("Error"); + } - } - - /*========================================================================================================================== - | TEST: ERROR CONTROLLER: HTTP: RETURNS EXPECTED ERROR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the action with different status codes, and ensures - /// that the expected is returned in the . - /// - [Theory] - [InlineData(405, "405")] // Exact match - [InlineData(412, "400")] // Fallback to category - [InlineData(512, "Error")] // Fallback to root topic - public async Task ErrorController_Http_ReturnsExpectedError(int errorCode, string expectedContent) { + /*============================================================================================================================ + | TEST: ERROR CONTROLLER: HTTP: RETURNS EXPECTED ERROR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the action with different status codes, and ensures + /// that the expected is returned in the . + /// + [Theory] + [InlineData(405, "405")] // Exact match + [InlineData(412, "400")] // Fallback to category + [InlineData(512, "Error")] // Fallback to root topic + public async Task ErrorController_Http_ReturnsExpectedError(int errorCode, string expectedContent) { - var controller = new ErrorController(_topicRepository, _topicMappingService) { - ControllerContext = new(_context) - }; - var result = await controller.HttpAsync(errorCode).ConfigureAwait(false) as TopicViewResult; - var model = result?.Model as PageTopicViewModel; + var controller = new ErrorController(_topicRepository, _topicMappingService) { + ControllerContext = new(_context) + }; + var result = await controller.HttpAsync(errorCode) as TopicViewResult; + var model = result?.Model as PageTopicViewModel; - controller.Dispose(); + controller.Dispose(); - Assert.NotNull(result); - Assert.Equal(expectedContent, model?.Title); + Assert.NotNull(result); + Assert.Equal(expectedContent, model?.Title); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/OnTopic.AspNetCore.Mvc.Tests.csproj b/OnTopic.AspNetCore.Mvc.Tests/OnTopic.AspNetCore.Mvc.Tests.csproj index 491863ea..64349739 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/OnTopic.AspNetCore.Mvc.Tests.csproj +++ b/OnTopic.AspNetCore.Mvc.Tests/OnTopic.AspNetCore.Mvc.Tests.csproj @@ -4,6 +4,7 @@ net8.0 Exe false + CA1515 diff --git a/OnTopic.AspNetCore.Mvc.Tests/SitemapControllerTest.cs b/OnTopic.AspNetCore.Mvc.Tests/SitemapControllerTest.cs index 607eb93d..d4597e9e 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/SitemapControllerTest.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/SitemapControllerTest.cs @@ -12,221 +12,220 @@ using OnTopic.Data.Caching; using OnTopic.Repositories; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: SITEMAP CONTROLLER TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the . +/// +[ExcludeFromCodeCoverage] +public class SitemapControllerTest: IClassFixture { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly ControllerContext _context; /*============================================================================================================================ - | CLASS: SITEMAP CONTROLLER TEST + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the . + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - public class SitemapControllerTest: IClassFixture { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. In addition, it initializes a shared reference to use for the various + /// tests. + /// + public SitemapControllerTest(TestTopicRepository topicRepository) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ControllerContext _context; + _topicRepository = new CachedTopicRepository(topicRepository); - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. In addition, it initializes a shared reference to use for the various - /// tests. - /// - public SitemapControllerTest(TestTopicRepository topicRepository) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = new CachedTopicRepository(topicRepository); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish view model context - \-----------------------------------------------------------------------------------------------------------------------*/ - var routes = new RouteData(); - - routes.Values.Add("rootTopic", "Web"); - routes.Values.Add("path", "Web/Valid/Child/"); - - var actionContext = new ActionContext { - HttpContext = new DefaultHttpContext(), - RouteData = routes, - ActionDescriptor = new ControllerActionDescriptor() - }; - _context = new(actionContext); - - } - - /*========================================================================================================================== - | TEST: SITEMAP CONTROLLER: INDEX: RETURNS SITEMAP XML + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish view model context \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the index action of the action. - /// - [Fact] - public void SitemapController_Index_ReturnsSitemapXml() { + var routes = new RouteData(); - var controller = new SitemapController(_topicRepository) { - ControllerContext = new(_context) - }; - var result = controller.Index() as ContentResult; - var model = result?.Content as string; + routes.Values.Add("rootTopic", "Web"); + routes.Values.Add("path", "Web/Valid/Child/"); - controller.Dispose(); + var actionContext = new ActionContext { + HttpContext = new DefaultHttpContext(), + RouteData = routes, + ActionDescriptor = new ControllerActionDescriptor() + }; + _context = new(actionContext); - Assert.NotNull(model); + } - Assert.StartsWith("", model, StringComparison.Ordinal); - Assert.Contains("/Web/Valid/Child/", model!, StringComparison.Ordinal); + /*============================================================================================================================ + | TEST: SITEMAP CONTROLLER: INDEX: RETURNS SITEMAP XML + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the index action of the action. + /// + [Fact] + public void SitemapController_Index_ReturnsSitemapXml() { - } + var controller = new SitemapController(_topicRepository) { + ControllerContext = new(_context) + }; + var result = controller.Index() as ContentResult; + var model = result?.Content as string; - /*========================================================================================================================== - | TEST: SITEMAP CONTROLLER: INDEX: EXCLUDES CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the index action of the action and verifies that it - /// properly excludes List content types, and skips over Container and PageGroup. - /// - [Fact] - public void SitemapController_Index_ExcludesContentTypes() { - - var controller = new SitemapController(_topicRepository) { - ControllerContext = new(_context) - }; - var result = controller.Extended(true) as ContentResult; - var model = result?.Content as string; - - controller.Dispose(); - - Assert.NotNull(model); - Assert.False(model!.Contains("NestedTopics/", StringComparison.Ordinal)); - Assert.False(model!.Contains("NestedTopic/", StringComparison.Ordinal)); - Assert.False(model!.Contains("Redirect/", StringComparison.Ordinal)); - Assert.False(model!.Contains("NoIndex/", StringComparison.Ordinal)); - Assert.False(model!.Contains("Disabled/", StringComparison.Ordinal)); - Assert.False(model!.Contains("PageGroup/", StringComparison.Ordinal)); - - Assert.True(model!.Contains("PageGroupChild/", StringComparison.Ordinal)); - Assert.True(model!.Contains("NoIndexChild/", StringComparison.Ordinal)); - - } - - /*========================================================================================================================== - | TEST: SITEMAP CONTROLLER: INDEX: EXCLUDES CONTAINER DESCENDANTS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the index action of the action and verifies that it - /// properly excludes the children of Container topics that are marked as NoIndex. - /// - [Fact] - public void SitemapController_Index_ExcludesContainerDescendants() { + controller.Dispose(); - var controller = new SitemapController(_topicRepository) { - ControllerContext = new(_context) - }; - var result = controller.Extended(true) as ContentResult; - var model = result?.Content as string; + Assert.NotNull(model); - controller.Dispose(); + Assert.StartsWith("", model, StringComparison.Ordinal); + Assert.Contains("/Web/Valid/Child/", model!, StringComparison.Ordinal); - Assert.NotNull(model); - Assert.False(model!.Contains("NoIndexContainer/", StringComparison.Ordinal)); - Assert.False(model!.Contains("NoIndexContainerChild/", StringComparison.Ordinal)); + } - } + /*============================================================================================================================ + | TEST: SITEMAP CONTROLLER: INDEX: EXCLUDES CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the index action of the action and verifies that it + /// properly excludes List content types, and skips over Container and PageGroup. + /// + [Fact] + public void SitemapController_Index_ExcludesContentTypes() { - /*========================================================================================================================== - | TEST: SITEMAP CONTROLLER: INDEX: EXCLUDES PRIVATE BRANCHES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the index action of the action and verifies that it - /// properly excludes the topics that are marked as IsPrivateBranch, including their descendants. - /// - [Fact] - public void SitemapController_Index_ExcludesPrivateBranches() { + var controller = new SitemapController(_topicRepository) { + ControllerContext = new(_context) + }; + var result = controller.Extended(true) as ContentResult; + var model = result?.Content as string; - var controller = new SitemapController(_topicRepository) { - ControllerContext = new(_context) - }; - var result = controller.Extended(true) as ContentResult; - var model = result?.Content as string; + controller.Dispose(); - controller.Dispose(); + Assert.NotNull(model); + Assert.False(model!.Contains("NestedTopics/", StringComparison.Ordinal)); + Assert.False(model!.Contains("NestedTopic/", StringComparison.Ordinal)); + Assert.False(model!.Contains("Redirect/", StringComparison.Ordinal)); + Assert.False(model!.Contains("NoIndex/", StringComparison.Ordinal)); + Assert.False(model!.Contains("Disabled/", StringComparison.Ordinal)); + Assert.False(model!.Contains("PageGroup/", StringComparison.Ordinal)); - Assert.NotNull(model); - Assert.False(model!.Contains("PrivateBranch/", StringComparison.Ordinal)); - Assert.False(model!.Contains("PrivateBranchChild/", StringComparison.Ordinal)); + Assert.True(model!.Contains("PageGroupChild/", StringComparison.Ordinal)); + Assert.True(model!.Contains("NoIndexChild/", StringComparison.Ordinal)); - } + } - /*========================================================================================================================== - | TEST: SITEMAP CONTROLLER: EXTENDED: INCLUDES ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the extended action of the action and ensures that the - /// results include the expected attributes. - /// - [Fact] - public void SitemapController_Extended_IncludesAttributes() { + /*============================================================================================================================ + | TEST: SITEMAP CONTROLLER: INDEX: EXCLUDES CONTAINER DESCENDANTS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the index action of the action and verifies that it + /// properly excludes the children of Container topics that are marked as NoIndex. + /// + [Fact] + public void SitemapController_Index_ExcludesContainerDescendants() { - var controller = new SitemapController(_topicRepository) { - ControllerContext = new(_context) - }; - var result = controller.Extended(true) as ContentResult; - var model = result?.Content as string; + var controller = new SitemapController(_topicRepository) { + ControllerContext = new(_context) + }; + var result = controller.Extended(true) as ContentResult; + var model = result?.Content as string; - controller.Dispose(); + controller.Dispose(); - Assert.NotNull(model); + Assert.NotNull(model); + Assert.False(model!.Contains("NoIndexContainer/", StringComparison.Ordinal)); + Assert.False(model!.Contains("NoIndexContainerChild/", StringComparison.Ordinal)); - Assert.Contains("", model, StringComparison.Ordinal); - Assert.Contains("/Web/Valid/Child/", model, StringComparison.Ordinal); + } - Assert.Contains("Value", model, StringComparison.Ordinal); - Assert.Contains("Title", model, StringComparison.Ordinal); - Assert.Contains("", model, StringComparison.Ordinal); - Assert.Contains("Web:Redirect", model, StringComparison.Ordinal); - Assert.Contains("", model, StringComparison.Ordinal); - Assert.Contains("Web:Redirect", model, StringComparison.Ordinal); + /*============================================================================================================================ + | TEST: SITEMAP CONTROLLER: INDEX: EXCLUDES PRIVATE BRANCHES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the index action of the action and verifies that it + /// properly excludes the topics that are marked as IsPrivateBranch, including their descendants. + /// + [Fact] + public void SitemapController_Index_ExcludesPrivateBranches() { - } + var controller = new SitemapController(_topicRepository) { + ControllerContext = new(_context) + }; + var result = controller.Extended(true) as ContentResult; + var model = result?.Content as string; - /*========================================================================================================================== - | TEST: SITEMAP CONTROLLER: EXTENDED: EXCLUDES ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the index action of the action and verifies that it - /// properly excludes e.g. the Body and IsHidden attributes. - /// - [Fact] - public void SitemapController_Index_ExcludesAttributes() { + controller.Dispose(); + + Assert.NotNull(model); + Assert.False(model!.Contains("PrivateBranch/", StringComparison.Ordinal)); + Assert.False(model!.Contains("PrivateBranchChild/", StringComparison.Ordinal)); + + } + + /*============================================================================================================================ + | TEST: SITEMAP CONTROLLER: EXTENDED: INCLUDES ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the extended action of the action and ensures that the + /// results include the expected attributes. + /// + [Fact] + public void SitemapController_Extended_IncludesAttributes() { + + var controller = new SitemapController(_topicRepository) { + ControllerContext = new(_context) + }; + var result = controller.Extended(true) as ContentResult; + var model = result?.Content as string; + + controller.Dispose(); + + Assert.NotNull(model); + + Assert.Contains("", model, StringComparison.Ordinal); + Assert.Contains("/Web/Valid/Child/", model, StringComparison.Ordinal); + + Assert.Contains("Value", model, StringComparison.Ordinal); + Assert.Contains("Title", model, StringComparison.Ordinal); + Assert.Contains("", model, StringComparison.Ordinal); + Assert.Contains("Web:Redirect", model, StringComparison.Ordinal); + Assert.Contains("", model, StringComparison.Ordinal); + Assert.Contains("Web:Redirect", model, StringComparison.Ordinal); + + } + + /*============================================================================================================================ + | TEST: SITEMAP CONTROLLER: EXTENDED: EXCLUDES ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the index action of the action and verifies that it + /// properly excludes e.g. the Body and IsHidden attributes. + /// + [Fact] + public void SitemapController_Index_ExcludesAttributes() { - var controller = new SitemapController(_topicRepository) { - ControllerContext = new(_context) - }; - var result = controller.Extended(true) as ContentResult; - var model = result?.Content as string; + var controller = new SitemapController(_topicRepository) { + ControllerContext = new(_context) + }; + var result = controller.Extended(true) as ContentResult; + var model = result?.Content as string; - controller.Dispose(); + controller.Dispose(); - Assert.NotNull(model); + Assert.NotNull(model); - Assert.False(model!.Contains("", StringComparison.Ordinal)); - Assert.False(model!.Contains("", StringComparison.Ordinal)); - Assert.False(model!.Contains("", StringComparison.Ordinal)); - Assert.False(model!.Contains("List", StringComparison.Ordinal)); + Assert.False(model!.Contains("", StringComparison.Ordinal)); + Assert.False(model!.Contains("", StringComparison.Ordinal)); + Assert.False(model!.Contains("", StringComparison.Ordinal)); + Assert.False(model!.Contains("List", StringComparison.Ordinal)); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/FakeControllerContext.cs b/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/FakeControllerContext.cs index f18ec164..90344e4e 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/FakeControllerContext.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/FakeControllerContext.cs @@ -8,54 +8,53 @@ using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Routing; -namespace OnTopic.AspNetCore.Mvc.Tests.TestDoubles { +namespace OnTopic.AspNetCore.Mvc.Tests.TestDoubles; + +/*============================================================================================================================== +| CLASS: FAKE CONTROLLER CONTEXT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a factory method for generating a fake for the purpose of testing controllers. +/// +[ExcludeFromCodeCoverage] +internal static class FakeControllerContext { /*============================================================================================================================ - | CLASS: FAKE CONTROLLER CONTEXT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a factory method for generating a fake for the purpose of testing controllers. + /// Creates a new instances of a . /// - [ExcludeFromCodeCoverage] - internal static class FakeControllerContext { + public static ControllerContext GetControllerContext(string rootTopic, string? path = null) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish view model context + \-------------------------------------------------------------------------------------------------------------------------*/ + var routes = new RouteData(); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Set routes based on parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a new instances of a . - /// - public static ControllerContext GetControllerContext(string rootTopic, string? path = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish view model context - \-----------------------------------------------------------------------------------------------------------------------*/ - var routes = new RouteData(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set routes based on parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - routes.Values.Add("rootTopic", rootTopic); - - if (path is not null) { - routes.Values.Add("path", path); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Create action context - \-----------------------------------------------------------------------------------------------------------------------*/ - var actionContext = new ActionContext { - HttpContext = new DefaultHttpContext(), - RouteData = routes, - ActionDescriptor = new ControllerActionDescriptor() - }; - - /*------------------------------------------------------------------------------------------------------------------------ - | Return new ControllerContext instance - \-----------------------------------------------------------------------------------------------------------------------*/ - return new(actionContext); + routes.Values.Add("rootTopic", rootTopic); + if (path is not null) { + routes.Values.Add("path", path); } - } //Class -} //Namespace + /*-------------------------------------------------------------------------------------------------------------------------- + | Create action context + \-------------------------------------------------------------------------------------------------------------------------*/ + var actionContext = new ActionContext { + HttpContext = new DefaultHttpContext(), + RouteData = routes, + ActionDescriptor = new ControllerActionDescriptor() + }; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return new ControllerContext instance + \-------------------------------------------------------------------------------------------------------------------------*/ + return new(actionContext); + + } + +} //Class diff --git a/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/TestTopicRepository.cs b/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/TestTopicRepository.cs index 614222e6..4f4604ec 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/TestTopicRepository.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/TestDoubles/TestTopicRepository.cs @@ -8,112 +8,111 @@ using OnTopic.Internal.Diagnostics; using OnTopic.Repositories; -namespace OnTopic.AspNetCore.Mvc.Tests.TestDoubles { +namespace OnTopic.AspNetCore.Mvc.Tests.TestDoubles; + +/*============================================================================================================================== +| STUB: TEST TOPIC REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a basic version of an with instances meant to evaluate the +/// business logic of various controllers, such as the , , and +/// . +/// +[ExcludeFromCodeCoverage] +public class TestTopicRepository: DummyTopicRepository { /*============================================================================================================================ - | STUB: TEST TOPIC REPOSITORY + | VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly Topic _cache; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a basic version of an with instances meant to evaluate the - /// business logic of various controllers, such as the , , and - /// . + /// Instantiates a new instance of the StubTopicRepository. /// - [ExcludeFromCodeCoverage] - public class TestTopicRepository: DummyTopicRepository { + /// A new instance of the StubTopicRepository. + public TestTopicRepository() : base() { + _cache = CreateFakeData(); + Contract.Assume(_cache); + } - /*========================================================================================================================== - | VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly Topic _cache; + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load() => _cache; - /*========================================================================================================================== - | CONSTRUCTOR + /*============================================================================================================================ + | METHOD: CREATE FAKE DATA + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a collection of fake data that loosely mimics a bare bones database. + /// + private static Topic CreateFakeData() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Define topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the StubTopicRepository. - /// - /// A new instance of the StubTopicRepository. - public TestTopicRepository() : base() { - _cache = CreateFakeData(); - Contract.Assume(_cache); - } - - /*========================================================================================================================== - | METHOD: LOAD + var rootTopic = new Topic("Root", "Container"); + var webTopic = new Topic("Web", "Page", rootTopic); + var validTopic = new Topic("Valid", "Page", webTopic); + var childTopic = new Topic("Child", "Page", validTopic, 5); + var nestedTopics = new Topic("NestedTopics", "List", childTopic); + _ = new Topic("NestedTopic", "Page", nestedTopics); + var redirectPage = new Topic("Redirect", "Page", webTopic); + var noIndexPage = new Topic("NoIndex", "Page", webTopic); + _ = new Topic("NoIndexChild", "Page", noIndexPage); + var noIndexContainer = new Topic("NoIndexContainer", "Container", webTopic); + _ = new Topic("NoIndexContainerChild", "Page", noIndexContainer); + var privateBranch = new Topic("PrivateBranch", "Page", webTopic); + _ = new Topic("PrivateBranchChild", "Page", privateBranch); + var disabledPage = new Topic("Disabled", "Page", webTopic); + var pageGroup = new Topic("PageGroup", "PageGroup", rootTopic); + _ = new Topic("PageGroupChild", "Page", pageGroup); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish error topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load() => _cache; + var error = new Topic("Error", "Page", rootTopic); + + _ = new Topic("400", "Page", error); + _ = new Topic("405", "Page", error); + _ = new Topic("Unauthorized", "Page", error); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Define attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + + //Associations + childTopic.References.SetValue("Reference", redirectPage); + childTopic.Relationships.SetValue("Relationships", redirectPage); - /*========================================================================================================================== - | METHOD: CREATE FAKE DATA + //Valid attributes + validTopic.Attributes.SetValue("Attribute", "Value"); + validTopic.Attributes.SetValue("Title", "Title"); + + //Excluded attributes + validTopic.Attributes.SetBoolean("NoIndex", false); + validTopic.Attributes.SetBoolean("IsHidden", true); + validTopic.Attributes.SetValue("Body", "Body"); + validTopic.Attributes.SetValue("SortOrder", "5"); + + //Excluded topics + redirectPage.Attributes.SetValue("Url", "https://www.ignia.com/"); + noIndexPage.Attributes.SetBoolean("NoIndex", true); + disabledPage.Attributes.SetBoolean("IsDisabled", true); + + //Excluded descendants + noIndexContainer.Attributes.SetBoolean("NoIndex", true); + privateBranch.Attributes.SetBoolean("IsPrivateBranch", true); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return data \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a collection of fake data that loosely mimics a bare bones database. - /// - private static Topic CreateFakeData() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Define topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var rootTopic = new Topic("Root", "Container"); - var webTopic = new Topic("Web", "Page", rootTopic); - var validTopic = new Topic("Valid", "Page", webTopic); - var childTopic = new Topic("Child", "Page", validTopic, 5); - var nestedTopics = new Topic("NestedTopics", "List", childTopic); - _ = new Topic("NestedTopic", "Page", nestedTopics); - var redirectPage = new Topic("Redirect", "Page", webTopic); - var noIndexPage = new Topic("NoIndex", "Page", webTopic); - _ = new Topic("NoIndexChild", "Page", noIndexPage); - var noIndexContainer = new Topic("NoIndexContainer", "Container", webTopic); - _ = new Topic("NoIndexContainerChild", "Page", noIndexContainer); - var privateBranch = new Topic("PrivateBranch", "Page", webTopic); - _ = new Topic("PrivateBranchChild", "Page", privateBranch); - var disabledPage = new Topic("Disabled", "Page", webTopic); - var pageGroup = new Topic("PageGroup", "PageGroup", rootTopic); - _ = new Topic("PageGroupChild", "Page", pageGroup); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish error topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var error = new Topic("Error", "Page", rootTopic); - - _ = new Topic("400", "Page", error); - _ = new Topic("405", "Page", error); - _ = new Topic("Unauthorized", "Page", error); - - /*------------------------------------------------------------------------------------------------------------------------ - | Define attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - - //Associations - childTopic.References.SetValue("Reference", redirectPage); - childTopic.Relationships.SetValue("Relationships", redirectPage); - - //Valid attributes - validTopic.Attributes.SetValue("Attribute", "Value"); - validTopic.Attributes.SetValue("Title", "Title"); - - //Excluded attributes - validTopic.Attributes.SetBoolean("NoIndex", false); - validTopic.Attributes.SetBoolean("IsHidden", true); - validTopic.Attributes.SetValue("Body", "Body"); - validTopic.Attributes.SetValue("SortOrder", "5"); - - //Excluded topics - redirectPage.Attributes.SetValue("Url", "https://www.ignia.com/"); - noIndexPage.Attributes.SetBoolean("NoIndex", true); - disabledPage.Attributes.SetBoolean("IsDisabled", true); - - //Excluded descendants - noIndexContainer.Attributes.SetBoolean("NoIndex", true); - privateBranch.Attributes.SetBoolean("IsPrivateBranch", true); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return data - \-----------------------------------------------------------------------------------------------------------------------*/ - return rootTopic; - - } + return rootTopic; } + } diff --git a/OnTopic.AspNetCore.Mvc.Tests/TopicControllerTest.cs b/OnTopic.AspNetCore.Mvc.Tests/TopicControllerTest.cs index 64811049..abf06f6c 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/TopicControllerTest.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/TopicControllerTest.cs @@ -12,113 +12,112 @@ using OnTopic.Repositories; using OnTopic.ViewModels; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC CONTROLLER TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the , and other classes that are part of +/// the namespace. +/// +[ExcludeFromCodeCoverage] +public class TopicControllerTest: IClassFixture { /*============================================================================================================================ - | CLASS: TOPIC CONTROLLER TEST + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly ITopicMappingService _topicMappingService; + readonly Topic _topic; + readonly ControllerContext _context; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the , and other classes that are part of - /// the namespace. + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - public class TopicControllerTest: IClassFixture { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. In addition, it initializes a shared reference to use for the various + /// tests. + /// + public TopicControllerTest(TestTopicRepository topicRepository) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ITopicMappingService _topicMappingService; - readonly Topic _topic; - readonly ControllerContext _context; + _topicRepository = new CachedTopicRepository(topicRepository); + _topic = _topicRepository.Load("Root:Web:Valid:Child")!; + _topicMappingService = new TopicMappingService(_topicRepository, new TopicViewModelLookupService()); + _context = FakeControllerContext.GetControllerContext("Web", "Web/Valid/Child/"); - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. In addition, it initializes a shared reference to use for the various - /// tests. - /// - public TopicControllerTest(TestTopicRepository topicRepository) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = new CachedTopicRepository(topicRepository); - _topic = _topicRepository.Load("Root:Web:Valid:Child")!; - _topicMappingService = new TopicMappingService(_topicRepository, new TopicViewModelLookupService()); - _context = FakeControllerContext.GetControllerContext("Web", "Web/Valid/Child/"); - - } - - /*========================================================================================================================== - | TEST: TOPIC CONTROLLER: INDEX ASYNC: RETURNS TOPIC VIEW RESULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the action. - /// - [Fact] - public async Task TopicController_IndexAsync_ReturnsTopicViewResult() { + } - var controller = new TopicController(_topicRepository, _topicMappingService) { - ControllerContext = _context - }; + /*============================================================================================================================ + | TEST: TOPIC CONTROLLER: INDEX ASYNC: RETURNS TOPIC VIEW RESULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the action. + /// + [Fact] + public async Task TopicController_IndexAsync_ReturnsTopicViewResult() { - var result = await controller.IndexAsync(_topic.GetWebPath()).ConfigureAwait(false) as TopicViewResult; - var model = result?.Model as PageTopicViewModel; + var controller = new TopicController(_topicRepository, _topicMappingService) { + ControllerContext = _context + }; - controller.Dispose(); + var result = await controller.IndexAsync(_topic.GetWebPath()) as TopicViewResult; + var model = result?.Model as PageTopicViewModel; - Assert.NotNull(model); - Assert.Equal("Child", model?.Title); + controller.Dispose(); - } + Assert.NotNull(model); + Assert.Equal("Child", model?.Title); - /*========================================================================================================================== - | TEST: REDIRECT CONTROLLER: REDIRECT: RETURNS REDIRECT RESULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the action. - /// - [Fact] - public void RedirectController_TopicRedirect_ReturnsRedirectResult() { + } - var controller = new RedirectController(_topicRepository); - var result = controller.Redirect(_topic.Id) as RedirectResult; + /*============================================================================================================================ + | TEST: REDIRECT CONTROLLER: REDIRECT: RETURNS REDIRECT RESULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the action. + /// + [Fact] + public void RedirectController_TopicRedirect_ReturnsRedirectResult() { - controller.Dispose(); + var controller = new RedirectController(_topicRepository); + var result = controller.Redirect(_topic.Id) as RedirectResult; - Assert.NotNull(result); - Assert.True(result?.Permanent?? false); - Assert.Equal(_topic.GetWebPath(), result?.Url); + controller.Dispose(); - } + Assert.NotNull(result); + Assert.True(result?.Permanent?? false); + Assert.Equal(_topic.GetWebPath(), result?.Url); - /*========================================================================================================================== - | TEST: REDIRECT CONTROLLER: REDIRECT: RETURNS NOT FOUND OBJECT RESULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Triggers the action with an invalid and - /// confirms that a is returned. - /// - [Fact] - public void RedirectController_TopicRedirect_ReturnsNotFoundObjectResult() { + } + + /*============================================================================================================================ + | TEST: REDIRECT CONTROLLER: REDIRECT: RETURNS NOT FOUND OBJECT RESULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Triggers the action with an invalid and + /// confirms that a is returned. + /// + [Fact] + public void RedirectController_TopicRedirect_ReturnsNotFoundObjectResult() { - var controller = new RedirectController(_topicRepository); - var result = controller.Redirect(12345); + var controller = new RedirectController(_topicRepository); + var result = controller.Redirect(12345); - controller.Dispose(); + controller.Dispose(); - Assert.NotNull(result); - Assert.IsType(result); + Assert.NotNull(result); + Assert.IsType(result); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/TopicRepositoryExtensionsTest.cs b/OnTopic.AspNetCore.Mvc.Tests/TopicRepositoryExtensionsTest.cs index 4b70e8f7..0f302fcd 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/TopicRepositoryExtensionsTest.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/TopicRepositoryExtensionsTest.cs @@ -8,103 +8,102 @@ using OnTopic.Data.Caching; using OnTopic.Repositories; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC REPOSITORY EXTENSIONS TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +[Collection("Data Tests")] +public class TopicRepositoryExtensionsTest: IClassFixture { /*============================================================================================================================ - | CLASS: TOPIC REPOSITORY EXTENSIONS TEST + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the with shared resources. + /// + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. + /// + public TopicRepositoryExtensionsTest(StubTopicRepository topicRepository) { + _topicRepository = new CachedTopicRepository(topicRepository); + } + + /*============================================================================================================================ + | TEST: LOAD: BY ROUTE: RETURNS TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes route data and ensures that a topic is correctly identified based on that route. + /// + [Fact] + public void Load_ByRoute_ReturnsTopic() { + + var routes = new RouteData(); + var topic = _topicRepository.Load("Root:Web:Web_0:Web_0_1:Web_0_1_1"); + + routes.Values.Add("rootTopic", "Web"); + routes.Values.Add("path", "Web_0/Web_0_1/Web_0_1_1"); + + var currentTopic = _topicRepository.Load(routes); + + Assert.NotNull(currentTopic); + Assert.Equal(topic, currentTopic); + Assert.Equal("Web_0_1_1", currentTopic?.Key); + + } + + /*============================================================================================================================ + | TEST: LOAD: BY ROUTE: RETURNS ROOT TOPIC \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Establishes route data and ensures that the root topic is correctly identified based on that route. /// - [ExcludeFromCodeCoverage] - [Collection("Data Tests")] - public class TopicRepositoryExtensionsTest: IClassFixture { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. - /// - public TopicRepositoryExtensionsTest(StubTopicRepository topicRepository) { - _topicRepository = new CachedTopicRepository(topicRepository); - } - - /*========================================================================================================================== - | TEST: LOAD: BY ROUTE: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes route data and ensures that a topic is correctly identified based on that route. - /// - [Fact] - public void Load_ByRoute_ReturnsTopic() { - - var routes = new RouteData(); - var topic = _topicRepository.Load("Root:Web:Web_0:Web_0_1:Web_0_1_1"); - - routes.Values.Add("rootTopic", "Web"); - routes.Values.Add("path", "Web_0/Web_0_1/Web_0_1_1"); - - var currentTopic = _topicRepository.Load(routes); - - Assert.NotNull(currentTopic); - Assert.Equal(topic, currentTopic); - Assert.Equal("Web_0_1_1", currentTopic?.Key); - - } - - /*========================================================================================================================== - | TEST: LOAD: BY ROUTE: RETURNS ROOT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes route data and ensures that the root topic is correctly identified based on that route. - /// - [Fact] - public void Load_ByRoute_ReturnsRootTopic() { - - var routes = new RouteData(); - var topic = _topicRepository.Load("Root"); - - routes.Values.Add("path", "Root/"); - - var currentTopic = _topicRepository.Load(routes); - - Assert.NotNull(currentTopic); - Assert.Equal(topic, currentTopic); - Assert.Equal("Root", currentTopic?.Key); - - } - - /*========================================================================================================================== - | TEST: LOAD: BY ROUTE: SWALLOWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes route data with an invalid key and ensures that no result is returned, but no exception is thrown. - /// - [Fact] - public void Load_ByRoute_SwallowsException() { - - var routes = new RouteData(); - - routes.Values.Add("rootTopic", "Web"); - routes.Values.Add("path", "Web/~* &$#@"); - - var currentTopic = _topicRepository.Load(routes); - - Assert.Null(currentTopic); - - } - - } //Class -} //Namespace \ No newline at end of file + [Fact] + public void Load_ByRoute_ReturnsRootTopic() { + + var routes = new RouteData(); + var topic = _topicRepository.Load("Root"); + + routes.Values.Add("path", "Root/"); + + var currentTopic = _topicRepository.Load(routes); + + Assert.NotNull(currentTopic); + Assert.Equal(topic, currentTopic); + Assert.Equal("Root", currentTopic?.Key); + + } + + /*============================================================================================================================ + | TEST: LOAD: BY ROUTE: SWALLOWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes route data with an invalid key and ensures that no result is returned, but no exception is thrown. + /// + [Fact] + public void Load_ByRoute_SwallowsException() { + + var routes = new RouteData(); + + routes.Values.Add("rootTopic", "Web"); + routes.Values.Add("path", "Web/~* &$#@"); + + var currentTopic = _topicRepository.Load(routes); + + Assert.Null(currentTopic); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/TopicViewComponentTest.cs b/OnTopic.AspNetCore.Mvc.Tests/TopicViewComponentTest.cs index b40fc646..d45e9c97 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/TopicViewComponentTest.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/TopicViewComponentTest.cs @@ -16,247 +16,246 @@ using OnTopic.Repositories; using OnTopic.ViewModels; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC VIEW COMPONENT TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the , and derived classes that are part of +/// the namespace. +/// +[ExcludeFromCodeCoverage] +[Collection("Data Tests")] +public class TopicViewComponentTest: IClassFixture { /*============================================================================================================================ - | CLASS: TOPIC VIEW COMPONENT TEST + | PRIVATE VARIABLES \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides unit tests for the , and derived classes that are part of - /// the namespace. - /// - [ExcludeFromCodeCoverage] - [Collection("Data Tests")] - public class TopicViewComponentTest: IClassFixture { + readonly ITopicRepository _topicRepository; + readonly ITopicMappingService _topicMappingService; + readonly Topic _topic; + readonly ViewComponentContext _context; - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ITopicMappingService _topicMappingService; - readonly Topic _topic; - readonly ViewComponentContext _context; + /*============================================================================================================================ + | HIERARCHICAL TOPIC MAPPING SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; - /*========================================================================================================================== - | HIERARCHICAL TOPIC MAPPING SERVICE + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the with shared resources. + /// + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. In addition, it initializes a shared reference to use for the various + /// tests. + /// + public TopicViewComponentTest(StubTopicRepository topicRepository) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + _topicRepository = new CachedTopicRepository(topicRepository); + _topic = _topicRepository.Load("Root:Web:Web_3:Web_3_0")!; + _topicMappingService = new TopicMappingService(_topicRepository, new TopicViewModelLookupService()); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish hierarchical topic mapping service \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. In addition, it initializes a shared reference to use for the various - /// tests. - /// - public TopicViewComponentTest(StubTopicRepository topicRepository) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = new CachedTopicRepository(topicRepository); - _topic = _topicRepository.Load("Root:Web:Web_3:Web_3_0")!; - _topicMappingService = new TopicMappingService(_topicRepository, new TopicViewModelLookupService()); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish hierarchical topic mapping service - \-----------------------------------------------------------------------------------------------------------------------*/ - _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( - new HierarchicalTopicMappingService( - _topicRepository, - _topicMappingService - ) - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish view model context - \-----------------------------------------------------------------------------------------------------------------------*/ - _context = GetViewComponentContext(_topic.GetWebPath()); - - } - - /*========================================================================================================================== - | METHOD: GET VIEW COMPONENT CONTEXT + _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( + new HierarchicalTopicMappingService( + _topicRepository, + _topicMappingService + ) + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish view model context \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on a given . - /// - private static ViewComponentContext GetViewComponentContext(string webPath) { + _context = GetViewComponentContext(_topic.GetWebPath()); - var routes = new RouteData(); + } - routes.Values.Add("rootTopic", "Web"); - routes.Values.Add("path", webPath); + /*============================================================================================================================ + | METHOD: GET VIEW COMPONENT CONTEXT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new based on a given . + /// + private static ViewComponentContext GetViewComponentContext(string webPath) { - var viewContext = new ViewContext() { - HttpContext = new DefaultHttpContext(), - RouteData = routes - }; - var viewComponentContext = new ViewComponentContext() { - ViewContext = viewContext - }; + var routes = new RouteData(); - return viewComponentContext; + routes.Values.Add("rootTopic", "Web"); + routes.Values.Add("path", webPath); - } + var viewContext = new ViewContext() { + HttpContext = new DefaultHttpContext(), + RouteData = routes + }; + var viewComponentContext = new ViewComponentContext() { + ViewContext = viewContext + }; - /*========================================================================================================================== - | TEST: MENU: INVOKE: RETURNS NAVIGATION VIEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a new and confirms the resulting values. - /// - [Fact] - public async Task Menu_Invoke_ReturnsNavigationViewModel() { + return viewComponentContext; - var viewComponent = new MenuViewComponent(_topicRepository, _hierarchicalMappingService) { - ViewComponentContext = _context - }; + } - var result = await viewComponent.InvokeAsync().ConfigureAwait(false); - var concreteResult = result as ViewViewComponentResult; - var model = concreteResult?.ViewData?.Model as NavigationViewModel; + /*============================================================================================================================ + | TEST: MENU: INVOKE: RETURNS NAVIGATION VIEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a new and confirms the resulting values. + /// + [Fact] + public async Task Menu_Invoke_ReturnsNavigationViewModel() { - Assert.NotNull(model); - Assert.Equal(_topic.GetWebPath(), model?.CurrentWebPath); - Assert.Equal("/Web/", model?.NavigationRoot?.WebPath); - Assert.Equal(3, model?.NavigationRoot?.Children.Count); + var viewComponent = new MenuViewComponent(_topicRepository, _hierarchicalMappingService) { + ViewComponentContext = _context + }; - } + var result = await viewComponent.InvokeAsync(); + var concreteResult = result as ViewViewComponentResult; + var model = concreteResult?.ViewData?.Model as NavigationViewModel; - /*========================================================================================================================== - | TEST: MENU: INVOKE: RETURNS CONFIGURED NAVIGATION ROOT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a new with a context defining an alternate NavigationRoot, and confirms - /// that is returned as the . - /// - [Fact] - public async Task Menu_Invoke_ReturnsConfiguredNavigationRoot() { - - var webPath = "/Web/Web_3/Web_3_1/Web_3_1_0/"; - var viewComponent = new MenuViewComponent(_topicRepository, _hierarchicalMappingService) { - ViewComponentContext = GetViewComponentContext(webPath) - }; - - var result = await viewComponent.InvokeAsync().ConfigureAwait(false); - var concreteResult = result as ViewViewComponentResult; - var model = concreteResult?.ViewData?.Model as NavigationViewModel; - - Assert.NotNull(model); - Assert.Equal(webPath, model?.CurrentWebPath); - Assert.Equal("/Configuration/", model?.NavigationRoot?.WebPath); - - } - - /*========================================================================================================================== - | TEST: NAVIGATION TOPIC VIEW MODEL: IS SELECTED: RETURNS EXPECTED OUTPUT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a with a child instance, and ensures that the method returns the expected results. - /// - [Fact] - public void NavigationTopicViewModel_IsSelected_ReturnsExpectedOutput() { - - var parent = new NavigationTopicViewModel() { - WebPath = "/Web/" - }; - var child = new NavigationTopicViewModel() { - WebPath = parent.WebPath + "Path/" - }; - parent.Children.Add(child); - - Assert.True(child.IsSelected(child.WebPath)); - Assert.True(parent.IsSelected(child.WebPath)); - Assert.False(child.IsSelected(parent.WebPath)); - - } - - /*========================================================================================================================== - | TEST: PAGE-LEVEL NAVIGATION: INVOKE: RETURNS NAVIGATION VIEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a new and confirms the resulting values. - /// - [Fact] - public async Task PageLevelNavigation_Invoke_ReturnsNavigationViewModel() { - - var viewComponent = new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService) { - ViewComponentContext = _context - }; - - var result = await viewComponent.InvokeAsync().ConfigureAwait(false); - var concreteResult = result as ViewViewComponentResult; - var model = concreteResult?.ViewData?.Model as NavigationViewModel; - - Assert.NotNull(model); - Assert.Equal(_topic.GetWebPath(), model?.CurrentWebPath); - Assert.Equal("/Web/Web_3/", model?.NavigationRoot?.WebPath); - Assert.Equal(2, model?.NavigationRoot?.Children.Count); - Assert.True(model?.NavigationRoot?.IsSelected(_topic.GetWebPath())?? false); - - } - - /*========================================================================================================================== - | TEST: PAGE-LEVEL NAVIGATION: INVOKE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a new with a root that does not derive from a PageGroup - /// and confirms the resulting is null. - /// - [Fact] - public async Task PageLevelNavigation_Invoke_ReturnsNull() { + Assert.NotNull(model); + Assert.Equal(_topic.GetWebPath(), model?.CurrentWebPath); + Assert.Equal("/Web/", model?.NavigationRoot?.WebPath); + Assert.Equal(3, model?.NavigationRoot?.Children.Count); - var webPath = "/Web/Web_1/Web_1_0/"; + } - var viewComponent = new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService) { - ViewComponentContext = GetViewComponentContext(webPath) - }; + /*============================================================================================================================ + | TEST: MENU: INVOKE: RETURNS CONFIGURED NAVIGATION ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a new with a context defining an alternate NavigationRoot, and confirms + /// that is returned as the . + /// + [Fact] + public async Task Menu_Invoke_ReturnsConfiguredNavigationRoot() { - var result = await viewComponent.InvokeAsync().ConfigureAwait(false); - var concreteResult = result as ViewViewComponentResult; - var model = concreteResult?.ViewData?.Model as NavigationViewModel; + var webPath = "/Web/Web_3/Web_3_1/Web_3_1_0/"; + var viewComponent = new MenuViewComponent(_topicRepository, _hierarchicalMappingService) { + ViewComponentContext = GetViewComponentContext(webPath) + }; - Assert.NotNull(model); - Assert.Equal(webPath, model?.CurrentWebPath); - Assert.Null(model?.NavigationRoot); + var result = await viewComponent.InvokeAsync(); + var concreteResult = result as ViewViewComponentResult; + var model = concreteResult?.ViewData?.Model as NavigationViewModel; - } + Assert.NotNull(model); + Assert.Equal(webPath, model?.CurrentWebPath); + Assert.Equal("/Configuration/", model?.NavigationRoot?.WebPath); - /*========================================================================================================================== - | TEST: PAGE-LEVEL NAVIGATION: INVOKE WITH NULL TOPIC: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a new with a null topic reference and confirms the resulting is null. This occurs when handling 404 errors. - /// - [Fact] - public async Task PageLevelNavigation_InvokeWithNullTopic_ReturnsNull() - { + } - var webPath = "/Invalid/Path/"; + /*============================================================================================================================ + | TEST: NAVIGATION TOPIC VIEW MODEL: IS SELECTED: RETURNS EXPECTED OUTPUT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a with a child instance, and ensures that the method returns the expected results. + /// + [Fact] + public void NavigationTopicViewModel_IsSelected_ReturnsExpectedOutput() { + + var parent = new NavigationTopicViewModel() { + WebPath = "/Web/" + }; + var child = new NavigationTopicViewModel() { + WebPath = parent.WebPath + "Path/" + }; + parent.Children.Add(child); + + Assert.True(child.IsSelected(child.WebPath)); + Assert.True(parent.IsSelected(child.WebPath)); + Assert.False(child.IsSelected(parent.WebPath)); + + } + + /*============================================================================================================================ + | TEST: PAGE-LEVEL NAVIGATION: INVOKE: RETURNS NAVIGATION VIEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a new and confirms the resulting values. + /// + [Fact] + public async Task PageLevelNavigation_Invoke_ReturnsNavigationViewModel() { + + var viewComponent = new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService) { + ViewComponentContext = _context + }; + + var result = await viewComponent.InvokeAsync(); + var concreteResult = result as ViewViewComponentResult; + var model = concreteResult?.ViewData?.Model as NavigationViewModel; + + Assert.NotNull(model); + Assert.Equal(_topic.GetWebPath(), model?.CurrentWebPath); + Assert.Equal("/Web/Web_3/", model?.NavigationRoot?.WebPath); + Assert.Equal(2, model?.NavigationRoot?.Children.Count); + Assert.True(model?.NavigationRoot?.IsSelected(_topic.GetWebPath())?? false); + + } + + /*============================================================================================================================ + | TEST: PAGE-LEVEL NAVIGATION: INVOKE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a new with a root that does not derive from a PageGroup + /// and confirms the resulting is null. + /// + [Fact] + public async Task PageLevelNavigation_Invoke_ReturnsNull() { + + var webPath = "/Web/Web_1/Web_1_0/"; + + var viewComponent = new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService) { + ViewComponentContext = GetViewComponentContext(webPath) + }; + + var result = await viewComponent.InvokeAsync(); + var concreteResult = result as ViewViewComponentResult; + var model = concreteResult?.ViewData?.Model as NavigationViewModel; + + Assert.NotNull(model); + Assert.Equal(webPath, model?.CurrentWebPath); + Assert.Null(model?.NavigationRoot); + + } - var viewComponent = new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService) - { - ViewComponentContext = GetViewComponentContext(webPath) - }; + /*============================================================================================================================ + | TEST: PAGE-LEVEL NAVIGATION: INVOKE WITH NULL TOPIC: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a new with a null topic reference and confirms the resulting is null. This occurs when handling 404 errors. + /// + [Fact] + public async Task PageLevelNavigation_InvokeWithNullTopic_ReturnsNull() + { + + var webPath = "/Invalid/Path/"; + + var viewComponent = new PageLevelNavigationViewComponent(_topicRepository, _hierarchicalMappingService) + { + ViewComponentContext = GetViewComponentContext(webPath) + }; - var result = await viewComponent.InvokeAsync().ConfigureAwait(false); - var concreteResult = result as ViewViewComponentResult; - var model = concreteResult?.ViewData?.Model as NavigationViewModel; + var result = await viewComponent.InvokeAsync(); + var concreteResult = result as ViewViewComponentResult; + var model = concreteResult?.ViewData?.Model as NavigationViewModel; - Assert.NotNull(model); - Assert.Equal(String.Empty, model?.CurrentWebPath); - Assert.Null(model?.NavigationRoot); + Assert.NotNull(model); + Assert.Equal(String.Empty, model?.CurrentWebPath); + Assert.Null(model?.NavigationRoot); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc.Tests/ValidateTopicAttributeTest.cs b/OnTopic.AspNetCore.Mvc.Tests/ValidateTopicAttributeTest.cs index 393de837..00068ccb 100644 --- a/OnTopic.AspNetCore.Mvc.Tests/ValidateTopicAttributeTest.cs +++ b/OnTopic.AspNetCore.Mvc.Tests/ValidateTopicAttributeTest.cs @@ -13,327 +13,327 @@ using OnTopic.Attributes; using OnTopic.Metadata; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: VALIDATE TOPIC ATTRIBUTE TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the . +/// +[ExcludeFromCodeCoverage] +public class ValidateTopicAttributeTest { /*============================================================================================================================ - | CLASS: VALIDATE TOPIC ATTRIBUTE TEST + | METHOD: GET ACTION EXECUTING CONTEXT \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the . + /// Given a , generates a barebones for testing. /// - [ExcludeFromCodeCoverage] - public class ValidateTopicAttributeTest { - - /*========================================================================================================================== - | METHOD: GET ACTION EXECUTING CONTEXT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , generates a barebones for testing. - /// - public static ActionExecutingContext GetActionExecutingContext(Controller controller) { - - var modelState = new ModelStateDictionary(); - - var actionContext = new ActionContext( - new DefaultHttpContext(), - new(), - new ControllerActionDescriptor(), - modelState - ); - - var actionExecutingContext = new ActionExecutingContext( - actionContext, - new List(), - new Dictionary(), - controller - ); - - return actionExecutingContext; - - } - - /*========================================================================================================================== - | METHOD: GET CONTROLLER CONTEXT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Generates a barebones for testing a controller. - /// - public static ControllerContext GetControllerContext() => - new( - new() { - HttpContext = new DefaultHttpContext(), - RouteData = new(), - ActionDescriptor = new ControllerActionDescriptor() - } - ); - - /*========================================================================================================================== - | METHOD: GET TOPIC CONTROLLER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Generates a barebones for testing a controller. - /// - public static TopicController GetTopicController(Topic? topic) => - new( - new DummyTopicRepository(), - new DummyTopicMappingService() - ) { - CurrentTopic = topic, - ControllerContext = GetControllerContext() - }; - - /*========================================================================================================================== - | TEST: INVALID CONTROLLER TYPE THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a controller that doesn't derive from throws a . - /// - [Fact] - public void InvalidControllerType_ThrowsException() { - - using var controller = new DummyController() { - ControllerContext = GetControllerContext() - }; - - var validateFilter = new ValidateTopicAttribute(); - var actionContext = GetActionExecutingContext(controller); - - Assert.Throws(() => - validateFilter.OnActionExecuting(actionContext) - ); - - } - - /*========================================================================================================================== - | TEST: NULL TOPIC: RETURNS NOT FOUND - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the is null. - /// - [Fact] - public void NullTopic_ReturnsNotFound() { - - var validateFilter = new ValidateTopicAttribute(); - var controller = GetTopicController(null); - var context = GetActionExecutingContext(controller); - - validateFilter.OnActionExecuting(context); - - controller.Dispose(); - - Assert.IsType(context.Result); - - } - - /*========================================================================================================================== - | TEST: DISABLED TOPIC: RETURNS NOT AUTHORIZED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the is null. - /// - [Fact] - public void DisabledTopic_ReturnsNotFound() { - - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Key", "Page"); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); - - topic.Attributes.SetBoolean("IsDisabled", true); - - validateFilter.OnActionExecuting(context); - - controller.Dispose(); - - Assert.IsType(context.Result); - - } - - /*========================================================================================================================== - | TEST: TOPIC WITH URL: RETURNS REDIRECT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the contains - /// a Url attribute. - /// - [Fact] - public void TopicWithUrl_ReturnsRedirect() { - - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Key", "Page"); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); - - topic.Attributes.SetValue("Url", "https://www.github.com/Ignia/Topic-Library"); - - validateFilter.OnActionExecuting(context); - - controller.Dispose(); - - Assert.IsType(context.Result); + public static ActionExecutingContext GetActionExecutingContext(Controller controller) { - } + var modelState = new ModelStateDictionary(); - /*========================================================================================================================== - | TEST: NESTED TOPIC: LIST: RETURNS 403 - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the has a - /// of List. - /// - [Fact] - public void NestedTopic_List_Returns403() { + var actionContext = new ActionContext( + new DefaultHttpContext(), + new(), + new ControllerActionDescriptor(), + modelState + ); - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Key", "List"); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); + var actionExecutingContext = new ActionExecutingContext( + actionContext, + new List(), + new Dictionary(), + controller + ); - validateFilter.OnActionExecuting(context); + return actionExecutingContext; - controller.Dispose(); + } - var result = context.Result as StatusCodeResult; + /*============================================================================================================================ + | METHOD: GET CONTROLLER CONTEXT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Generates a barebones for testing a controller. + /// + [SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "This constructs a new object graph, so it isn't appropriate as a property.")] + public static ControllerContext GetControllerContext() => + new( + new() { + HttpContext = new DefaultHttpContext(), + RouteData = new(), + ActionDescriptor = new ControllerActionDescriptor() + } + ); - Assert.NotNull(result); - Assert.Equal(403, result?.StatusCode); + /*============================================================================================================================ + | METHOD: GET TOPIC CONTROLLER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Generates a barebones for testing a controller. + /// + public static TopicController GetTopicController(Topic? topic) => + new( + new DummyTopicRepository(), + new DummyTopicMappingService() + ) { + CurrentTopic = topic, + ControllerContext = GetControllerContext() + }; - } + /*============================================================================================================================ + | TEST: INVALID CONTROLLER TYPE THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a controller that doesn't derive from throws a . + /// + [Fact] + public void InvalidControllerType_ThrowsException() { - /*========================================================================================================================== - | TEST: NESTED TOPIC: ITEM: RETURNS 403 - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the has a - /// parent with a of List. - /// - [Fact] - public void NestedTopic_Item_Returns403() { + using var controller = new DummyController() { + ControllerContext = GetControllerContext() + }; - var validateFilter = new ValidateTopicAttribute(); - var list = new Topic("Key", "List"); - var topic = new Topic("Item", "Page", list); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); + var validateFilter = new ValidateTopicAttribute(); + var actionContext = GetActionExecutingContext(controller); - validateFilter.OnActionExecuting(context); + Assert.Throws(() => + validateFilter.OnActionExecuting(actionContext) + ); - controller.Dispose(); + } - var result = context.Result as StatusCodeResult; + /*============================================================================================================================ + | TEST: NULL TOPIC: RETURNS NOT FOUND + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the is null. + /// + [Fact] + public void NullTopic_ReturnsNotFound() { - Assert.NotNull(result); - Assert.Equal(403, result?.StatusCode); + var validateFilter = new ValidateTopicAttribute(); + var controller = GetTopicController(null); + var context = GetActionExecutingContext(controller); - } + validateFilter.OnActionExecuting(context); - /*========================================================================================================================== - | TEST: NESTED TOPIC: ITEM: RETURNS 403 - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the has a - /// parent with a of List. - /// - [Fact] - public void Container_Returns403() { + controller.Dispose(); - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Item", "Container"); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); + Assert.IsType(context.Result); - validateFilter.OnActionExecuting(context); + } - controller.Dispose(); + /*============================================================================================================================ + | TEST: DISABLED TOPIC: RETURNS NOT AUTHORIZED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the is null. + /// + [Fact] + public void DisabledTopic_ReturnsNotFound() { - var result = context.Result as StatusCodeResult; + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Key", "Page"); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); - Assert.NotNull(result); - Assert.Equal(403, result?.StatusCode); + topic.Attributes.SetBoolean("IsDisabled", true); - } + validateFilter.OnActionExecuting(context); - /*========================================================================================================================== - | TEST: PAGE GROUP TOPIC: RETURNS REDIRECT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the has a - /// of PageGroup. - /// - [Fact] - public void PageGroupTopic_ReturnsRedirect() { + controller.Dispose(); - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Key", "PageGroup"); - var child = new Topic("Child", "Page", topic); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); - _ = new Topic("Home", "Page", topic); + Assert.IsType(context.Result); - validateFilter.OnActionExecuting(context); + } - controller.Dispose(); + /*============================================================================================================================ + | TEST: TOPIC WITH URL: RETURNS REDIRECT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the contains + /// a Url attribute. + /// + [Fact] + public void TopicWithUrl_ReturnsRedirect() { + + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Key", "Page"); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); + + topic.Attributes.SetValue("Url", "https://www.github.com/Ignia/Topic-Library"); + + validateFilter.OnActionExecuting(context); + + controller.Dispose(); + + Assert.IsType(context.Result); + + } - Assert.IsType(context.Result); - Assert.Equal(child.GetWebPath(), ((RedirectResult?)context.Result)?.Url); + /*============================================================================================================================ + | TEST: NESTED TOPIC: LIST: RETURNS 403 + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the has a + /// of List. + /// + [Fact] + public void NestedTopic_List_Returns403() { + + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Key", "List"); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); - } + validateFilter.OnActionExecuting(context); - /*========================================================================================================================== - | TEST: PAGE GROUP TOPIC: EMPTY: RETURNS REDIRECT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the has a - /// of PageGroup with no . - /// - [Fact] - public void PageGroupTopic_Empty_ReturnsRedirect() { + controller.Dispose(); - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Key", "PageGroup"); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); + var result = context.Result as StatusCodeResult; - validateFilter.OnActionExecuting(context); + Assert.NotNull(result); + Assert.Equal(403, result?.StatusCode); - controller.Dispose(); + } + + /*============================================================================================================================ + | TEST: NESTED TOPIC: ITEM: RETURNS 403 + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the has a + /// parent with a of List. + /// + [Fact] + public void NestedTopic_Item_Returns403() { - var result = context.Result as StatusCodeResult; + var validateFilter = new ValidateTopicAttribute(); + var list = new Topic("Key", "List"); + var topic = new Topic("Item", "Page", list); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); - Assert.NotNull(result); - Assert.Equal(403, result?.StatusCode); + validateFilter.OnActionExecuting(context); - } + controller.Dispose(); + + var result = context.Result as StatusCodeResult; + + Assert.NotNull(result); + Assert.Equal(403, result?.StatusCode); + + } + + /*============================================================================================================================ + | TEST: NESTED TOPIC: ITEM: RETURNS 403 + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the has a + /// parent with a of List. + /// + [Fact] + public void Container_Returns403() { + + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Item", "Container"); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); + + validateFilter.OnActionExecuting(context); + + controller.Dispose(); + + var result = context.Result as StatusCodeResult; + + Assert.NotNull(result); + Assert.Equal(403, result?.StatusCode); + + } + + /*============================================================================================================================ + | TEST: PAGE GROUP TOPIC: RETURNS REDIRECT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the has a + /// of PageGroup. + /// + [Fact] + public void PageGroupTopic_ReturnsRedirect() { + + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Key", "PageGroup"); + var child = new Topic("Child", "Page", topic); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); + _ = new Topic("Home", "Page", topic); + + validateFilter.OnActionExecuting(context); + + controller.Dispose(); + + Assert.IsType(context.Result); + Assert.Equal(child.GetWebPath(), ((RedirectResult?)context.Result)?.Url); + + } + + /*============================================================================================================================ + | TEST: PAGE GROUP TOPIC: EMPTY: RETURNS REDIRECT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the has a + /// of PageGroup with no . + /// + [Fact] + public void PageGroupTopic_Empty_ReturnsRedirect() { + + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Key", "PageGroup"); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); + + validateFilter.OnActionExecuting(context); + + controller.Dispose(); + + var result = context.Result as StatusCodeResult; + + Assert.NotNull(result); + Assert.Equal(403, result?.StatusCode); + + } + + /*============================================================================================================================ + | TEST: CANONICAL URL: RETURNS REDIRECT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is thrown if the has a + /// which doesn't match the current URL, even just by case. + /// + /// + /// The defines a , which doesn't + /// define a . As a result, if no other condition is met, the canonical condition should + /// always be tripped as part of these unit tests. + /// + [Fact] + public void CanonicalUrl_ReturnsRedirect() { - /*========================================================================================================================== - | TEST: CANONICAL URL: RETURNS REDIRECT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is thrown if the has a - /// which doesn't match the current URL, even just by case. - /// - /// - /// The defines a , which doesn't - /// define a . As a result, if no other condition is met, the canonical condition should - /// always be tripped as part of these unit tests. - /// - [Fact] - public void CanonicalUrl_ReturnsRedirect() { + var validateFilter = new ValidateTopicAttribute(); + var topic = new Topic("Key", "Page"); + var controller = GetTopicController(topic); + var context = GetActionExecutingContext(controller); + _ = new Topic("Home", "Page", topic); - var validateFilter = new ValidateTopicAttribute(); - var topic = new Topic("Key", "Page"); - var controller = GetTopicController(topic); - var context = GetActionExecutingContext(controller); - _ = new Topic("Home", "Page", topic); + validateFilter.OnActionExecuting(context); - validateFilter.OnActionExecuting(context); - - controller.Dispose(); + controller.Dispose(); - Assert.IsType(context.Result); + Assert.IsType(context.Result); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Components/MenuViewComponentBase{T}.cs b/OnTopic.AspNetCore.Mvc/Components/MenuViewComponentBase{T}.cs index c64da4ae..6e9cc422 100644 --- a/OnTopic.AspNetCore.Mvc/Components/MenuViewComponentBase{T}.cs +++ b/OnTopic.AspNetCore.Mvc/Components/MenuViewComponentBase{T}.cs @@ -8,131 +8,130 @@ using OnTopic.Mapping.Hierarchical; using OnTopic.Models; -namespace OnTopic.AspNetCore.Mvc.Components { +namespace OnTopic.AspNetCore.Mvc.Components; + +/*============================================================================================================================== +| CLASS: MENU VIEW COMPONENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a which provides access to a menu of instances. +/// +/// +/// +/// As a best practice, global data required by the layout view are requested independent of the current page. This allows +/// each layout element to be provided with its own layout data, in the form of a s, +/// instead of needing to add this data to every view model returned by e.g. a . +/// +/// +/// In order to remain view model agnostic, the does not assume that a particular +/// view model will be used, and instead accepts a generic argument for any view model that implements the interface . Since generic view components cannot be effectively routed to, however, that +/// means implementors must, at minimum, provide a local instance of , which sets the +/// generic value to the desired view model. To help enforce this, while avoiding ambiguity, this class is marked as +/// abstract and suffixed with Base. +/// +/// +/// While the only requires that the implement , views will require additional properties. These can be determined on a per-case +/// basis, as required by the implementation. Implementaters, however, should consider implementing the interface, which provides the standard properties that most views will likely need, as +/// well as a method for determining if the navigation item +/// is currently selected. +/// +/// +public abstract class MenuViewComponentBase : + NavigationTopicViewComponentBase where T : class, IHierarchicalTopicViewModel, new() +{ /*============================================================================================================================ - | CLASS: MENU VIEW COMPONENT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines a which provides access to a menu of instances. + /// Initializes a new instance of a with necessary dependencies. + /// + protected MenuViewComponentBase( + ITopicRepository topicRepository, + IHierarchicalTopicMappingService hierarchicalTopicMappingService + ) : base( + topicRepository, + hierarchicalTopicMappingService + ) { + } + + /*============================================================================================================================ + | METHOD: GET NAVIGATION ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// + /// Retrieves the root from which to map the objects. /// /// - /// - /// As a best practice, global data required by the layout view are requested independent of the current page. This allows - /// each layout element to be provided with its own layout data, in the form of a s, - /// instead of needing to add this data to every view model returned by e.g. a . - /// - /// - /// In order to remain view model agnostic, the does not assume that a particular - /// view model will be used, and instead accepts a generic argument for any view model that implements the interface . Since generic view components cannot be effectively routed to, however, that - /// means implementors must, at minimum, provide a local instance of , which sets the - /// generic value to the desired view model. To help enforce this, while avoiding ambiguity, this class is marked as - /// abstract and suffixed with Base. - /// - /// - /// While the only requires that the implement , views will require additional properties. These can be determined on a per-case - /// basis, as required by the implementation. Implementaters, however, should consider implementing the interface, which provides the standard properties that most views will likely need, as - /// well as a method for determining if the navigation item - /// is currently selected. - /// + /// The navigation root in the case of the main menu is the namespace; i.e., the first topic underneath the root. /// - public abstract class MenuViewComponentBase : - NavigationTopicViewComponentBase where T : class, IHierarchicalTopicViewModel, new() - { + protected Topic? GetNavigationRoot() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - protected MenuViewComponentBase( - ITopicRepository topicRepository, - IHierarchicalTopicMappingService hierarchicalTopicMappingService - ) : base( - topicRepository, - hierarchicalTopicMappingService - ) { - } + Contract.Assume(CurrentTopic, nameof(CurrentTopic)); - /*========================================================================================================================== - | METHOD: GET NAVIGATION ROOT + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify navigation root \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// - /// Retrieves the root from which to map the objects. - /// - /// - /// The navigation root in the case of the main menu is the namespace; i.e., the first topic underneath the root. - /// - protected Topic? GetNavigationRoot() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Assume(CurrentTopic, nameof(CurrentTopic)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Identify navigation root - \-----------------------------------------------------------------------------------------------------------------------*/ - var navigationRootTopic = (Topic?)null; - var configuredRoot = CurrentTopic.Attributes.GetValue("NavigationRoot", true); - - if (!String.IsNullOrEmpty(configuredRoot)) { - navigationRootTopic = TopicRepository.Load("Root:" + configuredRoot, CurrentTopic); - } - navigationRootTopic ??= HierarchicalTopicMappingService.GetHierarchicalRoot(CurrentTopic, 2, "Web"); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return root - \-----------------------------------------------------------------------------------------------------------------------*/ - return navigationRootTopic; + var navigationRootTopic = (Topic?)null; + var configuredRoot = CurrentTopic.Attributes.GetValue("NavigationRoot", true); + if (!String.IsNullOrEmpty(configuredRoot)) { + navigationRootTopic = TopicRepository.Load("Root:" + configuredRoot, CurrentTopic); } + navigationRootTopic ??= HierarchicalTopicMappingService.GetHierarchicalRoot(CurrentTopic, 2, "Web"); - /*========================================================================================================================== - | METHOD: MAP NAVIGATION TOPIC VIEW MODELS + /*-------------------------------------------------------------------------------------------------------------------------- + | Return root \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a list of instances based on the . - /// - protected async Task MapNavigationTopicViewModels(Topic? navigationRootTopic) => - await HierarchicalTopicMappingService.GetRootViewModelAsync( - navigationRootTopic!, - 3, - t => t is not { ContentType: "List" } and not { Parent.ContentType: "PageGroup" } - ).ConfigureAwait(false); - - /*========================================================================================================================== - | METHOD: INVOKE (ASYNC) + return navigationRootTopic; + + } + + /*============================================================================================================================ + | METHOD: MAP NAVIGATION TOPIC VIEW MODELS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a list of instances based on the . + /// + protected async Task MapNavigationTopicViewModels(Topic? navigationRootTopic) => + await HierarchicalTopicMappingService.GetRootViewModelAsync( + navigationRootTopic!, + 3, + t => t is not { ContentType: "List" } and not { Parent.ContentType: "PageGroup" } + ).ConfigureAwait(false); + + /*============================================================================================================================ + | METHOD: INVOKE (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the global menu for the site layout, which exposes the top two tiers of navigation. + /// + public async Task InvokeAsync() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve root topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the global menu for the site layout, which exposes the top two tiers of navigation. - /// - public async Task InvokeAsync() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve root topic - \-----------------------------------------------------------------------------------------------------------------------*/ - var navigationRootTopic = GetNavigationRoot(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Construct view model - \-----------------------------------------------------------------------------------------------------------------------*/ - var navigationViewModel = new NavigationViewModel() { - NavigationRoot = await MapNavigationTopicViewModels(navigationRootTopic).ConfigureAwait(true), - CurrentWebPath = CurrentTopic?.GetWebPath()?? HttpContext.Request.Path - }; - - /*------------------------------------------------------------------------------------------------------------------------ - | Return the corresponding view - \-----------------------------------------------------------------------------------------------------------------------*/ - return View(navigationViewModel); + var navigationRootTopic = GetNavigationRoot(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Construct view model + \-------------------------------------------------------------------------------------------------------------------------*/ + var navigationViewModel = new NavigationViewModel() { + NavigationRoot = await MapNavigationTopicViewModels(navigationRootTopic).ConfigureAwait(true), + CurrentWebPath = CurrentTopic?.GetWebPath()?? HttpContext.Request.Path + }; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return the corresponding view + \-------------------------------------------------------------------------------------------------------------------------*/ + return View(navigationViewModel); + + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Components/NavigationTopicViewComponentBase{T}.cs b/OnTopic.AspNetCore.Mvc/Components/NavigationTopicViewComponentBase{T}.cs index f3677fa5..34ccac4f 100644 --- a/OnTopic.AspNetCore.Mvc/Components/NavigationTopicViewComponentBase{T}.cs +++ b/OnTopic.AspNetCore.Mvc/Components/NavigationTopicViewComponentBase{T}.cs @@ -6,90 +6,84 @@ using OnTopic.Mapping.Hierarchical; using OnTopic.Models; -namespace OnTopic.AspNetCore.Mvc.Components { +namespace OnTopic.AspNetCore.Mvc.Components; + +/*============================================================================================================================== +| CLASS: NAVIGATION TOPIC VIEW COMPONENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a foundation for custom implementations that are based on the location of the +/// current and require access to the to populate the +/// model. +/// +/// +/// +/// This class is intended to provide a foundation for concrete implementations. It is not a fully formed implementation +/// itself. As a result, it is marked as abstract. +/// +/// +/// While the only requires that the implement +/// , views will require additional properties. These can be determined on a +/// per-case basis, as required by the implementation. Implementaters, however, should consider implementing the interface, which provides the standard properties that most views will likely need, +/// as well as a method for determining if the navigation +/// item is currently selected. +/// +/// +public abstract class NavigationTopicViewComponentBase : ViewComponent where T : class, IHierarchicalTopicViewModel, new() { /*============================================================================================================================ - | CLASS: NAVIGATION TOPIC VIEW COMPONENT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines a foundation for custom implementations that are based on the location of the - /// current and require access to the to populate the - /// model. + /// Initializes a new instance of a with necessary dependencies. /// - /// - /// - /// This class is intended to provide a foundation for concrete implementations. It is not a fully formed implementation - /// itself. As a result, it is marked as abstract. - /// - /// - /// While the only requires that the implement - /// , views will require additional properties. These can be determined on a - /// per-case basis, as required by the implementation. Implementaters, however, should consider implementing the interface, which provides the standard properties that most views will likely need, - /// as well as a method for determining if the navigation - /// item is currently selected. - /// - /// - public abstract class NavigationTopicViewComponentBase : ViewComponent where T : class, IHierarchicalTopicViewModel, new() { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private Topic? _currentTopic; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - /// A topic . - protected NavigationTopicViewComponentBase( - ITopicRepository topicRepository, - IHierarchicalTopicMappingService hierarchicalTopicMappingService - ) { - TopicRepository = topicRepository; - HierarchicalTopicMappingService = hierarchicalTopicMappingService; - } + /// A topic . + protected NavigationTopicViewComponentBase( + ITopicRepository topicRepository, + IHierarchicalTopicMappingService hierarchicalTopicMappingService + ) { + TopicRepository = topicRepository; + HierarchicalTopicMappingService = hierarchicalTopicMappingService; + } - /*========================================================================================================================== - | TOPIC REPOSITORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the in order to allow the current topic to be identified based - /// on the route data. - /// - /// - /// The associated with the . - /// - protected ITopicRepository TopicRepository { get; } + /*============================================================================================================================ + | TOPIC REPOSITORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the in order to allow the current topic to be identified based + /// on the route data. + /// + /// + /// The associated with the . + /// + protected ITopicRepository TopicRepository { get; } - /*========================================================================================================================== - | HIERARCHICAL TOPIC MAPPING SERVICE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the in order to allow trees of topics to - /// be mapped. - /// - /// - /// The associated with the . - /// - protected IHierarchicalTopicMappingService HierarchicalTopicMappingService { get; } + /*============================================================================================================================ + | HIERARCHICAL TOPIC MAPPING SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the in order to allow trees of topics to + /// be mapped. + /// + /// + /// The associated with the . + /// + protected IHierarchicalTopicMappingService HierarchicalTopicMappingService { get; } - /*========================================================================================================================== - | CURRENT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the current topic associated with the request. - /// - /// The Topic associated with the current request. - protected Topic? CurrentTopic { - get { - _currentTopic ??= TopicRepository.Load(RouteData); - return _currentTopic; - } + /*============================================================================================================================ + | CURRENT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the current topic associated with the request. + /// + /// The Topic associated with the current request. + protected Topic? CurrentTopic { + get { + field ??= TopicRepository.Load(RouteData); + return field; } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Components/PageLevelNavigationViewComponentBase{T}.cs b/OnTopic.AspNetCore.Mvc/Components/PageLevelNavigationViewComponentBase{T}.cs index c012934e..3a7f11df 100644 --- a/OnTopic.AspNetCore.Mvc/Components/PageLevelNavigationViewComponentBase{T}.cs +++ b/OnTopic.AspNetCore.Mvc/Components/PageLevelNavigationViewComponentBase{T}.cs @@ -3,134 +3,135 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ +using System.Diagnostics.CodeAnalysis; using OnTopic.AspNetCore.Mvc.Controllers; using OnTopic.AspNetCore.Mvc.Models; using OnTopic.Mapping.Hierarchical; using OnTopic.Models; -namespace OnTopic.AspNetCore.Mvc.Components { +namespace OnTopic.AspNetCore.Mvc.Components; + +/*============================================================================================================================== +| CLASS: PAGE-LEVEL NAVIGATION VIEW COMPONENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a which provides access to a menu of instances representing +/// the nearest page-level navigation. +/// +/// +/// +/// As a best practice, global data required by the layout view are requested independent of the current page. This +/// allows each layout element to be provided with its own layout data, in the form of s, instead of needing to add this data to every view model returned by . +/// +/// +/// In order to remain view model agnostic, the does not assume that +/// a particular view model will be used, and instead accepts a generic argument for any view model that implements the +/// interface . Since generic view components cannot be effectively routed to, +/// however, that means implementors must, at minimum, provide a local instance of which sets the generic value to the desired view model. To help +/// enforce this, while avoiding ambiguity, this class is marked as abstract and suffixed with Base. +/// +/// +/// While the only requires that the +/// implement , views will require additional properties. These can be +/// determined on a per-case basis, as required by the implementation. Implementaters, however, should consider +/// implementing the interface, which provides the standard properties that +/// most views will likely need, as well as a method for +/// determining if the navigation item is currently selected. +/// +/// +public abstract class PageLevelNavigationViewComponentBase : + NavigationTopicViewComponentBase where T : class, IHierarchicalTopicViewModel, new() +{ + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of a with necessary dependencies. + /// + protected PageLevelNavigationViewComponentBase( + ITopicRepository topicRepository, + IHierarchicalTopicMappingService hierarchicalTopicMappingService + ) : base( + topicRepository, + hierarchicalTopicMappingService + ) {} /*============================================================================================================================ - | CLASS: PAGE-LEVEL NAVIGATION VIEW COMPONENT + | METHOD: GET NAVIGATION ROOT \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines a which provides access to a menu of instances representing - /// the nearest page-level navigation. + /// Retrieves the root from which to map the objects. /// /// - /// - /// As a best practice, global data required by the layout view are requested independent of the current page. This - /// allows each layout element to be provided with its own layout data, in the form of s, instead of needing to add this data to every view model returned by . - /// - /// - /// In order to remain view model agnostic, the does not assume that - /// a particular view model will be used, and instead accepts a generic argument for any view model that implements the - /// interface . Since generic view components cannot be effectively routed to, - /// however, that means implementors must, at minimum, provide a local instance of which sets the generic value to the desired view model. To help - /// enforce this, while avoiding ambiguity, this class is marked as abstract and suffixed with Base. - /// - /// - /// While the only requires that the - /// implement , views will require additional properties. These can be - /// determined on a per-case basis, as required by the implementation. Implementaters, however, should consider - /// implementing the interface, which provides the standard properties that - /// most views will likely need, as well as a method for - /// determining if the navigation item is currently selected. - /// + /// The navigation root in the case of the page-level navigation any parent of content type PageGroup. /// - public abstract class PageLevelNavigationViewComponentBase : - NavigationTopicViewComponentBase where T : class, IHierarchicalTopicViewModel, new() - { + [SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "This walks the parent hierarchy, so it isn't appropriate as a property.")] + protected Topic? GetNavigationRoot() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - protected PageLevelNavigationViewComponentBase( - ITopicRepository topicRepository, - IHierarchicalTopicMappingService hierarchicalTopicMappingService - ) : base( - topicRepository, - hierarchicalTopicMappingService - ) {} + var currentTopic = CurrentTopic; + var navigationRootTopic = (Topic?)currentTopic; - /*========================================================================================================================== - | METHOD: GET NAVIGATION ROOT + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify navigation root \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the root from which to map the objects. - /// - /// - /// The navigation root in the case of the page-level navigation any parent of content type PageGroup. - /// - protected Topic? GetNavigationRoot() { + if (navigationRootTopic is not null) { + while ( + navigationRootTopic is not null and not ({ Parent: null } or { ContentType: "PageGroup" }) + ) { + navigationRootTopic = navigationRootTopic.Parent; + } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var currentTopic = CurrentTopic; - var navigationRootTopic = (Topic?)currentTopic; + /*-------------------------------------------------------------------------------------------------------------------------- + | Return root + \-------------------------------------------------------------------------------------------------------------------------*/ + return navigationRootTopic?.Parent is null? null : navigationRootTopic; - /*------------------------------------------------------------------------------------------------------------------------ - | Identify navigation root - \-----------------------------------------------------------------------------------------------------------------------*/ - if (navigationRootTopic is not null) { - while ( - navigationRootTopic is not null and not ({ Parent: null } or { ContentType: "PageGroup" }) - ) { - navigationRootTopic = navigationRootTopic.Parent; - } - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return root - \-----------------------------------------------------------------------------------------------------------------------*/ - return navigationRootTopic?.Parent is null? null : navigationRootTopic; + /*============================================================================================================================ + | METHOD: MAP NAVIGATION TOPIC VIEW MODELS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a list of instances based on the . + /// + protected async Task MapNavigationTopicViewModels(Topic? navigationRootTopic) => + await HierarchicalTopicMappingService.GetRootViewModelAsync(navigationRootTopic).ConfigureAwait(true); - } + /*============================================================================================================================ + | METHOD: INVOKE (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the pagel-level navigation menu for the current page, which exposes one tier of navigation from the nearest + /// page group. + /// + public async Task InvokeAsync() { - /*========================================================================================================================== - | METHOD: MAP NAVIGATION TOPIC VIEW MODELS + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve root topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a list of instances based on the . - /// - protected async Task MapNavigationTopicViewModels(Topic? navigationRootTopic) => - await HierarchicalTopicMappingService.GetRootViewModelAsync(navigationRootTopic).ConfigureAwait(true); + var navigationRootTopic = GetNavigationRoot(); - /*========================================================================================================================== - | METHOD: INVOKE (ASYNC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Construct view model \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the pagel-level navigation menu for the current page, which exposes one tier of navigation from the nearest - /// page group. - /// - public async Task InvokeAsync() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve root topic - \-----------------------------------------------------------------------------------------------------------------------*/ - var navigationRootTopic = GetNavigationRoot(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Construct view model - \-----------------------------------------------------------------------------------------------------------------------*/ - var navigationViewModel = new NavigationViewModel() { - NavigationRoot = await MapNavigationTopicViewModels(navigationRootTopic).ConfigureAwait(true), - CurrentWebPath = CurrentTopic?.GetWebPath()?? HttpContext.Request.Path - }; + var navigationViewModel = new NavigationViewModel() { + NavigationRoot = await MapNavigationTopicViewModels(navigationRootTopic).ConfigureAwait(true), + CurrentWebPath = CurrentTopic?.GetWebPath()?? HttpContext.Request.Path + }; - /*------------------------------------------------------------------------------------------------------------------------ - | Return the corresponding view - \-----------------------------------------------------------------------------------------------------------------------*/ - return View(navigationViewModel); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return the corresponding view + \-------------------------------------------------------------------------------------------------------------------------*/ + return View(navigationViewModel); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Controllers/ErrorController.cs b/OnTopic.AspNetCore.Mvc/Controllers/ErrorController.cs index 3d900fdf..3cb9a557 100644 --- a/OnTopic.AspNetCore.Mvc/Controllers/ErrorController.cs +++ b/OnTopic.AspNetCore.Mvc/Controllers/ErrorController.cs @@ -7,78 +7,77 @@ using Microsoft.AspNetCore.Diagnostics; using OnTopic.Mapping; -namespace OnTopic.AspNetCore.Mvc.Controllers { +namespace OnTopic.AspNetCore.Mvc.Controllers; + +/*============================================================================================================================== +| CLASS: ERROR CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a default handler for responding to requests from the configuration. +/// +/// +/// The will redirect to a URL with the +/// HTTP error code in the route. This is fine if there is one error page that, perhaps, injects the error code into the +/// content. It's also fine if there is an error page for every HTTP error. In practice, however, many sites handle some +/// HTTP errors, but not others. Given this, the provides logic to deliver a associated with the HTTP error, if available, and otherwise to fallback first to the +/// HTTP category (e.g., 5xx), and otherwise to a generic error. +/// +public class ErrorController : TopicController { /*============================================================================================================================ - | CLASS: ERROR CONTROLLER + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a default handler for responding to requests from the configuration. + /// Initializes a new instance of an Error Controller with necessary dependencies. /// - /// - /// The will redirect to a URL with the - /// HTTP error code in the route. This is fine if there is one error page that, perhaps, injects the error code into the - /// content. It's also fine if there is an error page for every HTTP error. In practice, however, many sites handle some - /// HTTP errors, but not others. Given this, the provides logic to deliver a associated with the HTTP error, if available, and otherwise to fallback first to the - /// HTTP category (e.g., 5xx), and otherwise to a generic error. - /// - public class ErrorController : TopicController { + /// An error controller for loading views associated with HTTP error codes. + public ErrorController( + ITopicRepository topicRepository, + ITopicMappingService topicMappingService + ) : base( + topicRepository, + topicMappingService + ) { } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of an Error Controller with necessary dependencies. - /// - /// An error controller for loading views associated with HTTP error codes. - public ErrorController( - ITopicRepository topicRepository, - ITopicMappingService topicMappingService - ) : base( - topicRepository, - topicMappingService - ) { } + /*============================================================================================================================ + | GET: HTTP ERROR (VIEW TOPIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Evaluates the against configured s, and returns the most appropriate + /// content available. + /// + /// A view associated with the requested current . + public async virtual Task HttpAsync([FromRoute(Name="id")] int statusCode, bool includeStaticFiles = true) { - /*========================================================================================================================== - | GET: HTTP ERROR (VIEW TOPIC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Bypass for resources \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates the against configured s, and returns the most appropriate - /// content available. - /// - /// A view associated with the requested current . - public async virtual Task HttpAsync([FromRoute(Name="id")] int statusCode, bool includeStaticFiles = true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Bypass for resources - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!includeStaticFiles) { - var feature = HttpContext.Features.Get(); - if (feature?.OriginalPath.Contains('.', StringComparison.Ordinal)?? false) { - return Content("The resource requested could not found."); - } + if (!includeStaticFiles) { + var feature = HttpContext.Features.Get(); + if (feature?.OriginalPath.Contains('.', StringComparison.Ordinal)?? false) { + return Content("The resource requested could not found."); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify base path - \-----------------------------------------------------------------------------------------------------------------------*/ - var rootTopic = HttpContext.Request.RouteValues.GetValueOrDefault("rootTopic") as string?? "Error"; + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify base path + \-------------------------------------------------------------------------------------------------------------------------*/ + var rootTopic = HttpContext.Request.RouteValues.GetValueOrDefault("rootTopic") as string?? "Error"; - /*------------------------------------------------------------------------------------------------------------------------ - | Identify relevant topic - \-----------------------------------------------------------------------------------------------------------------------*/ - CurrentTopic = TopicRepository.Load($"{rootTopic}:{statusCode}")?? - TopicRepository.Load($"{rootTopic}:{statusCode/100*100}")?? - TopicRepository.Load($"{rootTopic}"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify relevant topic + \-------------------------------------------------------------------------------------------------------------------------*/ + CurrentTopic = TopicRepository.Load($"{rootTopic}:{statusCode}")?? + TopicRepository.Load($"{rootTopic}:{statusCode/100*100}")?? + TopicRepository.Load($"{rootTopic}"); - /*------------------------------------------------------------------------------------------------------------------------ - | Return topic view - \-----------------------------------------------------------------------------------------------------------------------*/ - return await IndexAsync(CurrentTopic?.GetWebPath()?? "Error").ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return topic view + \-------------------------------------------------------------------------------------------------------------------------*/ + return await IndexAsync(CurrentTopic?.GetWebPath()?? "Error").ConfigureAwait(false); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Controllers/RedirectController.cs b/OnTopic.AspNetCore.Mvc/Controllers/RedirectController.cs index 33de99c0..593ac5e9 100644 --- a/OnTopic.AspNetCore.Mvc/Controllers/RedirectController.cs +++ b/OnTopic.AspNetCore.Mvc/Controllers/RedirectController.cs @@ -4,69 +4,57 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.AspNetCore.Mvc.Controllers { +namespace OnTopic.AspNetCore.Mvc.Controllers; + +/*============================================================================================================================== +| CLASS: REDIRECT CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Handles redirect based on TopicID, thus allowing permanent redirects to be setup. +/// +/// +/// Typically, a page is requested based on the value, which is a hash of +/// its . When a is moved to a different location in the topic graph, +/// however, its will return a different value, corresponding to its new location. To allow +/// permanent references to page, therefore, the accepts paths based on the , which is expected to be stable for the lifetime of a entity. +/// +/// +/// An implementation of an to retrieve the current from. +/// +public class RedirectController(ITopicRepository topicRepository) : Controller { /*============================================================================================================================ - | CLASS: REDIRECT CONTROLLER + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ITopicRepository _topicRepository = topicRepository; + + /*============================================================================================================================ + | REDIRECT \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Handles redirect based on TopicID, thus allowing permanent redirects to be setup. + /// Redirect based on . /// - /// - /// Typically, a page is requested based on the value, which is a hash of - /// its . When a is moved to a different location in the topic graph, - /// however, its will return a different value, corresponding to its new location. To allow - /// permanent references to page, therefore, the accepts paths based on the , which is expected to be stable for the lifetime of a entity. - /// - public class RedirectController : Controller { + /// The to lookup in the . + public ActionResult Redirect(int topicId) { - /*========================================================================================================================== - | PRIVATE VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Find the topic with the correct PageID. \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITopicRepository _topicRepository; + var topic = _topicRepository.Load(topicId); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide error handling \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a Topic Controller with necessary dependencies. - /// - /// - /// An implementation of an to retrieve the current from. - /// - /// A topic controller for loading OnTopic views. - public RedirectController(ITopicRepository topicRepository) : base() { - _topicRepository = topicRepository; + if (topic is null) { + return NotFound("Invalid TopicID."); } - /*========================================================================================================================== - | REDIRECT + /*-------------------------------------------------------------------------------------------------------------------------- + | Perform redirect \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Redirect based on . - /// - /// The to lookup in the . - public ActionResult Redirect(int topicId) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Find the topic with the correct PageID. - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = _topicRepository.Load(topicId); + return RedirectPermanent(topic.GetWebPath()); - /*------------------------------------------------------------------------------------------------------------------------ - | Provide error handling - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) { - return NotFound("Invalid TopicID."); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Perform redirect - \-----------------------------------------------------------------------------------------------------------------------*/ - return RedirectPermanent(topic.GetWebPath()); - - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Controllers/SitemapController.cs b/OnTopic.AspNetCore.Mvc/Controllers/SitemapController.cs index ec21a475..f055fcfd 100644 --- a/OnTopic.AspNetCore.Mvc/Controllers/SitemapController.cs +++ b/OnTopic.AspNetCore.Mvc/Controllers/SitemapController.cs @@ -9,282 +9,265 @@ using System.Xml.Linq; using OnTopic.Attributes; -namespace OnTopic.AspNetCore.Mvc.Controllers { +namespace OnTopic.AspNetCore.Mvc.Controllers; + +/*============================================================================================================================== +| CLASS: SITEMAP CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Responds to requests for a sitemap according to sitemap.org's schema. The view is expected to recursively loop over +/// child topics to generate the appropriate markup. +/// +/// +/// +/// By default, some s are excluded based on their content types—which includes not only the +/// , but also all of its descendents. Other s are skipped, also based on +/// their content types; in this case, the is excluded, but its descendents are not. What content +/// types are excluded or skipped can be configured, respectively, by modifying the static and collections. +/// +/// +/// The action enables an extended sitemap with Google's custom PageMap schema for +/// exposing , , and . By +/// default, some content attributes, such as Body, IsDisabled, and NoIndex, are hidden. This list +/// can be modified by updating the static collection. +/// +/// +/// +/// The used to retrieve instances for the sitemap. +/// +public class SitemapController(ITopicRepository topicRepository) : Controller { /*============================================================================================================================ - | CLASS: SITEMAP CONTROLLER + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ITopicRepository _topicRepository = Contract.Requires(topicRepository); + + /*============================================================================================================================ + | CONSTANTS + \---------------------------------------------------------------------------------------------------------------------------*/ + private static readonly XNamespace _sitemapNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; + private static readonly XNamespace _pagemapNamespace = "http://www.google.com/schemas/sitemap-pagemap/1.0"; + + /*============================================================================================================================ + | EXCLUDED CONTENT TYPES \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Responds to requests for a sitemap according to sitemap.org's schema. The view is expected to recursively loop over - /// child topics to generate the appropriate markup. + /// Specifies what content types should not be listed in the sitemap, including any descendents. /// - /// - /// - /// By default, some s are excluded based on their content types—which includes not only the - /// , but also all of its descendents. Other s are skipped, also based on - /// their content types; in this case, the is excluded, but its descendents are not. What content - /// types are excluded or skipped can be configured, respectively, by modifying the static and collections. - /// - /// - /// The action enables an extended sitemap with Google's custom PageMap schema for - /// exposing , , and . By - /// default, some content attributes, such as Body, IsDisabled, and NoIndex, are hidden. This list - /// can be modified by updating the static collection. - /// - /// - public class SitemapController : Controller { + public static Collection ExcludedContentTypes { get; } = new() { + "List" + }; - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITopicRepository _topicRepository; + /*============================================================================================================================ + | SKIPPED CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Specifies what content types should not be listed in the sitemap—but whose descendents should still be evaluated. + /// + public static Collection SkippedContentTypes { get; } = new() { + "PageGroup", + "Container" + }; - /*========================================================================================================================== - | CONSTANTS - \-------------------------------------------------------------------------------------------------------------------------*/ - private static readonly XNamespace _sitemapNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; - private static readonly XNamespace _pagemapNamespace = "http://www.google.com/schemas/sitemap-pagemap/1.0"; + /*============================================================================================================================ + | EXCLUDED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Specifies what attributes should not be listed in the sitemap. + /// + public static Collection ExcludedAttributes { get; } = new() { + "Body", + "IsDisabled", + "ParentID", //Legacy, but exposed for avoid leacking legacy data + "TopicID", //Legacy, but exposed for avoid leacking legacy data + "ContentType", //Legacy, but exposed for avoid leacking legacy data + "IsHidden", + "NoIndex", + "SortOrder" + }; - /*========================================================================================================================== - | EXCLUDED CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Specifies what content types should not be listed in the sitemap, including any descendents. - /// - public static Collection ExcludedContentTypes { get; } = new() { - "List" - }; + /*============================================================================================================================ + | GET: /SITEMAP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the Sitemap.org sitemap for the site. + /// + /// Optionally enables indentation of XML elements in output for human readability. + /// Optionally enables extended metadata associated with each topic. + /// A Sitemap.org sitemap. + public ActionResult Index(bool indent = false, bool includeMetadata = false) { - /*========================================================================================================================== - | SKIPPED CONTENT TYPES + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure topics are loaded \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Specifies what content types should not be listed in the sitemap—but whose descendents should still be evaluated. - /// - public static Collection SkippedContentTypes { get; } = new() { - "PageGroup", - "Container" - }; + var rootTopic = _topicRepository.Load(); - /*========================================================================================================================== - | EXCLUDED ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Specifies what attributes should not be listed in the sitemap. - /// - public static Collection ExcludedAttributes { get; } = new() { - "Body", - "IsDisabled", - "ParentID", //Legacy, but exposed for avoid leacking legacy data - "TopicID", //Legacy, but exposed for avoid leacking legacy data - "ContentType", //Legacy, but exposed for avoid leacking legacy data - "IsHidden", - "NoIndex", - "SortOrder" - }; + Contract.Assume( + rootTopic, + $"The topic graph could not be successfully loaded from the {nameof(ITopicRepository)} instance. The " + + $"{nameof(SitemapController)} is unable to establish a local copy to work off of." + ); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish sitemap \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a Topic Controller with necessary dependencies. - /// - /// A topic controller for loading OnTopic views. - public SitemapController(ITopicRepository topicRepository) { + var declaration = new XDeclaration("1.0", "utf-8", "no"); + var sitemap = GenerateSitemap(rootTopic, includeMetadata); + var settings = indent? SaveOptions.None : SaveOptions.DisableFormatting; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicRepository, nameof(topicRepository)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = topicRepository; - - } - - /*========================================================================================================================== - | GET: /SITEMAP + /*-------------------------------------------------------------------------------------------------------------------------- + | Return the homepage view \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the Sitemap.org sitemap for the site. - /// - /// Optionally enables indentation of XML elements in output for human readability. - /// Optionally enables extended metadata associated with each topic. - /// A Sitemap.org sitemap. - public ActionResult Index(bool indent = false, bool includeMetadata = false) { + return Content(declaration.ToString() + sitemap.ToString(settings), "text/xml"); - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure topics are loaded - \-----------------------------------------------------------------------------------------------------------------------*/ - var rootTopic = _topicRepository.Load(); + } - Contract.Assume( - rootTopic, - $"The topic graph could not be successfully loaded from the {nameof(ITopicRepository)} instance. The " + - $"{nameof(SitemapController)} is unable to establish a local copy to work off of." - ); + /*============================================================================================================================ + | GET: /SITEMAP/EXTENDED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the Sitemap.org sitemap for the site, including extended metadata attributes. + /// + /// + /// Introducing the metadata makes the sitemap considerably larger. However, it also means that some agents will index the + /// additional information and make it available for querying. For instance, the (now defunct) Google Custom Search Engine + /// (CSE) would previously allow queries to be filtered based on metadata attributes exposed via the sitemap. + /// + /// Optionally enables indentation of XML elements in output for human readability. + /// A Sitemap.org sitemap. + public ActionResult Extended(bool indent = false) => Index(indent, true); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish sitemap - \-----------------------------------------------------------------------------------------------------------------------*/ - var declaration = new XDeclaration("1.0", "utf-8", "no"); - var sitemap = GenerateSitemap(rootTopic, includeMetadata); - var settings = indent? SaveOptions.None : SaveOptions.DisableFormatting; + /*============================================================================================================================ + | METHOD: GENERATE SITEMAP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a root topic, generates an XML-formatted sitemap. + /// + /// The topic to add to the sitemap. + /// Optionally enables extended metadata associated with each topic. + /// A Sitemap.org sitemap. + private XDocument GenerateSitemap(Topic rootTopic, bool includeMetadata = false) => + new( + new XElement(_sitemapNamespace + "urlset", + from topic in rootTopic.Children + select AddTopic(topic, includeMetadata) + ) + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Return the homepage view - \-----------------------------------------------------------------------------------------------------------------------*/ - return Content(declaration.ToString() + sitemap.ToString(settings), "text/xml"); + /*============================================================================================================================ + | METHOD: ADD TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , adds it to a given . + /// + /// The topic to add to the sitemap. + /// Optionally enables extended metadata associated with each topic. + private List AddTopic(Topic topic, bool includeMetadata = false) { - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish return collection + \-------------------------------------------------------------------------------------------------------------------------*/ + var topics = new List(); - /*========================================================================================================================== - | GET: /SITEMAP/EXTENDED + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the Sitemap.org sitemap for the site, including extended metadata attributes. - /// - /// - /// Introducing the metadata makes the sitemap considerably larger. However, it also means that some agents will index the - /// additional information and make it available for querying. For instance, the (now defunct) Google Custom Search Engine - /// (CSE) would previously allow queries to be filtered based on metadata attributes exposed via the sitemap. - /// - /// Optionally enables indentation of XML elements in output for human readability. - /// A Sitemap.org sitemap. - public ActionResult Extended(bool indent = false) => Index(indent, true); + if ( + topic.Attributes.GetBoolean("IsPrivateBranch") || + topic.ContentType.Equals("Container", StringComparison.OrdinalIgnoreCase) && + topic.Attributes.GetBoolean("NoIndex") + ) return topics; + if (ExcludedContentTypes.Any(c => topic.ContentType.Equals(c, StringComparison.OrdinalIgnoreCase))) return topics; - /*========================================================================================================================== - | METHOD: GENERATE SITEMAP + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a root topic, generates an XML-formatted sitemap. - /// - /// The topic to add to the sitemap. - /// Optionally enables extended metadata associated with each topic. - /// A Sitemap.org sitemap. - private XDocument GenerateSitemap(Topic rootTopic, bool includeMetadata = false) => - new( - new XElement(_sitemapNamespace + "urlset", - from topic in rootTopic.Children - select AddTopic(topic, includeMetadata) - ) - ); + var domain = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; + var lastModified = new DateTime(Math.Max(topic.LastModified.Ticks, new DateTime(2000, 1, 1).Ticks)); - /*========================================================================================================================== - | METHOD: ADD TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish root element \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , adds it to a given . - /// - /// The topic to add to the sitemap. - /// Optionally enables extended metadata associated with each topic. - private IEnumerable AddTopic(Topic topic, bool includeMetadata = false) { + var topicElement = new XElement(_sitemapNamespace + "url", + new XElement(_sitemapNamespace + "loc", domain + topic.GetWebPath()), + new XElement(_sitemapNamespace + "changefreq", "monthly"), + new XElement(_sitemapNamespace + "lastmod", lastModified.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)), + new XElement(_sitemapNamespace + "priority", 1), + includeMetadata? new XElement(_pagemapNamespace + "PageMap", + getAttributes(), + getRelationships(), + getReferences() + ) : null + ); + if ( + !SkippedContentTypes.Any(c => topic.ContentType?.Equals(c, StringComparison.OrdinalIgnoreCase)?? false) && + String.IsNullOrWhiteSpace(topic.Attributes.GetValue("Url")) && + !topic.Attributes.GetBoolean("NoIndex") && + !topic.Attributes.GetBoolean("IsDisabled") + ) { + topics.Add(topicElement); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish return collection - \-----------------------------------------------------------------------------------------------------------------------*/ - var topics = new List(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Iterate over children + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var childTopic in topic.Children) { + topics.AddRange(AddTopic(childTopic, includeMetadata)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate topic - \-----------------------------------------------------------------------------------------------------------------------*/ - if ( - topic.Attributes.GetBoolean("IsPrivateBranch") || - topic.ContentType.Equals("Container", StringComparison.OrdinalIgnoreCase) && - topic.Attributes.GetBoolean("NoIndex") - ) return topics; - if (ExcludedContentTypes.Any(c => topic.ContentType.Equals(c, StringComparison.OrdinalIgnoreCase))) return topics; + return topics; - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var domain = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; - var lastModified = new DateTime(Math.Max(topic.LastModified.Ticks, new DateTime(2000, 1, 1).Ticks)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Get attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + XElement getAttributes() => + new(_pagemapNamespace + "DataObject", + new XAttribute("type", "Attributes"), + new XElement(_pagemapNamespace + "Attribute", + new XAttribute("name", "ContentType"), + new XText(topic.ContentType?? "Page") + ), + from attribute in topic.Attributes + let attributeValue = topic.Attributes.GetValue(attribute.Key) + where !ExcludedAttributes.Contains(attribute.Key, StringComparer.OrdinalIgnoreCase) + where attributeValue?.Length < 256 + select new XElement(_pagemapNamespace + "Attribute", + new XAttribute("name", attribute.Key), + new XText(attributeValue ?? "") + ) + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish root element - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicElement = new XElement(_sitemapNamespace + "url", - new XElement(_sitemapNamespace + "loc", domain + topic.GetWebPath()), - new XElement(_sitemapNamespace + "changefreq", "monthly"), - new XElement(_sitemapNamespace + "lastmod", lastModified.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)), - new XElement(_sitemapNamespace + "priority", 1), - includeMetadata? new XElement(_pagemapNamespace + "PageMap", - getAttributes(), - getRelationships(), - getReferences() - ) : null + /*-------------------------------------------------------------------------------------------------------------------------- + | Get relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + IEnumerable getRelationships() => + from relationship in topic.Relationships + select new XElement(_pagemapNamespace + "DataObject", + new XAttribute("type", relationship.Key), + from relatedTopic in relationship.Values + select new XElement(_pagemapNamespace + "Attribute", + new XAttribute("name", "TopicKey"), + new XText(relatedTopic.GetUniqueKey().Replace("Root:", "", StringComparison.OrdinalIgnoreCase)) + ) ); - if ( - !SkippedContentTypes.Any(c => topic.ContentType?.Equals(c, StringComparison.OrdinalIgnoreCase)?? false) && - String.IsNullOrWhiteSpace(topic.Attributes.GetValue("Url")) && - !topic.Attributes.GetBoolean("NoIndex") && - !topic.Attributes.GetBoolean("IsDisabled") - ) { - topics.Add(topicElement); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Iterate over children - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var childTopic in topic.Children) { - topics.AddRange(AddTopic(childTopic, includeMetadata)); - } - return topics; - - /*------------------------------------------------------------------------------------------------------------------------ - | Get attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - XElement getAttributes() => - new(_pagemapNamespace + "DataObject", - new XAttribute("type", "Attributes"), - new XElement(_pagemapNamespace + "Attribute", - new XAttribute("name", "ContentType"), - new XText(topic.ContentType?? "Page") - ), - from attribute in topic.Attributes - where !ExcludedAttributes.Contains(attribute.Key, StringComparer.OrdinalIgnoreCase) - where topic.Attributes.GetValue(attribute.Key)?.Length < 256 + /*-------------------------------------------------------------------------------------------------------------------------- + | Get references + \-------------------------------------------------------------------------------------------------------------------------*/ + XElement? getReferences() => + topic.References.Count is 0? + null : + new XElement(_pagemapNamespace + "DataObject", + new XAttribute("type", "References"), + from reference in topic.References + where reference.Value is not null select new XElement(_pagemapNamespace + "Attribute", - new XAttribute("name", attribute.Key), - new XText(topic.Attributes.GetValue(attribute.Key)) + new XAttribute("name", reference.Key), + new XText(reference.Value!.GetUniqueKey().Replace("Root:", "", StringComparison.OrdinalIgnoreCase)) ) ); - /*------------------------------------------------------------------------------------------------------------------------ - | Get relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - IEnumerable getRelationships() => - from relationship in topic.Relationships - select new XElement(_pagemapNamespace + "DataObject", - new XAttribute("type", relationship.Key), - from relatedTopic in relationship.Values - select new XElement(_pagemapNamespace + "Attribute", - new XAttribute("name", "TopicKey"), - new XText(relatedTopic.GetUniqueKey().Replace("Root:", "", StringComparison.OrdinalIgnoreCase)) - ) - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Get references - \-----------------------------------------------------------------------------------------------------------------------*/ - XElement? getReferences() => - topic.References.Count is 0? - null : - new XElement(_pagemapNamespace + "DataObject", - new XAttribute("type", "References"), - from reference in topic.References - select new XElement(_pagemapNamespace + "Attribute", - new XAttribute("name", reference.Key), - new XText(reference.Value?.GetUniqueKey().Replace("Root:", "", StringComparison.OrdinalIgnoreCase)) - ) - ); - - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Controllers/TopicController.cs b/OnTopic.AspNetCore.Mvc/Controllers/TopicController.cs index 2932bbf7..c761af9f 100644 --- a/OnTopic.AspNetCore.Mvc/Controllers/TopicController.cs +++ b/OnTopic.AspNetCore.Mvc/Controllers/TopicController.cs @@ -5,120 +5,98 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.AspNetCore.Mvc.Controllers { +namespace OnTopic.AspNetCore.Mvc.Controllers; + +/*============================================================================================================================== +| CLASS: TOPIC CONTROLLER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a default ASP.NET MVC Controller for any paths associated with the Ignia Topic Library. Responsible for +/// identifying the topic associated with the given path, determining its content type, and returning a view associated with +/// that content type (with potential overrides for multiple views). +/// +/// +/// A concrete implementation of an for loading topics. +/// +/// +/// A concrete implementation of an for mapping topics to view models. +/// +[TopicResponseCache] +public class TopicController(ITopicRepository topicRepository, ITopicMappingService topicMappingService) : Controller { /*============================================================================================================================ - | CLASS: TOPIC CONTROLLER + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ITopicMappingService _topicMappingService = Contract.Requires(topicMappingService); + + /*============================================================================================================================ + | TOPIC REPOSITORY \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a default ASP.NET MVC Controller for any paths associated with the Ignia Topic Library. Responsible for - /// identifying the topic associated with the given path, determining its content type, and returning a view associated with - /// that content type (with potential overrides for multiple views). + /// Provides a reference to the Topic Repository in order to gain arbitrary access to the entire topic graph. /// - [TopicResponseCache] - public class TopicController : Controller { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITopicMappingService _topicMappingService; - private Topic? _currentTopic; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a Topic Controller with necessary dependencies. - /// - /// A topic controller for loading OnTopic views. - public TopicController( - ITopicRepository topicRepository, - ITopicMappingService topicMappingService - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicRepository, "A concrete implementation of an ITopicRepository is required."); - Contract.Requires(topicMappingService, "A concrete implementation of an ITopicMappingService is required."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set values locally - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicRepository = topicRepository; - _topicMappingService = topicMappingService; + /// The TopicRepository associated with the controller. + protected internal ITopicRepository TopicRepository { get; } = Contract.Requires(topicRepository); + /*============================================================================================================================ + | CURRENT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the current topic associated with the request. + /// + /// The Topic associated with the current request. + public Topic? CurrentTopic { + get { + field ??= TopicRepository.Load(RouteData); + return field; } + set => field = value; + } - /*========================================================================================================================== - | TOPIC REPOSITORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the Topic Repository in order to gain arbitrary access to the entire topic graph. - /// - /// The TopicRepository associated with the controller. - protected internal ITopicRepository TopicRepository { get; } + /*============================================================================================================================ + | GET: INDEX (VIEW TOPIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides access to a view associated with the current topic's Content Type, if appropriate, view (as defined by the + /// query string or topic's view. + /// + /// A view associated with the requested topic's Content Type and view. + [ValidateTopic] + public async virtual Task IndexAsync(string path) { - /*========================================================================================================================== - | CURRENT TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish default view model \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the current topic associated with the request. - /// - /// The Topic associated with the current request. - public Topic? CurrentTopic { - get { - _currentTopic ??= TopicRepository.Load(RouteData); - return _currentTopic; - } - set => _currentTopic = value; - } + var topicViewModel = await _topicMappingService.MapAsync(CurrentTopic).ConfigureAwait(false); - /*========================================================================================================================== - | GET: INDEX (VIEW TOPIC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides access to a view associated with the current topic's Content Type, if appropriate, view (as defined by the - /// query string or topic's view. - /// - /// A view associated with the requested topic's Content Type and view. - [ValidateTopic] - public async virtual Task IndexAsync(string path) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish default view model - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicViewModel = await _topicMappingService.MapAsync(CurrentTopic).ConfigureAwait(false); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Assume( - topicViewModel, - $"A topic view model could not be created for the '{CurrentTopic?.GetUniqueKey()}' topic." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return topic view - \-----------------------------------------------------------------------------------------------------------------------*/ - return TopicView(topicViewModel, CurrentTopic?.View); + Contract.Assume( + topicViewModel, + $"A topic view model could not be created for the '{CurrentTopic?.GetUniqueKey()}' topic." + ); - } - - /*========================================================================================================================== - | METHOD: TOPIC VIEW + /*-------------------------------------------------------------------------------------------------------------------------- + | Return topic view \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object by specifying a and the to be rendered by the view. - /// - /// The model that is rendered by the view. - /// The optional name of the view that is rendered to the response. - /// The created object for the response. - [NonAction] - [ExcludeFromCodeCoverage] - public TopicViewResult TopicView(object model, string? viewName = null) => - new(ViewData, TempData, model, CurrentTopic?.ContentType, viewName); + return TopicView(topicViewModel, CurrentTopic?.View); - } //Class -} //Namespace \ No newline at end of file + } + + /*============================================================================================================================ + | METHOD: TOPIC VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object by specifying a and the to be rendered by the view. + /// + /// The model that is rendered by the view. + /// The optional name of the view that is rendered to the response. + /// The created object for the response. + [NonAction] + [ExcludeFromCodeCoverage] + public TopicViewResult TopicView(object model, string? viewName = null) => + new(ViewData, TempData, model, CurrentTopic?.ContentType, viewName); + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/Models/NavigationViewModel{T}.cs b/OnTopic.AspNetCore.Mvc/Models/NavigationViewModel{T}.cs index 510a4dfc..1d34f9ca 100644 --- a/OnTopic.AspNetCore.Mvc/Models/NavigationViewModel{T}.cs +++ b/OnTopic.AspNetCore.Mvc/Models/NavigationViewModel{T}.cs @@ -6,77 +6,76 @@ using OnTopic.AspNetCore.Mvc.Components; using OnTopic.Models; -namespace OnTopic.AspNetCore.Mvc.Models { +namespace OnTopic.AspNetCore.Mvc.Models; + +/*============================================================================================================================== +| VIEW MODEL: NAVIGATION TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed view model for feeding views with information expected to be required for each node in of +/// navigation. +/// +/// +/// +/// No topics are expected to have a Navigation content type. Instead, this view model is expected to be manually +/// constructed by the . +/// +/// +/// The can be any view model that implements , +/// which ensures support for hierarchical coverage. In practice, we expect most implementers will choose to implement +/// instead, which addresses not only , but also provides a base level of support for properties that most navigation views will need, as well as a +/// method for determining if a given instance is the currently-selected +/// topic. Derived implementations may introduce additional properties, as appropriate. +/// +/// +public class NavigationViewModel where T : class, IHierarchicalTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: NAVIGATION TOPIC + | NAVIGATION ROOT \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed view model for feeding views with information expected to be required for each node in of + /// Represents the root element in the navigation. + /// + /// + /// Since this implements , it may include multiple levels of children. By + /// implementing it as a generic, each site or application can provide its own implementation, thus potentially extending the schema with properties relevant to that site's navigation. For + /// example, a site may optionally add an IconUrl property if it wishes to assign unique icons to each link in the /// navigation. + /// + public T? NavigationRoot { get; set; } + + /*============================================================================================================================ + | CURRENT WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The representing the path to the current . /// /// /// - /// No topics are expected to have a Navigation content type. Instead, this view model is expected to be manually - /// constructed by the . + /// In order to determine whether any given , the views + /// will need to know where in the hierarchy the user currently is. By storing this on the used as the root view model for every navigation component, we ensure that the views + /// always have access to this information. /// /// - /// The can be any view model that implements , - /// which ensures support for hierarchical coverage. In practice, we expect most implementers will choose to implement - /// instead, which addresses not only , but also provides a base level of support for properties that most navigation views will need, as well as a - /// method for determining if a given instance is the currently-selected - /// topic. Derived implementations may introduce additional properties, as appropriate. + /// It's worth noting that while this could be stored on the itself, + /// that would prevent those values from being cached. As such, it's preferrable to keep the navigation nodes stateless, + /// and maintaining state exclusively in the itself. /// /// - public class NavigationViewModel where T : class, IHierarchicalTopicViewModel { - - /*========================================================================================================================== - | NAVIGATION ROOT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents the root element in the navigation. - /// - /// - /// Since this implements , it may include multiple levels of children. By - /// implementing it as a generic, each site or application can provide its own implementation, thus potentially extending the schema with properties relevant to that site's navigation. For - /// example, a site may optionally add an IconUrl property if it wishes to assign unique icons to each link in the - /// navigation. - /// - public T? NavigationRoot { get; set; } + public string CurrentWebPath { get; set; } = default!; - /*========================================================================================================================== - | CURRENT WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The representing the path to the current . - /// - /// - /// - /// In order to determine whether any given , the views - /// will need to know where in the hierarchy the user currently is. By storing this on the used as the root view model for every navigation component, we ensure that the views - /// always have access to this information. - /// - /// - /// It's worth noting that while this could be stored on the itself, - /// that would prevent those values from being cached. As such, it's preferrable to keep the navigation nodes stateless, - /// and maintaining state exclusively in the itself. - /// - /// - public string CurrentWebPath { get; set; } = default!; - - /*========================================================================================================================== - | CURRENT KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The representing the path to the current . - /// - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The CurrentKey property has been replaced in favor of {nameof(CurrentWebPath)}.", true)] - public string CurrentKey { get; set; } = default!; + /*============================================================================================================================ + | CURRENT KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The representing the path to the current . + /// + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The CurrentKey property has been replaced in favor of {nameof(CurrentWebPath)}.", true)] + public string CurrentKey { get; set; } = default!; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/ServiceCollectionExtensions.cs b/OnTopic.AspNetCore.Mvc/ServiceCollectionExtensions.cs index b972a345..bff32352 100644 --- a/OnTopic.AspNetCore.Mvc/ServiceCollectionExtensions.cs +++ b/OnTopic.AspNetCore.Mvc/ServiceCollectionExtensions.cs @@ -11,261 +11,260 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using OnTopic.AspNetCore.Mvc.Controllers; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: SERVICE COLLECTION EXTENSIONS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides extension methods for configuring the OnTopic library with ASP.NET Core MVC. +/// +public static class ServiceCollectionExtensions { /*============================================================================================================================ - | CLASS: SERVICE COLLECTION EXTENSIONS + | EXTENSION: ADD TOPIC SUPPORT (IMVCBUILDER) \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides extension methods for configuring the OnTopic library with ASP.NET Core MVC. + /// Configures the Razor engine to include OnTopic view locations via the . /// - public static class ServiceCollectionExtensions { + public static IMvcBuilder AddTopicSupport(this IMvcBuilder services) { - /*========================================================================================================================== - | EXTENSION: ADD TOPIC SUPPORT (IMVCBUILDER) + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Configures the Razor engine to include OnTopic view locations via the . - /// - public static IMvcBuilder AddTopicSupport(this IMvcBuilder services) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(services, nameof(services)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Register services - \-----------------------------------------------------------------------------------------------------------------------*/ - services.Services.TryAddSingleton, TopicViewResultExecutor>(); - services.Services.TryAddSingleton(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Configure services - \-----------------------------------------------------------------------------------------------------------------------*/ - services.AddRazorOptions(o => { - o.ViewLocationExpanders.Add(new TopicViewLocationExpander()); - }); + Contract.Requires(services, nameof(services)); - /*------------------------------------------------------------------------------------------------------------------------ - | Register local controllers - \-----------------------------------------------------------------------------------------------------------------------*/ - //Add Topic assembly into scope - services.AddApplicationPart(typeof(TopicController).Assembly); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return services for fluent API - \-----------------------------------------------------------------------------------------------------------------------*/ - return services; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Register services + \-------------------------------------------------------------------------------------------------------------------------*/ + services.Services.TryAddSingleton, TopicViewResultExecutor>(); + services.Services.TryAddSingleton(); - /*========================================================================================================================== - | EXTENSION: MAP TOPIC ROUTE (IROUTEBUILDER) + /*-------------------------------------------------------------------------------------------------------------------------- + | Configure services \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an MVC route for handling OnTopic related requests, and maps it to the by default. - /// - /// - /// For ASP.NET Core 3, prefer instead , as - /// endpoint routing is preferred in ASP.NET Core 3. OnTopic also offers far more extension methods for endpoint routing, - /// while this method is provided exclusively for backward compatibility. - /// - [ExcludeFromCodeCoverage] - [Obsolete("This method is deprecated and will be removed in OnTopic 5. Callers should migrate to endpoint routing.", true)] - public static IRouteBuilder MapTopicRoute( - this IRouteBuilder routes, - string rootTopic, - string controller = "Topic", - string action = "Index" - ) => - routes.MapRoute( - name: $"{rootTopic}Topic", - template: rootTopic + "/{*path}", - defaults: new { controller, action, rootTopic } - ); + services.AddRazorOptions(o => { + o.ViewLocationExpanders.Add(new TopicViewLocationExpander()); + }); - /*========================================================================================================================== - | EXTENSION: MAP TOPIC ROUTE (IENDPOINTROUTEBUILDER) + /*-------------------------------------------------------------------------------------------------------------------------- + | Register local controllers \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds the {rootTopic}/{**path} endpoint route for a specific root topic, which enables that root to be mapped to - /// specific topics via the - /// extension method used by . - /// - public static ControllerActionEndpointConventionBuilder MapTopicRoute( - this IEndpointRouteBuilder routes, - string rootTopic, - string controller = "Topic", - string action = "Index" - ) => - routes.MapControllerRoute( - name: $"{rootTopic}Topic", - pattern: rootTopic + "/{**path}", - defaults: new { controller, action, rootTopic } - ); + //Add Topic assembly into scope + services.AddApplicationPart(typeof(TopicController).Assembly); - /*========================================================================================================================== - | EXTENSION: MAP TOPIC AREA ROUTE (IENDPOINTROUTEBUILDER) + /*-------------------------------------------------------------------------------------------------------------------------- + | Return services for fluent API \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds the {areaName}/{**path} endpoint route for a specific area, which enables the areas to be mapped to - /// specific topics via the - /// extension method used by . - /// - /// - /// If there are multiple routes that fit this description, you can instead opt to use the extension, which will register all areas. - /// - [ExcludeFromCodeCoverage] - public static ControllerActionEndpointConventionBuilder MapTopicAreaRoute( - this IEndpointRouteBuilder routes, - string areaName, - string? controller = null, - string action = "Index" - ) => - routes.MapAreaControllerRoute( - name: $"TopicAreas", - areaName: areaName, - pattern: areaName + "/{**path}", - defaults: new { controller = controller?? areaName, action, rootTopic = areaName } - ); + return services; + } - /// - /// Adds the {area:exists}/{**path} endpoint route for all areas, which enables the areas to be mapped to specific - /// topics via the extension method - /// used by . - /// - /// - /// Be aware that this method uses the method. In .NET 3.x, this is incompatible with both the and classes. This means that e.g. @Url.Action() references - /// in views won't be properly formed. If these are required, prefer registering each route individually using . - /// - public static void MapTopicAreaRoute(this IEndpointRouteBuilder routes) => - routes.MapDynamicControllerRoute("{area:exists}/{**path}"); + /*============================================================================================================================ + | EXTENSION: MAP TOPIC ROUTE (IROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an MVC route for handling OnTopic related requests, and maps it to the by default. + /// + /// + /// For ASP.NET Core 3, prefer instead , as + /// endpoint routing is preferred in ASP.NET Core 3. OnTopic also offers far more extension methods for endpoint routing, + /// while this method is provided exclusively for backward compatibility. + /// + [ExcludeFromCodeCoverage] + [Obsolete("This method is deprecated and will be removed in OnTopic 5. Callers should migrate to endpoint routing.", true)] + public static IRouteBuilder MapTopicRoute( + this IRouteBuilder routes, + string rootTopic, + string controller = "Topic", + string action = "Index" + ) => + routes.MapRoute( + name: $"{rootTopic}Topic", + template: rootTopic + "/{*path}", + defaults: new { controller, action, rootTopic } + ); - /*========================================================================================================================== - | EXTENSION: MAP DEFAULT AREA CONTROLLER ROUTES (IENDPOINTROUTEBUILDER) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds the fully-qualified {area:exists}/{controller}/{action=Index}/{id?} endpoint route for all areas. - /// - /// - /// This is analogous to the standard method that ships with ASP.NET, except that it works with areas. - /// - public static void MapDefaultAreaControllerRoute(this IEndpointRouteBuilder routes) => - routes.MapControllerRoute( - name: "TopicAreas", - pattern: "{area:exists}/{controller}/{action=Index}/{id?}" - ); + /*============================================================================================================================ + | EXTENSION: MAP TOPIC ROUTE (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds the {rootTopic}/{**path} endpoint route for a specific root topic, which enables that root to be mapped to + /// specific topics via the + /// extension method used by . + /// + public static ControllerActionEndpointConventionBuilder MapTopicRoute( + this IEndpointRouteBuilder routes, + string rootTopic, + string controller = "Topic", + string action = "Index" + ) => + routes.MapControllerRoute( + name: $"{rootTopic}Topic", + pattern: rootTopic + "/{**path}", + defaults: new { controller, action, rootTopic } + ); - /*========================================================================================================================== - | EXTENSION: MAP IMPLICIT AREA CONTROLLER ROUTES (IENDPOINTROUTEBUILDER) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds the {areaName}/{action=Index} endpoint route for a specific area where the controller has the same name as - /// the area. - /// - /// - /// - /// This extension method implicitly assigns the controller name based on the area name. This is advantageous when an - /// area has a single controller which is named after the area—e.g., [Area("Forms")] and FormsController— - /// as this allows the redundant Controller to be ommited from the route (e.g., /Forms/Forms/{action}. - /// - /// - /// If there are multiple routes that fit this description, you can instead opt to use the overload, which will register all areas. - /// - /// - [ExcludeFromCodeCoverage] - public static void MapImplicitAreaControllerRoute(this IEndpointRouteBuilder routes, string areaName) => - routes.MapAreaControllerRoute( - name: $"{areaName}TopicArea", - areaName: areaName, - pattern: $"{areaName}/{{action}}", - defaults: new { controller = areaName } - ); + /*============================================================================================================================ + | EXTENSION: MAP TOPIC AREA ROUTE (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds the {areaName}/{**path} endpoint route for a specific area, which enables the areas to be mapped to + /// specific topics via the + /// extension method used by . + /// + /// + /// If there are multiple routes that fit this description, you can instead opt to use the extension, which will register all areas. + /// + [ExcludeFromCodeCoverage] + public static ControllerActionEndpointConventionBuilder MapTopicAreaRoute( + this IEndpointRouteBuilder routes, + string areaName, + string? controller = null, + string action = "Index" + ) => + routes.MapAreaControllerRoute( + name: $"TopicAreas", + areaName: areaName, + pattern: areaName + "/{**path}", + defaults: new { controller = controller?? areaName, action, rootTopic = areaName } + ); - /// - /// Adds the {area:exists}/{action=Index} endpoint route for all areas where the controller has the same name as - /// the area. - /// - /// - /// - /// This extension method implicitly assigns the controller name based on the area name. This is advantageous when there - /// are multiple areas which have a single controller which is named after the area—e.g., [Area("Forms")] and - /// FormsController: Controller—as this allows those to be collectively registered under a single route, without - /// needing the redundant Controller value to be defined in the route (e.g., /Forms/Forms/{action}. - /// - /// - /// Be aware that this method uses the method. In .NET 3.x, this is incompatible with both the and classes. This means that e.g. @Url.Action() references - /// in views won't be properly formed. If these are required, prefer registering each route individually using . - /// - /// - public static void MapImplicitAreaControllerRoute(this IEndpointRouteBuilder routes) => - routes.MapDynamicControllerRoute("{area:exists}/{action=Index}"); + /// + /// Adds the {area:exists}/{**path} endpoint route for all areas, which enables the areas to be mapped to specific + /// topics via the extension method + /// used by . + /// + /// + /// Be aware that this method uses the method. In .NET 3.x, this is incompatible with both the and classes. This means that e.g. @Url.Action() references + /// in views won't be properly formed. If these are required, prefer registering each route individually using . + /// + public static void MapTopicAreaRoute(this IEndpointRouteBuilder routes) => + routes.MapDynamicControllerRoute("{area:exists}/{**path}"); - /*========================================================================================================================== - | EXTENSION: MAP ERROR ROUTE (IENDPOINTROUTEBUILDER) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds the /Error/{errorCode} endpoint route for the . - /// - /// - /// This allows the to be used in conjunction with e.g., the , by providing a route for capturing the - /// errorCode. - /// - /// The this route is being added to. - /// The name of the root topic that the route should be mapped to. Defaults to Error. - /// Determines if static resources should be covered. Defaults to true. - public static ControllerActionEndpointConventionBuilder MapTopicErrors( - this IEndpointRouteBuilder routes, - string rootTopic = "Error", - bool includeStaticFiles = true - ) => - routes.MapControllerRoute( - name: "TopicError", - pattern: $"{rootTopic}/{{id:int}}/", - defaults: new { controller = "Error", action = "Http", rootTopic, includeStaticFiles } - ); + /*============================================================================================================================ + | EXTENSION: MAP DEFAULT AREA CONTROLLER ROUTES (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds the fully-qualified {area:exists}/{controller}/{action=Index}/{id?} endpoint route for all areas. + /// + /// + /// This is analogous to the standard method that ships with ASP.NET, except that it works with areas. + /// + public static void MapDefaultAreaControllerRoute(this IEndpointRouteBuilder routes) => + routes.MapControllerRoute( + name: "TopicAreas", + pattern: "{area:exists}/{controller}/{action=Index}/{id?}" + ); - /*========================================================================================================================== - | EXTENSION: MAP TOPIC SITEMAP (IENDPOINTROUTEBUILDER) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds the Sitemap/{action=Index} endpoint route for the OnTopic sitemap. - /// - /// - /// For most implementations, this will be covered by the default route, such as that implemented by the standard method that ships - /// with ASP.NET. This extension method is provided as a convenience method for implementations that aren't using the - /// standard route, for whatever reason, and want a specific route setup for the sitemap. - /// - public static ControllerActionEndpointConventionBuilder MapTopicSitemap(this IEndpointRouteBuilder routes) => - routes.MapControllerRoute( - name: "TopicSitemap", - pattern: "Sitemap/{action=Index}", - defaults: new { controller = "Sitemap" } - ); + /*============================================================================================================================ + | EXTENSION: MAP IMPLICIT AREA CONTROLLER ROUTES (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds the {areaName}/{action=Index} endpoint route for a specific area where the controller has the same name as + /// the area. + /// + /// + /// + /// This extension method implicitly assigns the controller name based on the area name. This is advantageous when an + /// area has a single controller which is named after the area—e.g., [Area("Forms")] and FormsController— + /// as this allows the redundant Controller to be ommited from the route (e.g., /Forms/Forms/{action}. + /// + /// + /// If there are multiple routes that fit this description, you can instead opt to use the overload, which will register all areas. + /// + /// + [ExcludeFromCodeCoverage] + public static void MapImplicitAreaControllerRoute(this IEndpointRouteBuilder routes, string areaName) => + routes.MapAreaControllerRoute( + name: $"{areaName}TopicArea", + areaName: areaName, + pattern: $"{areaName}/{{action}}", + defaults: new { controller = areaName } + ); - /*========================================================================================================================== - | EXTENSION: MAP TOPIC REDIRECT (IENDPOINTROUTEBUILDER) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an MVC route for handling OnTopic redirect requests, and maps it to the . - /// - public static ControllerActionEndpointConventionBuilder MapTopicRedirect(this IEndpointRouteBuilder routes) => - routes.MapControllerRoute( - name: "TopicRedirect", - pattern: "Topic/{topicId}", - defaults: new { controller = "Redirect", action = "Redirect" } - ); + /// + /// Adds the {area:exists}/{action=Index} endpoint route for all areas where the controller has the same name as + /// the area. + /// + /// + /// + /// This extension method implicitly assigns the controller name based on the area name. This is advantageous when there + /// are multiple areas which have a single controller which is named after the area—e.g., [Area("Forms")] and + /// FormsController: Controller—as this allows those to be collectively registered under a single route, without + /// needing the redundant Controller value to be defined in the route (e.g., /Forms/Forms/{action}. + /// + /// + /// Be aware that this method uses the method. In .NET 3.x, this is incompatible with both the and classes. This means that e.g. @Url.Action() references + /// in views won't be properly formed. If these are required, prefer registering each route individually using . + /// + /// + public static void MapImplicitAreaControllerRoute(this IEndpointRouteBuilder routes) => + routes.MapDynamicControllerRoute("{area:exists}/{action=Index}"); + + /*============================================================================================================================ + | EXTENSION: MAP ERROR ROUTE (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds the /Error/{errorCode} endpoint route for the . + /// + /// + /// This allows the to be used in conjunction with e.g., the , by providing a route for capturing the + /// errorCode. + /// + /// The this route is being added to. + /// The name of the root topic that the route should be mapped to. Defaults to Error. + /// Determines if static resources should be covered. Defaults to true. + public static ControllerActionEndpointConventionBuilder MapTopicErrors( + this IEndpointRouteBuilder routes, + string rootTopic = "Error", + bool includeStaticFiles = true + ) => + routes.MapControllerRoute( + name: "TopicError", + pattern: $"{rootTopic}/{{id:int}}/", + defaults: new { controller = "Error", action = "Http", rootTopic, includeStaticFiles } + ); + + /*============================================================================================================================ + | EXTENSION: MAP TOPIC SITEMAP (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds the Sitemap/{action=Index} endpoint route for the OnTopic sitemap. + /// + /// + /// For most implementations, this will be covered by the default route, such as that implemented by the standard method that ships + /// with ASP.NET. This extension method is provided as a convenience method for implementations that aren't using the + /// standard route, for whatever reason, and want a specific route setup for the sitemap. + /// + public static ControllerActionEndpointConventionBuilder MapTopicSitemap(this IEndpointRouteBuilder routes) => + routes.MapControllerRoute( + name: "TopicSitemap", + pattern: "Sitemap/{action=Index}", + defaults: new { controller = "Sitemap" } + ); + + /*============================================================================================================================ + | EXTENSION: MAP TOPIC REDIRECT (IENDPOINTROUTEBUILDER) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an MVC route for handling OnTopic redirect requests, and maps it to the . + /// + public static ControllerActionEndpointConventionBuilder MapTopicRedirect(this IEndpointRouteBuilder routes) => + routes.MapControllerRoute( + name: "TopicRedirect", + pattern: "Topic/{topicId}", + defaults: new { controller = "Redirect", action = "Redirect" } + ); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/TopicRepositoryExtensions.cs b/OnTopic.AspNetCore.Mvc/TopicRepositoryExtensions.cs index 6e0cdfbc..72793089 100644 --- a/OnTopic.AspNetCore.Mvc/TopicRepositoryExtensions.cs +++ b/OnTopic.AspNetCore.Mvc/TopicRepositoryExtensions.cs @@ -5,107 +5,106 @@ \=============================================================================================================================*/ using Microsoft.AspNetCore.Routing; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: TOPIC REPOSITORY EXTENSIONS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides methods that extend the functionality of with features dependent on ASP.NET +/// Core, and dependended on by the local assembly. +/// +public static class TopicRepositoryExtensions { /*============================================================================================================================ - | CLASS: TOPIC REPOSITORY EXTENSIONS + | EXTENSION: LOAD \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides methods that extend the functionality of with features dependent on ASP.NET - /// Core, and dependended on by the local assembly. + /// Loads the current topic based on variables defined in the dictionary. /// - public static class TopicRepositoryExtensions { + /// + /// The ASP.NET Core MVC defines specified route names. In addition to the common, out + /// of the box routes, such as controller and action, the defines + /// additional topic-specific routes, such as rootTopic and path. These can be combined to identify a topic + /// in the repository. By using the extension method, callers needn't assemble their own + /// prior to calling , assuming they are using the standard routing + /// variables. + /// + public static Topic? Load( + this ITopicRepository topicRepository, + RouteData routeData + ) { - /*========================================================================================================================== - | EXTENSION: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads the current topic based on variables defined in the dictionary. - /// - /// - /// The ASP.NET Core MVC defines specified route names. In addition to the common, out - /// of the box routes, such as controller and action, the defines - /// additional topic-specific routes, such as rootTopic and path. These can be combined to identify a topic - /// in the repository. By using the extension method, callers needn't assemble their own - /// prior to calling , assuming they are using the standard routing - /// variables. - /// - public static Topic? Load( - this ITopicRepository topicRepository, - RouteData routeData - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicRepository, nameof(topicRepository)); - Contract.Requires(routeData, nameof(routeData)); + Contract.Requires(topicRepository, nameof(topicRepository)); + Contract.Requires(routeData, nameof(routeData)); - /*------------------------------------------------------------------------------------------------------------------------ - | Define parameters from route - \-----------------------------------------------------------------------------------------------------------------------*/ - var area = getRouteValue("area"); - var controller = getRouteValue("controller"); - var action = getRouteValue("action"); - var path = getRouteValue("path"); - var rootTopic = getRouteValue("rootTopic"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Define parameters from route + \-------------------------------------------------------------------------------------------------------------------------*/ + var area = getRouteValue("area"); + var controller = getRouteValue("controller"); + var action = getRouteValue("action"); + var path = getRouteValue("path"); + var rootTopic = getRouteValue("rootTopic"); - /*------------------------------------------------------------------------------------------------------------------------ - | Define search paths based on route variables - >------------------------------------------------------------------------------------------------------------------------- - | ### NOTE JJC20191205: If any variables—such as {area}—is not defined, then it will be excluded and any slashes ("/") - | remaining at the beginning or the end will be removed. As such, there's no need to search for both e.g. - | {area}/{controller}/{action}/{path} as well as, say, {controller}/{action}. This provides an automatical fallback in - | case particular routes aren't present. That said, if they are defined, but should be excluded from a fallback, then - | that path does need to be defined—thus e.g. {area}/{controller}/{path}. - \-----------------------------------------------------------------------------------------------------------------------*/ - var paths = new List() { - cleanPath($"{rootTopic}/{path}"), - cleanPath($"{area}/{controller}/{action}/{path}"), - cleanPath($"{area}/{controller}/{path}"), - cleanPath($"{area}/{action}/{path}"), - cleanPath($"{area}/{path}") - }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Define search paths based on route variables + >------------------------------------------------------------------------------------------------------------------------- + | ### NOTE JJC20191205: If any variables—such as {area}—is not defined, then it will be excluded and any slashes ("/") + | remaining at the beginning or the end will be removed. As such, there's no need to search for both e.g. + | {area}/{controller}/{action}/{path} as well as, say, {controller}/{action}. This provides an automatical fallback in + | case particular routes aren't present. That said, if they are defined, but should be excluded from a fallback, then + | that path does need to be defined—thus e.g. {area}/{controller}/{path}. + \-------------------------------------------------------------------------------------------------------------------------*/ + var paths = new List() { + cleanPath($"{rootTopic}/{path}"), + cleanPath($"{area}/{controller}/{action}/{path}"), + cleanPath($"{area}/{controller}/{path}"), + cleanPath($"{area}/{action}/{path}"), + cleanPath($"{area}/{path}") + }; - /*------------------------------------------------------------------------------------------------------------------------ - | Load by path - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = (Topic?)null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Load by path + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = (Topic?)null; - foreach (var searchPath in paths) { - if (topic is not null) break; - if (String.IsNullOrEmpty(searchPath)) continue; - try { - topic = topicRepository.Load(searchPath); - } - catch (InvalidKeyException) { - //As route data comes from user-submitted requests, it's expected that some may contain invalid keys. From this - //method's perspective, this is no different than having an invalid URL. As such, we should return a null result, not - //bubble up an exception. - } + foreach (var searchPath in paths) { + if (topic is not null) break; + if (String.IsNullOrEmpty(searchPath)) continue; + try { + topic = topicRepository.Load(searchPath); + } + catch (InvalidKeyException) { + //As route data comes from user-submitted requests, it's expected that some may contain invalid keys. From this + //method's perspective, this is no different than having an invalid URL. As such, we should return a null result, not + //bubble up an exception. } + } - return topic; + return topic; - /*------------------------------------------------------------------------------------------------------------------------ - | Get route value - \-----------------------------------------------------------------------------------------------------------------------*/ - string? getRouteValue(string parameter) { - if (routeData.Values.TryGetValue(parameter, out var value)) { - return value?.ToString(); - } - return null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Get route value + \-------------------------------------------------------------------------------------------------------------------------*/ + string? getRouteValue(string parameter) { + if (routeData.Values.TryGetValue(parameter, out var value)) { + return value?.ToString(); } + return null; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Clean path - \-----------------------------------------------------------------------------------------------------------------------*/ - static string? cleanPath(string? path) => path? - .Trim(new char[] { '/' }) - .Replace("//", "/", StringComparison.Ordinal) - .Replace("/", ":", StringComparison.Ordinal); + /*-------------------------------------------------------------------------------------------------------------------------- + | Clean path + \-------------------------------------------------------------------------------------------------------------------------*/ + static string? cleanPath(string? path) => path? + .Trim('/') + .Replace("//", "/", StringComparison.Ordinal) + .Replace("/", ":", StringComparison.Ordinal); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/TopicRouteValueTransformer.cs b/OnTopic.AspNetCore.Mvc/TopicRouteValueTransformer.cs index 6dbe24c4..10cdac68 100644 --- a/OnTopic.AspNetCore.Mvc/TopicRouteValueTransformer.cs +++ b/OnTopic.AspNetCore.Mvc/TopicRouteValueTransformer.cs @@ -7,75 +7,74 @@ using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: TOPIC ROUTE VALUE TRANSFORMER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Interprets endpoint routes associated with OnTopic in order to dynamically fill in any missing metadata based on the +/// needs of the method. +/// +public class TopicRouteValueTransformer: DynamicRouteValueTransformer { /*============================================================================================================================ - | CLASS: TOPIC ROUTE VALUE TRANSFORMER + | OVERRIDE: TRANSFORM (ASYNC) \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Interprets endpoint routes associated with OnTopic in order to dynamically fill in any missing metadata based on the - /// needs of the method. + /// Evaluates the current for any missing attributes, and attempts to dynamically + /// inject them based on other values. /// - public class TopicRouteValueTransformer: DynamicRouteValueTransformer { + #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously + public override async ValueTask TransformAsync(HttpContext httpContext, RouteValueDictionary values) { - /*========================================================================================================================== - | OVERRIDE: TRANSFORM (ASYNC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates the current for any missing attributes, and attempts to dynamically - /// inject them based on other values. - /// - #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public override async ValueTask TransformAsync(HttpContext httpContext, RouteValueDictionary values) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(httpContext, nameof(httpContext)); - Contract.Requires(values, nameof(values)); + Contract.Requires(httpContext, nameof(httpContext)); + Contract.Requires(values, nameof(values)); - /*------------------------------------------------------------------------------------------------------------------------ - | Implicitly set controller - >------------------------------------------------------------------------------------------------------------------------- - | If the area is set, but not the controller, assume that the controller is named after the area by convention. If the - | controller is being set in the route pattern, this won't change that. - \-----------------------------------------------------------------------------------------------------------------------*/ - var controller = (string?)values["controller"]; - var area = (string?)values["area"]; - if (area is not null && controller is null) { - values["controller"] = area; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Implicitly set controller + >------------------------------------------------------------------------------------------------------------------------- + | If the area is set, but not the controller, assume that the controller is named after the area by convention. If the + | controller is being set in the route pattern, this won't change that. + \-------------------------------------------------------------------------------------------------------------------------*/ + var controller = (string?)values["controller"]; + var area = (string?)values["area"]; + if (area is not null && controller is null) { + values["controller"] = area; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Implicitly set action - >------------------------------------------------------------------------------------------------------------------------- - | If the action isn't defined in the route, assume Index—which is the default action for the TopicController. - \-----------------------------------------------------------------------------------------------------------------------*/ - var action = (string?)values["action"]; - if (action is null) { - action = "Index"; - values["action"] = action; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Implicitly set action + >------------------------------------------------------------------------------------------------------------------------- + | If the action isn't defined in the route, assume Index—which is the default action for the TopicController. + \-------------------------------------------------------------------------------------------------------------------------*/ + var action = (string?)values["action"]; + if (action is null) { + action = "Index"; + values["action"] = action; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Implicitly set root topic - >------------------------------------------------------------------------------------------------------------------------- - | If the path is set, but the root topic isn't, then set the root topic to the area/controller name. The root topic is - | required by the TopicRepositoryExtensions to create a fully qualified topic path, and correctly identify the topic - | based on the path. It is not needed when routing by controller/action pairs. - \-----------------------------------------------------------------------------------------------------------------------*/ - var path = (string?)values["path"]; - if (path is not null || action.Equals("Index", StringComparison.OrdinalIgnoreCase)) { - values["rootTopic"] = area; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Implicitly set root topic + >------------------------------------------------------------------------------------------------------------------------- + | If the path is set, but the root topic isn't, then set the root topic to the area/controller name. The root topic is + | required by the TopicRepositoryExtensions to create a fully qualified topic path, and correctly identify the topic + | based on the path. It is not needed when routing by controller/action pairs. + \-------------------------------------------------------------------------------------------------------------------------*/ + var path = (string?)values["path"]; + if (path is not null || action.Equals("Index", StringComparison.OrdinalIgnoreCase)) { + values["rootTopic"] = area; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return values - \-----------------------------------------------------------------------------------------------------------------------*/ - return values; + /*-------------------------------------------------------------------------------------------------------------------------- + | Return values + \-------------------------------------------------------------------------------------------------------------------------*/ + return values; - } - #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously + } + #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/TopicViewLocationExpander.cs b/OnTopic.AspNetCore.Mvc/TopicViewLocationExpander.cs index 790c1300..a7df88e4 100644 --- a/OnTopic.AspNetCore.Mvc/TopicViewLocationExpander.cs +++ b/OnTopic.AspNetCore.Mvc/TopicViewLocationExpander.cs @@ -5,120 +5,119 @@ \=============================================================================================================================*/ using Microsoft.AspNetCore.Mvc.Razor; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: TOPIC VIEW LOCATION EXPANDER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides hints to the configured view engine (presumably, ) on where to find views +/// associated with the current request. +/// +/// +/// In addition to Area ({2}), Controller ({1}), and View ({0}), the also factors in ContentType ({3}). Note that, by default, the action is used +/// as the view name. The topic library overrides this behavior by evaluating other sources of views. If a match with an +/// controller and an action is found, however, that should be prioritized. +/// +public class TopicViewLocationExpander : IViewLocationExpander { /*============================================================================================================================ - | CLASS: TOPIC VIEW LOCATION EXPANDER + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides hints to the configured view engine (presumably, ) on where to find views - /// associated with the current request. + /// Initializes a new instance of the class. /// - /// - /// In addition to Area ({2}), Controller ({1}), and View ({0}), the also factors in ContentType ({3}). Note that, by default, the action is used - /// as the view name. The topic library overrides this behavior by evaluating other sources of views. If a match with an - /// controller and an action is found, however, that should be prioritized. - /// - public class TopicViewLocationExpander : IViewLocationExpander { + public TopicViewLocationExpander() { + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - public TopicViewLocationExpander() { - } + /*============================================================================================================================ + | PROPERTY: VIEW LOCATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a static copy of all view locations associated with OnTopic. + /// + public static IEnumerable ViewLocations => [ + "/Views/{1}/{0}.cshtml", //Views/Controller/Action.cshtml + "/Views/{3}/{0}.cshtml", //Views/ContentType/View.cshtml + "/Views/{3}/Shared/{0}.cshtml", //Views/ContentType/Shared/View.cshtml + "/Views/ContentTypes/{3}.{0}.cshtml", //Views/ContentTypes/ContentType.View.cshtml + "/Views/{1}/Shared/{0}.cshtml", //Views/Controller/Shared/Action.cshtml + "/Views/ContentTypes/Shared/{0}.cshtml", //Views/ContentTypes/Shared/View.cshtml + "/Views/ContentTypes/{0}.cshtml", //Views/ContentTypes/View.cshtml + "/Views/Shared/{0}.cshtml", //Views/Shared/View.cshtml + ]; + + /*============================================================================================================================ + | PROPERTY: AREA VIEW LOCATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a static copy of all areas view locations associated with OnTopic. + /// + public static IEnumerable AreaViewLocations => [ + "/Areas/{2}/Views/{1}/{0}.cshtml", //Areas/Area/Views/Controller/Action.cshtml + "/Areas/{2}/Views/{3}/{0}.cshtml", //Areas/Area/Views/ContentType/View.cshtml + "/Areas/{2}/Views/{3}/Shared/{0}.cshtml", //Areas/Area/Views/ContentType/Shared/View.cshtml + "/Areas/{2}/Views/ContentTypes/{3}.{0}.cshtml", //Areas/Area/Views/ContentTypes/ContentType.View.cshtml + "/Areas/{2}/Views/{1}/Shared/{0}.cshtml", //Areas/Area/Views/Controller/Shared/Action.cshtml + "/Areas/{2}/Views/ContentTypes/Shared/{0}.cshtml", //Areas/Area/Views/ContentTypes/Shared/View.cshtml + "/Areas/{2}/Views/ContentTypes/{0}.cshtml", //Areas/Area/Views/ContentTypes/View.cshtml + "/Areas/{2}/Views/Shared/{0}.cshtml", //Areas/Area/Views/Shared/View.cshtml + ]; + + /*============================================================================================================================ + | METHOD: POPULATE VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the class. + /// + /// + /// The that the request is operating within. + public void PopulateValues(ViewLocationExpanderContext context) { + Contract.Requires(context, nameof(context)); + context.Values["action_displayname"] = context.ActionContext.ActionDescriptor.DisplayName; + context.ActionContext.RouteData.Values.TryGetValue("contenttype", out var contentType); + context.Values["content_type"] = (string?)contentType; + } - /*========================================================================================================================== - | PROPERTY: VIEW LOCATIONS + /*============================================================================================================================ + | METHOD: EXPAND VIEW LOCATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a static copy of all view locations associated with OnTopic. - /// - public static IEnumerable ViewLocations => new[] { - "/Views/{1}/{0}.cshtml", //Views/Controller/Action.cshtml - "/Views/{3}/{0}.cshtml", //Views/ContentType/View.cshtml - "/Views/{3}/Shared/{0}.cshtml", //Views/ContentType/Shared/View.cshtml - "/Views/ContentTypes/{3}.{0}.cshtml", //Views/ContentTypes/ContentType.View.cshtml - "/Views/{1}/Shared/{0}.cshtml", //Views/Controller/Shared/Action.cshtml - "/Views/ContentTypes/Shared/{0}.cshtml", //Views/ContentTypes/Shared/View.cshtml - "/Views/ContentTypes/{0}.cshtml", //Views/ContentTypes/View.cshtml - "/Views/Shared/{0}.cshtml", //Views/Shared/View.cshtml - }; + Contract.Requires(context, nameof(context)); + Contract.Requires(viewLocations, nameof(viewLocations)); - /*========================================================================================================================== - | PROPERTY: AREA VIEW LOCATIONS + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a static copy of all areas view locations associated with OnTopic. - /// - public static IEnumerable AreaViewLocations => new[] { - "/Areas/{2}/Views/{1}/{0}.cshtml", //Areas/Area/Views/Controller/Action.cshtml - "/Areas/{2}/Views/{3}/{0}.cshtml", //Areas/Area/Views/ContentType/View.cshtml - "/Areas/{2}/Views/{3}/Shared/{0}.cshtml", //Areas/Area/Views/ContentType/Shared/View.cshtml - "/Areas/{2}/Views/ContentTypes/{3}.{0}.cshtml", //Areas/Area/Views/ContentTypes/ContentType.View.cshtml - "/Areas/{2}/Views/{1}/Shared/{0}.cshtml", //Areas/Area/Views/Controller/Shared/Action.cshtml - "/Areas/{2}/Views/ContentTypes/Shared/{0}.cshtml", //Areas/Area/Views/ContentTypes/Shared/View.cshtml - "/Areas/{2}/Views/ContentTypes/{0}.cshtml", //Areas/Area/Views/ContentTypes/View.cshtml - "/Areas/{2}/Views/Shared/{0}.cshtml", //Areas/Area/Views/Shared/View.cshtml - }; + context.ActionContext.RouteData.Values.TryGetValue("contenttype", out var contentType); - /*========================================================================================================================== - | METHOD: POPULATE VALUES + /*-------------------------------------------------------------------------------------------------------------------------- + | Yield area view locations \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// - /// The that the request is operating within. - public void PopulateValues(ViewLocationExpanderContext context) { - Contract.Requires(context, nameof(context)); - context.Values["action_displayname"] = context.ActionContext.ActionDescriptor.DisplayName; - context.ActionContext.RouteData.Values.TryGetValue("contenttype", out var contentType); - context.Values["content_type"] = (string?)contentType; + foreach (var location in AreaViewLocations) { + yield return location.Replace(@"{3}", (string?)contentType, StringComparison.Ordinal); } - /*========================================================================================================================== - | METHOD: EXPAND VIEW LOCATIONS + /*-------------------------------------------------------------------------------------------------------------------------- + | Yield view locations \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public IEnumerable ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable viewLocations) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - Contract.Requires(viewLocations, nameof(viewLocations)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - context.ActionContext.RouteData.Values.TryGetValue("contenttype", out var contentType); - - /*------------------------------------------------------------------------------------------------------------------------ - | Yield area view locations - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var location in AreaViewLocations) { - yield return location.Replace(@"{3}", (string?)contentType, StringComparison.Ordinal); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Yield view locations - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var location in ViewLocations) { - yield return location.Replace(@"{3}", (string?)contentType, StringComparison.Ordinal); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Return previous - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var location in viewLocations) { - yield return location; - } + foreach (var location in ViewLocations) { + yield return location.Replace(@"{3}", (string?)contentType, StringComparison.Ordinal); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return previous + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var location in viewLocations) { + yield return location; } - } //Class -} //Namespace \ No newline at end of file + } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/TopicViewResult.cs b/OnTopic.AspNetCore.Mvc/TopicViewResult.cs index ad111962..8093cd6d 100644 --- a/OnTopic.AspNetCore.Mvc/TopicViewResult.cs +++ b/OnTopic.AspNetCore.Mvc/TopicViewResult.cs @@ -8,96 +8,95 @@ using Microsoft.Extensions.DependencyInjection; using OnTopic.Metadata; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: TOPIC VIEW RESULT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom version of capable of determining the most appropriate view. +/// +public class TopicViewResult : ViewResult { /*============================================================================================================================ - | CLASS: TOPIC VIEW RESULT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a custom version of capable of determining the most appropriate view. + /// Constructs a new instances of a based on a supplied and, + /// optionally, . /// - public class TopicViewResult : ViewResult { + /// + /// If the is not provided, it is assumed to be Page. If the + /// is not provided, it is assumed to be . + /// + public TopicViewResult( + ViewDataDictionary viewData, + ITempDataDictionary? tempData, + object viewModel, + string? contentType = null, + string? view = null + ) : base() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new instances of a based on a supplied and, - /// optionally, . - /// - /// - /// If the is not provided, it is assumed to be Page. If the - /// is not provided, it is assumed to be . - /// - public TopicViewResult( - ViewDataDictionary viewData, - ITempDataDictionary? tempData, - object viewModel, - string? contentType = null, - string? view = null - ) : base() { + Contract.Requires(viewData, nameof(viewData)); + Contract.Requires(viewModel, nameof(viewModel)); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(viewData, nameof(viewData)); - Contract.Requires(viewModel, nameof(viewModel)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Set local variables + \-------------------------------------------------------------------------------------------------------------------------*/ + ViewData = viewData; + TempData = tempData!; + ViewData.Model = viewModel; + TopicContentType = contentType?? TopicContentType; + TopicView = view ?? ContentType ?? TopicContentType; + //ViewName = TopicView; - /*------------------------------------------------------------------------------------------------------------------------ - | Set local variables - \-----------------------------------------------------------------------------------------------------------------------*/ - ViewData = viewData; - TempData = tempData; - ViewData.Model = viewModel; - TopicContentType = contentType?? TopicContentType; - TopicView = view ?? ContentType; - //ViewName = TopicView; + } - } + /*============================================================================================================================ + | PROPERTY: TOPIC CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Represents the name associated with the current . + /// + /// + /// The preferred nomenclature for the name of a is simply ContentType. The + /// base class has an existing property representing the + /// HTTP response value, however. As such, is used to disambiguate the terms. + /// + public string TopicContentType { get; } = "Page"; - /*========================================================================================================================== - | PROPERTY: TOPIC CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents the name associated with the current . - /// - /// - /// The preferred nomenclature for the name of a is simply ContentType. The - /// base class has an existing property representing the - /// HTTP response value, however. As such, is used to disambiguate the terms. - /// - public string TopicContentType { get; } = "Page"; + /*============================================================================================================================ + | PROPERTY: TOPIC VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Represents the property. This may be overwritten later by a variety of sources. + /// + /// + /// The associated will fall back to the if the view isn't + /// set via other sources, such as the HTTP accepts header, the query string, etc. + /// + public string TopicView { get; } - /*========================================================================================================================== - | PROPERTY: TOPIC VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents the property. This may be overwritten later by a variety of sources. - /// - /// - /// The associated will fall back to the if the view isn't - /// set via other sources, such as the HTTP accepts header, the query string, etc. - /// - public string TopicView { get; } + /*============================================================================================================================ + | METHOD: EXECUTE RESULT (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override async Task ExecuteResultAsync(ActionContext context) { - /*========================================================================================================================== - | METHOD: EXECUTE RESULT (ASYNC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override async Task ExecuteResultAsync(ActionContext context) { + Contract.Requires(context, nameof(context)); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Call associated executor - \-----------------------------------------------------------------------------------------------------------------------*/ - var executor = context.HttpContext.RequestServices.GetRequiredService>(); - await executor.ExecuteAsync(context, this).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Call associated executor + \-------------------------------------------------------------------------------------------------------------------------*/ + var executor = context.HttpContext.RequestServices.GetRequiredService>(); + await executor.ExecuteAsync(context, this).ConfigureAwait(false); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/TopicViewResultExecutor.cs b/OnTopic.AspNetCore.Mvc/TopicViewResultExecutor.cs index 74820214..c5aa032d 100644 --- a/OnTopic.AspNetCore.Mvc/TopicViewResultExecutor.cs +++ b/OnTopic.AspNetCore.Mvc/TopicViewResultExecutor.cs @@ -12,197 +12,201 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.Options; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: TOPIC VIEW RESULT EXECUTOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Finds and executes an for a . +/// +public class TopicViewResultExecutor : ViewExecutor, IActionResultExecutor { + + /// + /// Creates a new . + /// + /// The . + /// The . + /// The . + /// The . + /// The . + /// The . + public TopicViewResultExecutor( + IOptions viewOptions, + IHttpResponseStreamWriterFactory writerFactory, + ICompositeViewEngine viewEngine, + ITempDataDictionaryFactory tempDataFactory, + DiagnosticListener diagnosticListener, + IModelMetadataProvider modelMetadataProvider + ) : base( + viewOptions, writerFactory, viewEngine, tempDataFactory, diagnosticListener, modelMetadataProvider + ) { + } /*============================================================================================================================ - | CLASS: TOPIC VIEW RESULT EXECUTOR + | METHOD: FIND VIEW \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Finds and executes an for a . + /// Loops through potential sources for views to identify the most appropriate . /// - public class TopicViewResultExecutor : ViewExecutor, IActionResultExecutor { - - /// - /// Creates a new . - /// - /// The . - /// The . - /// The . - /// The . - /// The . - /// The . - public TopicViewResultExecutor( - IOptions viewOptions, - IHttpResponseStreamWriterFactory writerFactory, - ICompositeViewEngine viewEngine, - ITempDataDictionaryFactory tempDataFactory, - DiagnosticListener diagnosticListener, - IModelMetadataProvider modelMetadataProvider - ) : base( - viewOptions, writerFactory, viewEngine, tempDataFactory, diagnosticListener, modelMetadataProvider - ) { + /// + /// Will look for a view, in order, from the query string (?View=), collection + /// (for matches in the accepts header), then the property, if set, and finally falls back + /// to the . If none of those yield any results, will default to a content type of "Page", + /// which expects to find ~/Views/Page/Page.cshtml. + /// + /// The associated with the current request. + /// The . + /// A . + public ViewEngineResult FindView(ActionContext actionContext, TopicViewResult viewResult) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(actionContext, nameof(actionContext)); + Contract.Requires(viewResult, nameof(viewResult)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var routeData = actionContext.RouteData; + var contentType = viewResult.TopicContentType; + var topicView = viewResult.TopicView; + var viewEngine = viewResult.ViewEngine?? ViewEngine; + var requestContext = actionContext.HttpContext.Request; + var view = (ViewEngineResult?)null; + var searchedPaths = new List(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Cache content type as route variable + >------------------------------------------------------------------------------------------------------------------------- + | ### NOTE JJC20191123 This isn't required by the TopicViewResultExecutor itself, but is needed by the + | TopicViewLocationExpander, which is responsible for finding views that correspond to the ViewEngineResult returned by + | the TopicViewResultExecutor. This is necessary because by the time the TopicViewLocationExpander is executed, it only + | has access to the view name and the view data, but not the original TopicViewResult, or even the ViewEngineResult. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!routeData.Values.ContainsKey("contenttype")) { + routeData.Values.Add("contenttype", contentType); } - /*========================================================================================================================== - | METHOD: FIND VIEW + /*-------------------------------------------------------------------------------------------------------------------------- + | Check Querystring + >------------------------------------------------------------------------------------------------------------------------- + | Determines if the view is defined in the querystring. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loops through potential sources for views to identify the most appropriate . - /// - /// - /// Will look for a view, in order, from the query string (?View=), collection - /// (for matches in the accepts header), then the property, if set, and finally falls back - /// to the . If none of those yield any results, will default to a content type of "Page", - /// which expects to find ~/Views/Page/Page.cshtml. - /// - /// The associated with the current request. - /// The . - /// A . - public ViewEngineResult FindView(ActionContext actionContext, TopicViewResult viewResult) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(actionContext, nameof(actionContext)); - Contract.Requires(viewResult, nameof(viewResult)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var routeData = actionContext.RouteData; - var contentType = viewResult.TopicContentType; - var topicView = viewResult.TopicView; - var viewEngine = viewResult.ViewEngine?? ViewEngine; - var requestContext = actionContext.HttpContext.Request; - var view = (ViewEngineResult?)null; - var searchedPaths = new List(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Cache content type as route variable - >------------------------------------------------------------------------------------------------------------------------- - | ### NOTE JJC20191123 This isn't required by the TopicViewResultExecutor itself, but is needed by the - | TopicViewLocationExpander, which is responsible for finding views that correspond to the ViewEngineResult returned by - | the TopicViewResultExecutor. This is necessary because by the time the TopicViewLocationExpander is executed, it only - | has access to the view name and the view data, but not the original TopicViewResult, or even the ViewEngineResult. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!routeData.Values.ContainsKey("contenttype")) { - routeData.Values.Add("contenttype", contentType); + if (requestContext.Query.ContainsKey("View")) { + var queryStringValue = requestContext.Query["View"].First(); + if (queryStringValue is not null) { + view = viewEngine.FindView(actionContext, queryStringValue, isMainPage: true); + searchedPaths = [.. searchedPaths.Union(view.SearchedLocations ?? [])]; } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Check Querystring - >------------------------------------------------------------------------------------------------------------------------- - | Determines if the view is defined in the querystring. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (requestContext.Query.ContainsKey("View")) { - var queryStringValue = requestContext.Query["View"].First(); - if (queryStringValue is not null) { - view = viewEngine.FindView(actionContext, queryStringValue, isMainPage: true); - searchedPaths = searchedPaths.Union(view.SearchedLocations ?? Array.Empty()).ToList(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Pull Headers + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!(view?.Success ?? false) && requestContext.Headers.TryGetValue("Accept", out var acceptHeaders)) { + foreach (var header in acceptHeaders) { + if (header is null) { + continue; } - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Pull Headers - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!(view?.Success ?? false) && requestContext.Headers.ContainsKey("Accept")) { - foreach (var header in requestContext.Headers["Accept"]) { - var value = header.Replace("+", "-", StringComparison.Ordinal); - if (value.Contains('/', StringComparison.Ordinal)) { - value = value[(value.IndexOf("/", StringComparison.Ordinal)+1)..]; - } - if (value.Contains(';', StringComparison.Ordinal)) { - value = value[..(value.IndexOf(";", StringComparison.Ordinal))]; - } - if (value is not null) { - view = viewEngine.FindView(actionContext, value, isMainPage: true); - searchedPaths = searchedPaths.Union(view.SearchedLocations ?? Array.Empty()).ToList(); - } - if (view?.Success ?? false) { - break; - } + var value = header.Replace("+", "-", StringComparison.Ordinal); + if (value.Contains('/', StringComparison.Ordinal)) { + value = value[(value.IndexOf('/', StringComparison.Ordinal)+1)..]; + } + if (value.Contains(';', StringComparison.Ordinal)) { + value = value[..(value.IndexOf(';', StringComparison.Ordinal))]; + } + if (value is not null) { + view = viewEngine.FindView(actionContext, value, isMainPage: true); + searchedPaths = [.. searchedPaths.Union(view.SearchedLocations ?? [])]; + } + if (view?.Success ?? false) { + break; } } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Pull from action name - >------------------------------------------------------------------------------------------------------------------------- - | Typically, views in the topic library are contextual to the request, topic, or content type. When deriving from the - | TopicController, however, and implementing custom actions, we should prioritize views that correspond to that action, - | if they exist. This maps closely to how the default ViewResultExecutor works, but places it in the appropriate order for - | evaluation against other view sources. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!view?.Success ?? true) { - if (routeData.Values.TryGetValue("action", out var action)) { - var actionName = action?.ToString()?.Replace("Async", "", StringComparison.OrdinalIgnoreCase); + /*-------------------------------------------------------------------------------------------------------------------------- + | Pull from action name + >------------------------------------------------------------------------------------------------------------------------- + | Typically, views in the topic library are contextual to the request, topic, or content type. When deriving from the + | TopicController, however, and implementing custom actions, we should prioritize views that correspond to that action, + | if they exist. This maps closely to how the default ViewResultExecutor works, but places it in the appropriate order for + | evaluation against other view sources. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!view?.Success ?? true) { + if (routeData.Values.TryGetValue("action", out var action)) { + var actionName = action?.ToString()?.Replace("Async", "", StringComparison.OrdinalIgnoreCase); + if (actionName is not null) { view = ViewEngine.FindView(actionContext, actionName, isMainPage: true); - searchedPaths = searchedPaths.Union(view.SearchedLocations ?? Array.Empty()).ToList(); + searchedPaths = [.. searchedPaths.Union(view.SearchedLocations ?? [])]; } } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Pull from topic attribute - >------------------------------------------------------------------------------------------------------------------------- - | Pull from Topic's View Attribute; additional check against the Topic's ContentType Topic View Attribute is not necessary - | as it is set as the default View value for the Topic - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!(view?.Success ?? false) && !String.IsNullOrEmpty(topicView)) { - view = viewEngine.FindView(actionContext, topicView, isMainPage: true); - searchedPaths = searchedPaths.Union(view.SearchedLocations ?? Array.Empty()).ToList(); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Default to content type - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!view?.Success ?? true) { - view = viewEngine.FindView(actionContext, contentType, isMainPage: true); - searchedPaths = searchedPaths.Union(view.SearchedLocations ?? Array.Empty()).ToList(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Pull from topic attribute + >------------------------------------------------------------------------------------------------------------------------- + | Pull from Topic's View Attribute; additional check against the Topic's ContentType Topic View Attribute is not necessary + | as it is set as the default View value for the Topic + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!(view?.Success ?? false) && !String.IsNullOrEmpty(topicView)) { + view = viewEngine.FindView(actionContext, topicView, isMainPage: true); + searchedPaths = [.. searchedPaths.Union(view.SearchedLocations ?? [])]; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return view, if found - \-----------------------------------------------------------------------------------------------------------------------*/ - if (view is not null and { Success: true }) { - return view; - } - return ViewEngineResult.NotFound(contentType, searchedPaths); + /*-------------------------------------------------------------------------------------------------------------------------- + | Default to content type + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!view?.Success ?? true) { + view = viewEngine.FindView(actionContext, contentType, isMainPage: true); + searchedPaths = [.. searchedPaths.Union(view.SearchedLocations ?? [])]; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return view, if found + \-------------------------------------------------------------------------------------------------------------------------*/ + if (view is not null and { Success: true }) { + return view; } + return ViewEngineResult.NotFound(contentType, searchedPaths); - /*========================================================================================================================== - | METHOD: EXECUTE (ASYNC) + } + + /*============================================================================================================================ + | METHOD: EXECUTE (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task ExecuteAsync(ActionContext context, TopicViewResult result) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task ExecuteAsync(ActionContext context, TopicViewResult result) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - Contract.Requires(result, nameof(result)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Find view - \-----------------------------------------------------------------------------------------------------------------------*/ - var viewEngineResult = FindView(context, result); - viewEngineResult.EnsureSuccessful(originalLocations: null); - var view = viewEngineResult.View; - - /*------------------------------------------------------------------------------------------------------------------------ - | Execute - \-----------------------------------------------------------------------------------------------------------------------*/ - using (view as IDisposable) { - await ExecuteAsync( - context, - view, - result.ViewData, - result.TempData, - result.ContentType, - result.StatusCode - ).ConfigureAwait(false); - } + Contract.Requires(context, nameof(context)); + Contract.Requires(result, nameof(result)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Find view + \-------------------------------------------------------------------------------------------------------------------------*/ + var viewEngineResult = FindView(context, result); + viewEngineResult.EnsureSuccessful(originalLocations: null); + var view = viewEngineResult.View; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Execute + \-------------------------------------------------------------------------------------------------------------------------*/ + using (view as IDisposable) { + await ExecuteAsync( + context, + view, + result.ViewData, + result.TempData, + result.ContentType, + result.StatusCode + ).ConfigureAwait(false); } - } //Class -} //Namespace \ No newline at end of file + } + +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/_filters/TopicResponseCacheAttribute.cs b/OnTopic.AspNetCore.Mvc/_filters/TopicResponseCacheAttribute.cs index 321fd6de..4a39cfc7 100644 --- a/OnTopic.AspNetCore.Mvc/_filters/TopicResponseCacheAttribute.cs +++ b/OnTopic.AspNetCore.Mvc/_filters/TopicResponseCacheAttribute.cs @@ -11,159 +11,158 @@ using OnTopic.AspNetCore.Mvc.Controllers; using OnTopic.Attributes; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: RESPONSE CACHE FILTER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// When applied to a —or derived class—will apply any configured CacheProfile reference +/// associated with the current topic. +/// +/// +/// +/// The Page content type has a topic reference to a CacheProfile content type, which contains settings for +/// configuring HTTP response headers. The evaluates the current to +/// determine which, if any, CacheProfile it is associated with, and applies the settings to the HTTP response +/// headers. If a CacheProfile is not configured, it will default to the CacheProfile with the of Default. +/// +/// +/// This filter is enabled automatically when is +/// configured. It is only applied to actions on controllers derived from , which is needed +/// in order to ensure access to the current and a configured . +/// +/// +/// If the ASP.NET Core Response Caching Middleware is configured via e.g. , then the page content may be eligible for output caching, depending on the +/// configuration used. This allows the same processed page content to be used for multiple clients without the server +/// needing to rerender them. This reduces response time and CPU usages at a cost of increased memory. +/// +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public sealed class TopicResponseCacheAttribute : ActionFilterAttribute { /*============================================================================================================================ - | CLASS: RESPONSE CACHE FILTER + | PRIVATE VARIABLES \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// When applied to a —or derived class—will apply any configured CacheProfile reference - /// associated with the current topic. - /// - /// - /// - /// The Page content type has a topic reference to a CacheProfile content type, which contains settings for - /// configuring HTTP response headers. The evaluates the current to - /// determine which, if any, CacheProfile it is associated with, and applies the settings to the HTTP response - /// headers. If a CacheProfile is not configured, it will default to the CacheProfile with the of Default. - /// - /// - /// This filter is enabled automatically when is - /// configured. It is only applied to actions on controllers derived from , which is needed - /// in order to ensure access to the current and a configured . - /// - /// - /// If the ASP.NET Core Response Caching Middleware is configured via e.g. , then the page content may be eligible for output caching, depending on the - /// configuration used. This allows the same processed page content to be used for multiple clients without the server - /// needing to rerender them. This reduces response time and CPU usages at a cost of increased memory. - /// - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] - public sealed class TopicResponseCacheAttribute : ActionFilterAttribute { - - /*========================================================================================================================== - | PRIVATE VARIABLES + private static Topic? _defaultCacheProfile; + + /*============================================================================================================================ + | EVENT: ON ACTION EXECUTING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void OnActionExecuting(ActionExecutingContext context) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - private static Topic? _defaultCacheProfile; + Contract.Requires(context, nameof(context)); - /*========================================================================================================================== - | EVENT: ON ACTION EXECUTING + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate controller \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void OnActionExecuting(ActionExecutingContext context) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate controller - \-----------------------------------------------------------------------------------------------------------------------*/ - if (context.Controller is not TopicController controller) { - throw new InvalidOperationException( - $"The {nameof(TopicResponseCacheAttribute)} can only be applied to a controller deriving from {nameof(TopicController)}." - ); - } + if (context.Controller is not TopicController controller) { + throw new InvalidOperationException( + $"The {nameof(TopicResponseCacheAttribute)} can only be applied to a controller deriving from {nameof(TopicController)}." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure default cache profile - \-----------------------------------------------------------------------------------------------------------------------*/ + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure default cache profile + \-------------------------------------------------------------------------------------------------------------------------*/ - // Lookup the default cache profile for reference - _defaultCacheProfile ??= controller.TopicRepository.Load("Configuration:CacheProfiles:Default"); + // Lookup the default cache profile for reference + _defaultCacheProfile ??= controller.TopicRepository.Load("Configuration:CacheProfiles:Default"); - // Ensure the above lookup is only performed once per application - _defaultCacheProfile ??= new Topic("ImplicitDefault", "CacheProfile"); + // Ensure the above lookup is only performed once per application + _defaultCacheProfile ??= new Topic("ImplicitDefault", "CacheProfile"); - /*------------------------------------------------------------------------------------------------------------------------ - | Identify cache profile - \-----------------------------------------------------------------------------------------------------------------------*/ - var cacheProfile = controller.CurrentTopic?.References.GetValue("CacheProfile")?? _defaultCacheProfile; + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify cache profile + \-------------------------------------------------------------------------------------------------------------------------*/ + var cacheProfile = controller.CurrentTopic?.References.GetValue("CacheProfile")?? _defaultCacheProfile; - // If the empty cache profile is returned - if (cacheProfile.Key is "ImplicitDefault") { - return; - } + // If the empty cache profile is returned + if (cacheProfile.Key is "ImplicitDefault") { + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var headers = context.HttpContext.Response.Headers; - var duration = cacheProfile.Attributes.GetInteger("Duration"); - var location = Enum.Parse(cacheProfile.Attributes.GetValue("Location")?? "None"); - var noStore = cacheProfile.Attributes.GetBoolean("NoStore"); - var varyByHeader = cacheProfile.Attributes.GetValue("VaryByHeader"); - var varyByQueryKeys = cacheProfile.Attributes.GetValue("VaryByQueryKeys"); - - /*------------------------------------------------------------------------------------------------------------------------ - | Exit if the cache profile is effectively empty - \-----------------------------------------------------------------------------------------------------------------------*/ - if (duration is 0 && location is 0 && !noStore && String.IsNullOrEmpty(varyByHeader + varyByQueryKeys)) { - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var headers = context.HttpContext.Response.Headers; + var duration = cacheProfile.Attributes.GetInteger("Duration"); + var location = Enum.Parse(cacheProfile.Attributes.GetValue("Location")?? "None"); + var noStore = cacheProfile.Attributes.GetBoolean("NoStore"); + var varyByHeader = cacheProfile.Attributes.GetValue("VaryByHeader"); + var varyByQueryKeys = cacheProfile.Attributes.GetValue("VaryByQueryKeys"); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Exit if the cache profile is effectively empty + \-------------------------------------------------------------------------------------------------------------------------*/ + if (duration is 0 && location is 0 && !noStore && String.IsNullOrEmpty(varyByHeader + varyByQueryKeys)) { + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate metadata - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!noStore && duration is 0) { - throw new InvalidOperationException( - $"The {nameof(duration)} attribute must be set to a positive value if the {nameof(noStore)} attribute is not enabled." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate metadata + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!noStore && duration is 0) { + throw new InvalidOperationException( + $"The {nameof(duration)} attribute must be set to a positive value if the {nameof(noStore)} attribute is not enabled." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Clear existing headers - \-----------------------------------------------------------------------------------------------------------------------*/ - headers.Remove(HeaderNames.Vary); - headers.Remove(HeaderNames.CacheControl); - headers.Remove(HeaderNames.Pragma); - - /*------------------------------------------------------------------------------------------------------------------------ - | Vary by keys, if appropriate - \-----------------------------------------------------------------------------------------------------------------------*/ - if (varyByQueryKeys is not null) { - var responseCachingFeature = context.HttpContext.Features.Get(); - if (responseCachingFeature == null) { - throw new InvalidOperationException( - "VaryByQueryKeys depends on the ASP.NET Response Caching Middleware, which is not currently configured." - ); - } - responseCachingFeature.VaryByQueryKeys = varyByQueryKeys.Split(',', StringSplitOptions.RemoveEmptyEntries); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Clear existing headers + \-------------------------------------------------------------------------------------------------------------------------*/ + headers.Remove(HeaderNames.Vary); + headers.Remove(HeaderNames.CacheControl); + headers.Remove(HeaderNames.Pragma); - /*------------------------------------------------------------------------------------------------------------------------ - | Set standard HTTP headers - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!string.IsNullOrEmpty(varyByHeader)) { - headers[HeaderNames.Vary] = varyByHeader; + /*-------------------------------------------------------------------------------------------------------------------------- + | Vary by keys, if appropriate + \-------------------------------------------------------------------------------------------------------------------------*/ + if (varyByQueryKeys is not null) { + var responseCachingFeature = context.HttpContext.Features.Get(); + if (responseCachingFeature == null) { + throw new InvalidOperationException( + "VaryByQueryKeys depends on the ASP.NET Response Caching Middleware, which is not currently configured." + ); } + responseCachingFeature.VaryByQueryKeys = varyByQueryKeys.Split(',', StringSplitOptions.RemoveEmptyEntries); + } - if (noStore) { - headers[HeaderNames.CacheControl] = "no-store"; - if (location is ResponseCacheLocation.None) { - headers.AppendCommaSeparatedValues(HeaderNames.CacheControl, "no-cache"); - headers[HeaderNames.Pragma] = "no-cache"; - } - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Set standard HTTP headers + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!string.IsNullOrEmpty(varyByHeader)) { + headers[HeaderNames.Vary] = varyByHeader; + } + if (noStore) { + headers[HeaderNames.CacheControl] = "no-store"; if (location is ResponseCacheLocation.None) { - headers[HeaderNames.Pragma] = "no-cache"; + headers.AppendCommaSeparatedValues(HeaderNames.CacheControl, "no-cache"); + headers[HeaderNames.Pragma] = "no-cache"; } + return; + } + + if (location is ResponseCacheLocation.None) { + headers[HeaderNames.Pragma] = "no-cache"; + } - string? cacheControl = location switch { - ResponseCacheLocation.Any => "public", - ResponseCacheLocation.Client => "private", - ResponseCacheLocation.None => "no-cache", - _ => null - }; + string? cacheControl = location switch { + ResponseCacheLocation.Any => "public", + ResponseCacheLocation.Client => "private", + ResponseCacheLocation.None => "no-cache", + _ => null + }; - headers[HeaderNames.CacheControl] = $"{cacheControl},max-age={duration}"; + headers[HeaderNames.CacheControl] = $"{cacheControl},max-age={duration}"; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.AspNetCore.Mvc/_filters/ValidateTopicAttribute.cs b/OnTopic.AspNetCore.Mvc/_filters/ValidateTopicAttribute.cs index 01ebb4f7..dab68480 100644 --- a/OnTopic.AspNetCore.Mvc/_filters/ValidateTopicAttribute.cs +++ b/OnTopic.AspNetCore.Mvc/_filters/ValidateTopicAttribute.cs @@ -6,150 +6,151 @@ using Microsoft.AspNetCore.Mvc.Filters; using OnTopic.AspNetCore.Mvc.Controllers; -namespace OnTopic.AspNetCore.Mvc { +namespace OnTopic.AspNetCore.Mvc; + +/*============================================================================================================================== +| CLASS: VALIDATE TOPIC FILTER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// When applied to an action on a —or derived class—will validate the topic prior to further +/// execution. +/// +/// +/// Not all topics are appropriate to display in a view. If the topic isn't in the repository, the action should return a +/// . If the topic is marked as , then the action should return a +/// . If the topic contains a Url attribute, then the action should return a . All of this logic can be enforced by adding the to an +/// action. +/// +[AttributeUsage(AttributeTargets.Method)] +public sealed class ValidateTopicAttribute : ActionFilterAttribute { /*============================================================================================================================ - | CLASS: VALIDATE TOPIC FILTER + | PROPERTY: ALLOW NULL? \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// When applied to an action on a —or derived class—will validate the topic prior to further - /// execution. + /// Determines whether or not the action requires a current topic. /// /// - /// Not all topics are appropriate to display in a view. If the topic isn't in the repository, the action should return a - /// . If the topic is marked as , then the action should return a - /// . If the topic contains a Url attribute, then the action should return a . All of this logic can be enforced by adding the to an - /// action. + /// If is set to false (the default) then a is returned if + /// the cannot be resolved. /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class ValidateTopicAttribute : ActionFilterAttribute { + public bool AllowNull { get; set; } - /*========================================================================================================================== - | PROPERTY: ALLOW NULL? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not the action requires a current topic. - /// - /// - /// If is set to false (the default) then a is returned if - /// the cannot be resolved. - /// - public bool AllowNull { get; set; } - - /*========================================================================================================================== - | EVENT: ON ACTION EXECUTING + /*============================================================================================================================ + | EVENT: ON ACTION EXECUTING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides universal validation of calls to any action on or its derivatives. + /// + /// + /// While the event can be used to provide a wide variety of + /// filters, this specific implementation is focused on validating the state of the . Namely, it will provide error handling (if the is null), a + /// redirect (if the 's Url attribute is set, and an unauthorized + /// response (if the 's flag is set. + /// + /// A view associated with the requested topic's Content Type and view. + [NonAction] + public override void OnActionExecuting(ActionExecutingContext context) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides universal validation of calls to any action on or its derivatives. - /// - /// - /// While the event can be used to provide a wide variety of - /// filters, this specific implementation is focused on validating the state of the . Namely, it will provide error handling (if the is null), a - /// redirect (if the 's Url attribute is set, and an unauthorized - /// response (if the 's flag is set. - /// - /// A view associated with the requested topic's Content Type and view. - [NonAction] - public override void OnActionExecuting(ActionExecutingContext context) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(context, nameof(context)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate controller - \-----------------------------------------------------------------------------------------------------------------------*/ - if (context.Controller is not TopicController controller) { - throw new InvalidOperationException( - $"The {nameof(TopicResponseCacheAttribute)} can only be applied to a controller deriving from {nameof(TopicController)}." - ); - } + Contract.Requires(context, nameof(context)); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate current topic - \-----------------------------------------------------------------------------------------------------------------------*/ - var currentTopic = controller.CurrentTopic; + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate controller + \-------------------------------------------------------------------------------------------------------------------------*/ + if (context.Controller is not TopicController controller) { + throw new InvalidOperationException( + $"The {nameof(TopicResponseCacheAttribute)} can only be applied to a controller deriving from {nameof(TopicController)}." + ); + } - if (currentTopic is null) { - if (!AllowNull) { - context.Result = controller.NotFound(); - } - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate current topic + \-------------------------------------------------------------------------------------------------------------------------*/ + var currentTopic = controller.CurrentTopic; - /*------------------------------------------------------------------------------------------------------------------------ - | Handle disabled topic - \-----------------------------------------------------------------------------------------------------------------------*/ - //### TODO JJC082817: Should allow this to be bypassed for administrators; requires introduction of Role dependency - //### e.g., if (!Roles.IsUserInRole(Page?.User?.Identity?.Name ?? "", "Administrators")) {...} - if (currentTopic.IsDisabled) { - context.Result = new UnauthorizedResult(); - return; + if (currentTopic is null) { + if (!AllowNull) { + context.Result = controller.NotFound(); } + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle redirect - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!String.IsNullOrEmpty(currentTopic.Attributes.GetValue("URL"))) { - context.Result = controller.RedirectPermanent(currentTopic.Attributes.GetValue("URL")); - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle disabled topic + \-------------------------------------------------------------------------------------------------------------------------*/ + //### TODO JJC082817: Should allow this to be bypassed for administrators; requires introduction of Role dependency + //### e.g., if (!Roles.IsUserInRole(Page?.User?.Identity?.Name ?? "", "Administrators")) {...} + if (currentTopic.IsDisabled) { + context.Result = new UnauthorizedResult(); + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle nested topics - >------------------------------------------------------------------------------------------------------------------------- - | Nested topics are not expected to be viewed directly; if a user requests a nested topic, return a 403 to indicate that - | the request is valid, but forbidden. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (currentTopic is { ContentType: "List"} or { Parent.ContentType: "List" }) { - context.Result = new StatusCodeResult(403); - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle redirect + \-------------------------------------------------------------------------------------------------------------------------*/ + var redirectUrl = currentTopic.Attributes.GetValue("URL"); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle containers - >------------------------------------------------------------------------------------------------------------------------- - | Like nested topics, containers are not expected to be viewed directly; if a user requests a container, return a 403 to - | indicate that the request is valid, but forbidden. Unlike nested topics, children of containers are potentially valid. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (currentTopic.ContentType is "Container") { - context.Result = new StatusCodeResult(403); - return; - } + if (!String.IsNullOrEmpty(redirectUrl)) { + context.Result = controller.RedirectPermanent(redirectUrl); + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle page groups - >------------------------------------------------------------------------------------------------------------------------- - | PageGroups are a special content type for packaging multiple pages together. When a PageGroup is identified, the user is - | redirected to the first (non-hidden, non-disabled) page in the page group. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (currentTopic.ContentType is "PageGroup") { - var target = currentTopic.Children.Where(t => t.IsVisible()).FirstOrDefault()?.GetWebPath(); - context.Result = target is null? new StatusCodeResult(403) : controller.Redirect(target); - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle nested topics + >------------------------------------------------------------------------------------------------------------------------- + | Nested topics are not expected to be viewed directly; if a user requests a nested topic, return a 403 to indicate that + | the request is valid, but forbidden. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (currentTopic is { ContentType: "List"} or { Parent.ContentType: "List" }) { + context.Result = new StatusCodeResult(403); + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle canonical URL - >------------------------------------------------------------------------------------------------------------------------- - | Most search engines are case sensitive, even though many web servers are configured case insensitive. To help avoid - | mismatches between the requested URL and the canonical URL, and to help ensure that references to topics maintain the - | same case as assigned in the topic graph, URLs that vary only by case will be redirected to the expected case. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!currentTopic.GetWebPath().Equals(context.HttpContext.Request.Path, StringComparison.Ordinal)) { - context.Result = controller.RedirectPermanent(currentTopic.GetWebPath()); - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle containers + >------------------------------------------------------------------------------------------------------------------------- + | Like nested topics, containers are not expected to be viewed directly; if a user requests a container, return a 403 to + | indicate that the request is valid, but forbidden. Unlike nested topics, children of containers are potentially valid. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (currentTopic.ContentType is "Container") { + context.Result = new StatusCodeResult(403); + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Base processing - \-----------------------------------------------------------------------------------------------------------------------*/ - base.OnActionExecuting(context); + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle page groups + >------------------------------------------------------------------------------------------------------------------------- + | PageGroups are a special content type for packaging multiple pages together. When a PageGroup is identified, the user is + | redirected to the first (non-hidden, non-disabled) page in the page group. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (currentTopic.ContentType is "PageGroup") { + var target = currentTopic.Children.Where(t => t.IsVisible()).FirstOrDefault()?.GetWebPath(); + context.Result = target is null? new StatusCodeResult(403) : controller.Redirect(target); + return; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle canonical URL + >------------------------------------------------------------------------------------------------------------------------- + | Most search engines are case sensitive, even though many web servers are configured case insensitive. To help avoid + | mismatches between the requested URL and the canonical URL, and to help ensure that references to topics maintain the + | same case as assigned in the topic graph, URLs that vary only by case will be redirected to the expected case. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!currentTopic.GetWebPath().Equals(context.HttpContext.Request.Path, StringComparison.Ordinal)) { + context.Result = controller.RedirectPermanent(currentTopic.GetWebPath()); + return; } - } //Class -} //Namespace \ No newline at end of file + /*-------------------------------------------------------------------------------------------------------------------------- + | Base processing + \-------------------------------------------------------------------------------------------------------------------------*/ + base.OnActionExecuting(context); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Data.Caching/CachedTopicRepository.cs b/OnTopic.Data.Caching/CachedTopicRepository.cs index 24504eb5..0efe09d0 100644 --- a/OnTopic.Data.Caching/CachedTopicRepository.cs +++ b/OnTopic.Data.Caching/CachedTopicRepository.cs @@ -7,112 +7,116 @@ using OnTopic.Querying; using OnTopic.Repositories; -namespace OnTopic.Data.Caching { +namespace OnTopic.Data.Caching; + +/*============================================================================================================================== +| CLASS: CACHED TOPIC DATA REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides data access to topics stored in memory. +/// +/// +/// Concrete implementation of the class, which provides a wrapper +/// for an actual data access class. +/// + +public class CachedTopicRepository : TopicRepositoryDecorator { + + /*============================================================================================================================ + | VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly Topic _cache; /*============================================================================================================================ - | CLASS: CACHED TOPIC DATA REPOSITORY + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides data access to topics stored in memory. + /// Instantiates a new instance of the with a dependency on an underlying in order to provide necessary data access. /// - /// - /// Concrete implementation of the class, which provides a wrapper - /// for an actual data access class. - /// + /// + /// A concrete instance of an , which will be used for data access. + /// + /// A new instance of a . + public CachedTopicRepository(ITopicRepository topicRepository) : base(topicRepository) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure topics are loaded + \-------------------------------------------------------------------------------------------------------------------------*/ + var rootTopic = TopicRepository.Load(); - public class CachedTopicRepository : TopicRepositoryDecorator { + Contract.Assume( + rootTopic, + $"The topic graph could not be successfully loaded from the {nameof(ITopicRepository)} instance. The " + + $"{nameof(CachedTopicRepository)} is unable to establish the cache." + ); - /*========================================================================================================================== - | VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure topics are loaded \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly Topic _cache; + _cache = rootTopic; - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the with a dependency on an underlying in order to provide necessary data access. - /// - /// - /// A concrete instance of an , which will be used for data access. - /// - /// A new instance of a . - public CachedTopicRepository(ITopicRepository topicRepository) : base(topicRepository) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure topics are loaded - \-----------------------------------------------------------------------------------------------------------------------*/ - var rootTopic = TopicRepository.Load(); - - Contract.Assume( - rootTopic, - $"The topic graph could not be successfully loaded from the {nameof(ITopicRepository)} instance. The " + - $"{nameof(CachedTopicRepository)} is unable to establish the cache." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure topics are loaded - \-----------------------------------------------------------------------------------------------------------------------*/ - _cache = rootTopic; + } + + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle request for entire tree + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topicId < 0) { + return _cache; } - /*========================================================================================================================== - | METHOD: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Recursive search \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { + return _cache.FindFirst(t => t.Id.Equals(topicId)); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle request for entire tree - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topicId < 0) { - return _cache; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Recursive search - \-----------------------------------------------------------------------------------------------------------------------*/ - return _cache.FindFirst(t => t.Id.Equals(topicId)); + /// + public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + if (String.IsNullOrEmpty(uniqueKey)) { + return null; } - /// - public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - if (String.IsNullOrEmpty(uniqueKey)) { - return null; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup by TopicKey - \-----------------------------------------------------------------------------------------------------------------------*/ - return _cache.GetByUniqueKey(uniqueKey); + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup by TopicKey + \-------------------------------------------------------------------------------------------------------------------------*/ + return _cache.GetByUniqueKey(uniqueKey); - } + } - /// - public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) { + /// + public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) { - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(version.Date < DateTime.UtcNow, "The version requested must be a valid historical date."); - Contract.Requires( - version.Date > new DateTime(2014, 12, 9), - "The version is expected to have been created since version support was introduced into the topic library." - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Normalize parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + version = NormalizeToUtc(version); - /*------------------------------------------------------------------------------------------------------------------------ - | Return appropriate topic - \-----------------------------------------------------------------------------------------------------------------------*/ - return TopicRepository.Load(topicId, version, referenceTopic?? _cache); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(version.Date < DateTime.UtcNow, "The version requested must be a valid historical date."); + Contract.Requires( + version.Date >= new DateTime(2014, 12, 9), + "The version is expected to have been created since version support was introduced into the topic library." + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return appropriate topic + \-------------------------------------------------------------------------------------------------------------------------*/ + return TopicRepository.Load(topicId, version, referenceTopic?? _cache); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Data.Sql/Models/AttributeValuesDataTable.cs b/OnTopic.Data.Sql/Models/AttributeValuesDataTable.cs index c979a89a..fd3d86cb 100644 --- a/OnTopic.Data.Sql/Models/AttributeValuesDataTable.cs +++ b/OnTopic.Data.Sql/Models/AttributeValuesDataTable.cs @@ -6,73 +6,73 @@ using OnTopic.Attributes; using OnTopic.Collections.Specialized; -namespace OnTopic.Data.Sql.Models { +namespace OnTopic.Data.Sql.Models; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE VALUES (DATA TABLE) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Extends to model the schema for the AttributeValues user-defined table type. +/// +internal sealed class AttributeValuesDataTable: DataTable { /*============================================================================================================================ - | CLASS: ATTRIBUTE VALUES (DATA TABLE) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Extends to model the schema for the AttributeValues user-defined table type. + /// Establishes a new with the appropriate schema for the AttributeValues user-defined + /// table type. /// - internal class AttributeValuesDataTable: DataTable { + internal AttributeValuesDataTable() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | COLUMN: Attribute Key \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new with the appropriate schema for the AttributeValues user-defined - /// table type. - /// - internal AttributeValuesDataTable() { + Columns.Add( + new DataColumn("AttributeKey") { + MaxLength = 128 + } + ); - /*------------------------------------------------------------------------------------------------------------------------ - | COLUMN: Attribute Key - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add( - new DataColumn("AttributeKey") { - MaxLength = 128 - } - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | COLUMN: Attribute Value + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add( + new DataColumn("AttributeRecord") { + MaxLength = 255 + } + ); - /*------------------------------------------------------------------------------------------------------------------------ - | COLUMN: Attribute Value - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add( - new DataColumn("AttributeRecord") { - MaxLength = 255 - } - ); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a convenience method for adding a new based on the expected column values. + /// + /// The . + /// The . + internal DataRow AddRow(string attributeKey, string? attributeValue = null) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Define record \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a convenience method for adding a new based on the expected column values. - /// - /// The . - /// The . - internal DataRow AddRow(string attributeKey, string? attributeValue = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Define record - \-----------------------------------------------------------------------------------------------------------------------*/ - var record = NewRow(); - record["AttributeKey"] = attributeKey; - record["AttributeRecord"] = attributeValue; + var record = NewRow(); + record["AttributeKey"] = attributeKey; + record["AttributeRecord"] = attributeValue; - /*------------------------------------------------------------------------------------------------------------------------ - | Add record - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(record); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add record + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(record); - /*------------------------------------------------------------------------------------------------------------------------ - | Return record - \-----------------------------------------------------------------------------------------------------------------------*/ - return record; + /*-------------------------------------------------------------------------------------------------------------------------- + | Return record + \-------------------------------------------------------------------------------------------------------------------------*/ + return record; - } + } - } //Class -} //Namespaces \ No newline at end of file +} //Class +//Namespaces \ No newline at end of file diff --git a/OnTopic.Data.Sql/Models/TopicListDataTable.cs b/OnTopic.Data.Sql/Models/TopicListDataTable.cs index 1ba3f056..38715b44 100644 --- a/OnTopic.Data.Sql/Models/TopicListDataTable.cs +++ b/OnTopic.Data.Sql/Models/TopicListDataTable.cs @@ -4,60 +4,60 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Data.Sql.Models { +namespace OnTopic.Data.Sql.Models; + +/*============================================================================================================================== +| CLASS: TOPIC LIST (DATA TABLE) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Extends to model the schema for the TopicList user-defined table type. +/// +internal sealed class TopicListDataTable: DataTable { + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new with the appropriate schema for the TopicList user-defined + /// table type. + /// + internal TopicListDataTable() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | COLUMN: Topic ID + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add( + new DataColumn("TopicID", typeof(int)) + ); + + } /*============================================================================================================================ - | CLASS: TOPIC LIST (DATA TABLE) + | ADD ROW \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Extends to model the schema for the TopicList user-defined table type. + /// Provides a convenience method for adding a new based on the expected column values. /// - internal class TopicListDataTable: DataTable { + /// The of the related + internal DataRow AddRow(int topicId) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Define record \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new with the appropriate schema for the TopicList user-defined - /// table type. - /// - internal TopicListDataTable() { - - /*------------------------------------------------------------------------------------------------------------------------ - | COLUMN: Topic ID - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add( - new DataColumn("TopicID", typeof(int)) - ); - - } - - /*========================================================================================================================== - | ADD ROW + var record = NewRow(); + record["TopicID"] = topicId; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add record \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a convenience method for adding a new based on the expected column values. - /// - /// The of the related - internal DataRow AddRow(int topicId) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Define record - \-----------------------------------------------------------------------------------------------------------------------*/ - var record = NewRow(); - record["TopicID"] = topicId; - - /*------------------------------------------------------------------------------------------------------------------------ - | Add record - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(record); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return record - \-----------------------------------------------------------------------------------------------------------------------*/ - return record; - - } - - } //Class -} //Namespaces \ No newline at end of file + Rows.Add(record); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return record + \-------------------------------------------------------------------------------------------------------------------------*/ + return record; + + } + +} //Class +//Namespaces \ No newline at end of file diff --git a/OnTopic.Data.Sql/Models/TopicReferencesDataTable.cs b/OnTopic.Data.Sql/Models/TopicReferencesDataTable.cs index a9c1349b..b3d98c15 100644 --- a/OnTopic.Data.Sql/Models/TopicReferencesDataTable.cs +++ b/OnTopic.Data.Sql/Models/TopicReferencesDataTable.cs @@ -4,71 +4,71 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Data.Sql.Models { +namespace OnTopic.Data.Sql.Models; + +/*============================================================================================================================== +| CLASS: TOPIC REFERENCES (DATA TABLE) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Extends to model the schema for the TopicReferences user-defined table type. +/// +internal sealed class TopicReferencesDataTable: DataTable { /*============================================================================================================================ - | CLASS: TOPIC REFERENCES (DATA TABLE) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Extends to model the schema for the TopicReferences user-defined table type. + /// Establishes a new with the appropriate schema for the TopicReferences user-defined + /// table type. /// - internal class TopicReferencesDataTable: DataTable { + internal TopicReferencesDataTable() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | COLUMN: Reference Key \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new with the appropriate schema for the TopicReferences user-defined - /// table type. - /// - internal TopicReferencesDataTable() { + Columns.Add( + new DataColumn("ReferenceKey") { + MaxLength = 128 + } + ); - /*------------------------------------------------------------------------------------------------------------------------ - | COLUMN: Reference Key - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add( - new DataColumn("ReferenceKey") { - MaxLength = 128 - } - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | COLUMN: Topic ID + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add( + new DataColumn("TopicID", typeof(int)) + ); - /*------------------------------------------------------------------------------------------------------------------------ - | COLUMN: Topic ID - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add( - new DataColumn("TopicID", typeof(int)) - ); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a convenience method for adding a new based on the expected column values. + /// + /// The key to associated the referenced with. + /// The of the related . + internal DataRow AddRow(string referenceKey, int topicId) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Define record \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a convenience method for adding a new based on the expected column values. - /// - /// The key to associated the referenced with. - /// The of the related . - internal DataRow AddRow(string referenceKey, int topicId) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Define record - \-----------------------------------------------------------------------------------------------------------------------*/ - var record = NewRow(); - record["ReferenceKey"] = referenceKey; - record["TopicID"] = topicId; + var record = NewRow(); + record["ReferenceKey"] = referenceKey; + record["TopicID"] = topicId; - /*------------------------------------------------------------------------------------------------------------------------ - | Add record - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(record); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add record + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(record); - /*------------------------------------------------------------------------------------------------------------------------ - | Return record - \-----------------------------------------------------------------------------------------------------------------------*/ - return record; + /*-------------------------------------------------------------------------------------------------------------------------- + | Return record + \-------------------------------------------------------------------------------------------------------------------------*/ + return record; - } + } - } //Class -} //Namespaces \ No newline at end of file +} //Class +//Namespaces \ No newline at end of file diff --git a/OnTopic.Data.Sql/SqlCommandExtensions.cs b/OnTopic.Data.Sql/SqlCommandExtensions.cs index 8ebd48e4..44265bc1 100644 --- a/OnTopic.Data.Sql/SqlCommandExtensions.cs +++ b/OnTopic.Data.Sql/SqlCommandExtensions.cs @@ -6,153 +6,152 @@ using System.Globalization; using System.Text; -namespace OnTopic.Data.Sql { +namespace OnTopic.Data.Sql; + +/*============================================================================================================================== +| CLASS: SQL COMMAND EXTENSIONS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Extension methods for the class. +/// +internal static class SqlCommandExtensions { /*============================================================================================================================ - | CLASS: SQL COMMAND EXTENSIONS + | METHOD: GET RETURN CODE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Extension methods for the class. + /// Retrieves the return code from a stored procedure. /// - internal static class SqlCommandExtensions { - - /*========================================================================================================================== - | METHOD: GET RETURN CODE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the return code from a stored procedure. - /// - /// The SQL command object. - /// The name of the SQL parameter to retrieve as the return code. - internal static int GetReturnCode(this SqlCommand command, string sqlParameter = "ReturnCode") { - Contract.Assume( - command.Parameters.Contains($"@{sqlParameter}"), - $"The call to the {command.CommandText} stored procedure did not return the expected 'ReturnCode' parameter." - ); - var returnCode = command.Parameters[$"@{sqlParameter}"].Value?.ToString(); - if (Int32.TryParse(returnCode, NumberStyles.Integer, CultureInfo.InvariantCulture, out var returnValue)) { - return returnValue; - } - return -1; + /// The SQL command object. + /// The name of the SQL parameter to retrieve as the return code. + internal static int GetReturnCode(this SqlCommand command, string sqlParameter = "ReturnCode") { + Contract.Assume( + command.Parameters.Contains($"@{sqlParameter}"), + $"The call to the {command.CommandText} stored procedure did not return the expected 'ReturnCode' parameter." + ); + var returnCode = command.Parameters[$"@{sqlParameter}"].Value?.ToString(); + if (Int32.TryParse(returnCode, NumberStyles.Integer, CultureInfo.InvariantCulture, out var returnValue)) { + return returnValue; } + return -1; + } + + /*============================================================================================================================ + | METHOD: ADD OUTPUT PARAMETER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a SQL parameter to a command object, additionally setting the specified parameter direction. + /// + /// The SQL command object. + /// The name of the SQL output parameter. + internal static void AddOutputParameter(this SqlCommand command, string sqlParameter = "ReturnCode") => + AddParameter(command, sqlParameter, null, SqlDbType.Int, ParameterDirection.ReturnValue); + + /*============================================================================================================================ + | METHOD: ADD PARAMETER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Wrapper function that adds a SQL parameter to a command object. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + internal static void AddParameter(this SqlCommand command, string sqlParameter, int fieldValue) + => AddParameter(command, sqlParameter, fieldValue, SqlDbType.Int); - /*========================================================================================================================== - | METHOD: ADD OUTPUT PARAMETER + /// + /// Wrapper function that adds a SQL parameter to a command object. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + internal static void AddParameter(this SqlCommand command, string sqlParameter, bool fieldValue) + => AddParameter(command, sqlParameter, fieldValue, SqlDbType.Bit); + + /// + /// Wrapper function that adds a SQL parameter to a command object. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + internal static void AddParameter(this SqlCommand command, string sqlParameter, DateTime fieldValue) + => AddParameter(command, sqlParameter, fieldValue, SqlDbType.DateTime2); + + /// + /// Wrapper function that adds a SQL parameter to a command object. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + internal static void AddParameter(this SqlCommand command, string sqlParameter, DataTable fieldValue) + => AddParameter(command, sqlParameter, fieldValue, SqlDbType.Structured); + + /// + /// Wrapper function that adds a SQL parameter to a command object. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + internal static void AddParameter(this SqlCommand command, string sqlParameter, StringBuilder fieldValue) + => AddParameter(command, sqlParameter, fieldValue.ToString(), SqlDbType.Xml); + + /// + /// Wrapper function that adds a SQL parameter to a command object. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + internal static void AddParameter(this SqlCommand command, string sqlParameter, string? fieldValue) + => AddParameter(command, sqlParameter, String.IsNullOrEmpty(fieldValue)? null : fieldValue, SqlDbType.VarChar); + + /// + /// Adds a SQL parameter to a command object, additionally setting the specified SQL data length for the field. + /// + /// The SQL command object. + /// The SQL parameter. + /// The SQL field value. + /// The SQL field data type. + /// The SQL parameter's directional setting (input-only, output-only, etc.). + /// + /// command is not null + /// + private static void AddParameter( + SqlCommand command, + string sqlParameter, + object? fieldValue, + SqlDbType sqlDbType, + ParameterDirection paramDirection = ParameterDirection.Input + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish basic parameter \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a SQL parameter to a command object, additionally setting the specified parameter direction. - /// - /// The SQL command object. - /// The name of the SQL output parameter. - internal static void AddOutputParameter(this SqlCommand command, string sqlParameter = "ReturnCode") => - AddParameter(command, sqlParameter, null, SqlDbType.Int, ParameterDirection.ReturnValue); - - /*========================================================================================================================== - | METHOD: ADD PARAMETER + var parameter = new SqlParameter("@" + sqlParameter, sqlDbType) { + Direction = paramDirection + }; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set parameter value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Wrapper function that adds a SQL parameter to a command object. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - internal static void AddParameter(this SqlCommand command, string sqlParameter, int fieldValue) - => AddParameter(command, sqlParameter, fieldValue, SqlDbType.Int); - - /// - /// Wrapper function that adds a SQL parameter to a command object. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - internal static void AddParameter(this SqlCommand command, string sqlParameter, bool fieldValue) - => AddParameter(command, sqlParameter, fieldValue, SqlDbType.Bit); - - /// - /// Wrapper function that adds a SQL parameter to a command object. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - internal static void AddParameter(this SqlCommand command, string sqlParameter, DateTime fieldValue) - => AddParameter(command, sqlParameter, fieldValue, SqlDbType.DateTime2); - - /// - /// Wrapper function that adds a SQL parameter to a command object. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - internal static void AddParameter(this SqlCommand command, string sqlParameter, DataTable fieldValue) - => AddParameter(command, sqlParameter, fieldValue, SqlDbType.Structured); - - /// - /// Wrapper function that adds a SQL parameter to a command object. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - internal static void AddParameter(this SqlCommand command, string sqlParameter, StringBuilder fieldValue) - => AddParameter(command, sqlParameter, fieldValue.ToString(), SqlDbType.Xml); - - /// - /// Wrapper function that adds a SQL parameter to a command object. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - internal static void AddParameter(this SqlCommand command, string sqlParameter, string? fieldValue) - => AddParameter(command, sqlParameter, String.IsNullOrEmpty(fieldValue)? null : fieldValue, SqlDbType.VarChar); - - /// - /// Adds a SQL parameter to a command object, additionally setting the specified SQL data length for the field. - /// - /// The SQL command object. - /// The SQL parameter. - /// The SQL field value. - /// The SQL field data type. - /// The SQL parameter's directional setting (input-only, output-only, etc.). - /// - /// command is not null - /// - private static void AddParameter( - SqlCommand command, - string sqlParameter, - object? fieldValue, - SqlDbType sqlDbType, - ParameterDirection paramDirection = ParameterDirection.Input - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish basic parameter - \-----------------------------------------------------------------------------------------------------------------------*/ - var parameter = new SqlParameter("@" + sqlParameter, sqlDbType) { - Direction = paramDirection + if (fieldValue is null) { + parameter.Value = (string?)null; + } + else if (paramDirection is ParameterDirection.Input) { + parameter.Value = sqlDbType switch { + SqlDbType.Bit => (bool)fieldValue, + SqlDbType.DateTime2 => (DateTime)fieldValue, + SqlDbType.Int => (int)fieldValue, + SqlDbType.Xml => (string)fieldValue, + SqlDbType.Structured => (DataTable)fieldValue, + _ => (string)fieldValue, }; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Set parameter value - \-----------------------------------------------------------------------------------------------------------------------*/ - if (fieldValue is null) { - parameter.Value = (string?)null; - } - else if (paramDirection is ParameterDirection.Input) { - parameter.Value = sqlDbType switch { - SqlDbType.Bit => (bool)fieldValue, - SqlDbType.DateTime2 => (DateTime)fieldValue, - SqlDbType.Int => (int)fieldValue, - SqlDbType.Xml => (string)fieldValue, - SqlDbType.Structured => (DataTable)fieldValue, - _ => (string)fieldValue, - }; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Add parameter to command - \-----------------------------------------------------------------------------------------------------------------------*/ - command.Parameters.Add(parameter); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add parameter to command + \-------------------------------------------------------------------------------------------------------------------------*/ + command.Parameters.Add(parameter); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Data.Sql/SqlDataReaderExtensions.cs b/OnTopic.Data.Sql/SqlDataReaderExtensions.cs index a3a5ced4..b6ee0d64 100644 --- a/OnTopic.Data.Sql/SqlDataReaderExtensions.cs +++ b/OnTopic.Data.Sql/SqlDataReaderExtensions.cs @@ -8,532 +8,531 @@ using OnTopic.Collections.Specialized; using OnTopic.Querying; -namespace OnTopic.Data.Sql { +namespace OnTopic.Data.Sql; + +/*============================================================================================================================== +| CLASS: SQL DATA READER EXTENSIONS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Extension methods for the class. +/// +/// +/// Most of the extensions are optimized for reading the data returned from the GetTopics and GetTopicVersion +/// stored procedures, which require parsing multiple data sets in order to populate a topic graph. For that purpose, the +/// main entry point is . It is supported by a number of private extensions which allow +/// it to handle individual records from particular data sets (e.g., the method maps to +/// data returned from the ExtendedAttributeIndex view). That said, the Get extensions (e.g., ) are not specific to this format, and remain useful for a variety of database +/// queries, should they be needed, and thus are marked as internal. +/// +internal static class SqlDataReaderExtensions { /*============================================================================================================================ - | CLASS: SQL DATA READER EXTENSIONS + | METHOD: LOAD TOPIC GRAPH \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Extension methods for the class. + /// Given a from a call to the GetTopics stored procedure, will extract a list of + /// topics and populate their attributes, associations, and children. /// - /// - /// Most of the extensions are optimized for reading the data returned from the GetTopics and GetTopicVersion - /// stored procedures, which require parsing multiple data sets in order to populate a topic graph. For that purpose, the - /// main entry point is . It is supported by a number of private extensions which allow - /// it to handle individual records from particular data sets (e.g., the method maps to - /// data returned from the ExtendedAttributeIndex view). That said, the Get extensions (e.g., ) are not specific to this format, and remain useful for a variety of database - /// queries, should they be needed, and thus are marked as internal. - /// - internal static class SqlDataReaderExtensions { + /// The with output from the GetTopics stored procedure. + /// + /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic + /// associations—such as references, relationships, and —are integrated with existing entities. + /// + /// + /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it + /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that + /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update + /// from being persisted to the data store on . + /// + /// + /// Optionally disables populating external references such as and . This is useful for cases where it's known that a shallow copy is being retrieved, and + /// thus external references aren't likely to be available. + /// + internal static Topic? LoadTopicGraph( + this IDataReader reader, + Topic? referenceTopic = null, + bool? markDirty = null, + bool includeExternalReferences = true + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish topic index + \-------------------------------------------------------------------------------------------------------------------------*/ + var sqlDataReader = reader as SqlDataReader; + var topics = referenceTopic is not null? referenceTopic.GetRootTopic().GetTopicIndex() : new(); + var rootTopicId = -1; - /*========================================================================================================================== - | METHOD: LOAD TOPIC GRAPH + /*-------------------------------------------------------------------------------------------------------------------------- + | Populate topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a from a call to the GetTopics stored procedure, will extract a list of - /// topics and populate their attributes, associations, and children. - /// - /// The with output from the GetTopics stored procedure. - /// - /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic - /// associations—such as references, relationships, and —are integrated with existing entities. - /// - /// - /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it - /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that - /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update - /// from being persisted to the data store on . - /// - /// - /// Optionally disables populating external references such as and . This is useful for cases where it's known that a shallow copy is being retrieved, and - /// thus external references aren't likely to be available. - /// - internal static Topic? LoadTopicGraph( - this IDataReader reader, - Topic? referenceTopic = null, - bool? markDirty = null, - bool includeExternalReferences = true - ) { - - /*---------------------------------------------------------------------------------------------------------------------- - | Establish topic index - \---------------------------------------------------------------------------------------------------------------------*/ - var sqlDataReader = reader as SqlDataReader; - var topics = referenceTopic is not null? referenceTopic.GetRootTopic().GetTopicIndex() : new(); - var rootTopicId = -1; - - /*---------------------------------------------------------------------------------------------------------------------- - | Populate topics - \---------------------------------------------------------------------------------------------------------------------*/ - Debug.WriteLine("SqlTopicRepository.Load(): AddTopic() [" + DateTime.Now + "]"); - while (reader.Read()) { - if (rootTopicId < 0) { - rootTopicId = reader.GetTopicId(); - } - reader.AddTopic(topics, markDirty); + Debug.WriteLine("SqlTopicRepository.Load(): AddTopic() [" + DateTime.Now + "]"); + while (reader.Read()) { + if (rootTopicId < 0) { + rootTopicId = reader.GetTopicId(); } + reader.AddTopic(topics, markDirty); + } - /*---------------------------------------------------------------------------------------------------------------------- - | Read attributes - \---------------------------------------------------------------------------------------------------------------------*/ - Debug.WriteLine("SqlTopicRepository.Load(): SetIndexedAttributes() [" + DateTime.Now + "]"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Read attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + Debug.WriteLine("SqlTopicRepository.Load(): SetIndexedAttributes() [" + DateTime.Now + "]"); - // Move to TopicAttributes dataset - reader.NextResult(); + // Move to TopicAttributes dataset + reader.NextResult(); - while (reader.Read()) { - reader.SetIndexedAttributes(topics, markDirty); - } + while (reader.Read()) { + reader.SetIndexedAttributes(topics, markDirty); + } - /*---------------------------------------------------------------------------------------------------------------------- - | Read extended attributes - \---------------------------------------------------------------------------------------------------------------------*/ - Debug.WriteLine("SqlTopicRepository.Load(): SetExtendedAttributes() [" + DateTime.Now + "]"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Read extended attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + Debug.WriteLine("SqlTopicRepository.Load(): SetExtendedAttributes() [" + DateTime.Now + "]"); - // Move to extened attributes dataset - reader.NextResult(); + // Move to extened attributes dataset + reader.NextResult(); - // Loop through each extended attribute record associated with a specific topic - while (reader.Read()) { - sqlDataReader?.SetExtendedAttributes(topics, markDirty); - } + // Loop through each extended attribute record associated with a specific topic + while (reader.Read()) { + sqlDataReader?.SetExtendedAttributes(topics, markDirty); + } - /*---------------------------------------------------------------------------------------------------------------------- - | Read related items - \---------------------------------------------------------------------------------------------------------------------*/ - Debug.WriteLine("SqlTopicRepository.Load(): SetRelationships() [" + DateTime.Now + "]"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Read related items + \-------------------------------------------------------------------------------------------------------------------------*/ + Debug.WriteLine("SqlTopicRepository.Load(): SetRelationships() [" + DateTime.Now + "]"); - // Move to the relationships dataset - reader.NextResult(); + // Move to the relationships dataset + reader.NextResult(); - // Loop through each relationship; multiple records may exist per topic - if (includeExternalReferences) { - while (reader.Read()) { - reader.SetRelationships(topics, markDirty); - } + // Loop through each relationship; multiple records may exist per topic + if (includeExternalReferences) { + while (reader.Read()) { + reader.SetRelationships(topics, markDirty); } + } - /*---------------------------------------------------------------------------------------------------------------------- - | Read referenced items - \---------------------------------------------------------------------------------------------------------------------*/ - Debug.WriteLine("SqlTopicRepository.Load(): SetReferences() [" + DateTime.Now + "]"); - - // Move to the version history dataset - reader.NextResult(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Read referenced items + \-------------------------------------------------------------------------------------------------------------------------*/ + Debug.WriteLine("SqlTopicRepository.Load(): SetReferences() [" + DateTime.Now + "]"); - // Loop through each version; multiple records may exist per topic - while (reader.Read()) { - reader.SetReferences(topics, markDirty); - } + // Move to the version history dataset + reader.NextResult(); - /*---------------------------------------------------------------------------------------------------------------------- - | Read version history - \---------------------------------------------------------------------------------------------------------------------*/ - Debug.WriteLine("SqlTopicRepository.Load(): SetVersionHistory() [" + DateTime.Now + "]"); + // Loop through each version; multiple records may exist per topic + while (reader.Read()) { + reader.SetReferences(topics, markDirty); + } - // Move to the version history dataset - reader.NextResult(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Read version history + \-------------------------------------------------------------------------------------------------------------------------*/ + Debug.WriteLine("SqlTopicRepository.Load(): SetVersionHistory() [" + DateTime.Now + "]"); - // Loop through each version; multiple records may exist per topic - while (reader.Read()) { - reader.SetVersionHistory(topics); - } + // Move to the version history dataset + reader.NextResult(); - /*------------------------------------------------------------------------------------------------------------------------ - | Return objects - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topics.TryGetValue(rootTopicId, out var rootTopic)) { - return rootTopic; - } - return topics.Values.FirstOrDefault(); + // Loop through each version; multiple records may exist per topic + while (reader.Read()) { + reader.SetVersionHistory(topics); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return objects + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topics.TryGetValue(rootTopicId, out var rootTopic)) { + return rootTopic; } + return topics.Values.FirstOrDefault(); + + } - /*========================================================================================================================== - | METHOD: ADD TOPIC + /*============================================================================================================================ + | METHOD: ADD TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given the primary topic attributes from the TopicIndex view, establishes a barebones + /// instance and adds it to the collection. + /// + /// The with output from the GetTopics stored procedure. + /// A of topics to be loaded. + /// + /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it + /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that + /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update + /// from being persisted to the data store on . + /// + private static void AddTopic(this IDataReader reader, TopicIndex topics, bool? markDirty) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var topicId = reader.GetTopicId(); + var key = reader.GetString("TopicKey"); + var contentType = reader.GetString("ContentType"); + var parentId = reader.GetInteger("ParentID"); + var wasDirty = false; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given the primary topic attributes from the TopicIndex view, establishes a barebones - /// instance and adds it to the collection. - /// - /// The with output from the GetTopics stored procedure. - /// A of topics to be loaded. - /// - /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it - /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that - /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update - /// from being persisted to the data store on . - /// - private static void AddTopic(this IDataReader reader, TopicIndex topics, bool? markDirty) { + if (!topics.TryGetValue(topicId, out var current)) { + current = TopicFactory.Create(key, contentType, topicId); + topics.Add(current.Id, current); + } + else { + wasDirty = current.IsDirty(); + current.Key = key; + current.ContentType = contentType; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicId = reader.GetTopicId(); - var key = reader.GetString("TopicKey"); - var contentType = reader.GetString("ContentType"); - var parentId = reader.GetInteger("ParentID"); - var wasDirty = false; + /*-------------------------------------------------------------------------------------------------------------------------- + | Assign parent + \-------------------------------------------------------------------------------------------------------------------------*/ + if (parentId >= 0 && current.Parent?.Id != parentId && topics.TryGetValue(parentId, out var parentTopic)) { + current.Parent = parentTopic; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish topic - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!topics.TryGetValue(topicId, out var current)) { - current = TopicFactory.Create(key, contentType, topicId); - topics.Add(current.Id, current); - } - else { - wasDirty = current.IsDirty(); - current.Key = key; - current.ContentType = contentType; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Mark clean + \-------------------------------------------------------------------------------------------------------------------------*/ + if (wasDirty is false && markDirty is not null and false) { + current.MarkClean(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Assign parent - \-----------------------------------------------------------------------------------------------------------------------*/ - if (parentId >= 0 && current.Parent?.Id != parentId && topics.ContainsKey(parentId)) { - current.Parent = topics[parentId]; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Mark clean - \-----------------------------------------------------------------------------------------------------------------------*/ - if (wasDirty is false && markDirty is not null and false) { - current.MarkClean(); - } + /*============================================================================================================================ + | METHOD: SET INDEXED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given an attribute record from the AttributeIndex view, finds the associated in the + /// collection, and sets the corresponding value. + /// + /// The with output from the GetTopics stored procedure. + /// A of topics to be loaded. + /// + /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it + /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that + /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update + /// from being persisted to the data store on . + /// + private static void SetIndexedAttributes(this IDataReader reader, TopicIndex topics, bool? markDirty) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var topicId = reader.GetTopicId(); + var attributeKey = reader.GetString("AttributeKey"); + var attributeValue = reader.GetNullableString("AttributeValue"); + var version = reader.GetVersion(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify topic + \-------------------------------------------------------------------------------------------------------------------------*/ + var current = topics[topicId]; - /*========================================================================================================================== - | METHOD: SET INDEXED ATTRIBUTES + /*-------------------------------------------------------------------------------------------------------------------------- + | Set attribute value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given an attribute record from the AttributeIndex view, finds the associated in the - /// collection, and sets the corresponding value. - /// - /// The with output from the GetTopics stored procedure. - /// A of topics to be loaded. - /// - /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it - /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that - /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update - /// from being persisted to the data store on . - /// - private static void SetIndexedAttributes(this IDataReader reader, TopicIndex topics, bool? markDirty) { + current.Attributes.SetValue(attributeKey, attributeValue, markDirty, version, false); - /*------------------------------------------------------------------------------------------------------------------------ - | Identify attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicId = reader.GetTopicId(); - var attributeKey = reader.GetString("AttributeKey"); - var attributeValue = reader.GetNullableString("AttributeValue"); - var version = reader.GetVersion(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify topic - \-----------------------------------------------------------------------------------------------------------------------*/ - var current = topics[topicId]; + /*============================================================================================================================ + | METHOD: SET EXTENDED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given an XML record from the ExtendedAttributeIndex view, finds the associated in the + /// collection, and sets each of the the corresponding value. + /// + /// + /// Values of arbitrary length are stored in an XML entry. This makes them more efficient to store, but more difficult to + /// query; as such, it's ideal for content-oriented data. The XML values are returned as a separate data set. + /// + /// The with output from the GetTopics stored procedure. + /// A of topics to be loaded. + /// + /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it + /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that + /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update + /// from being persisted to the data store on . + /// + private static void SetExtendedAttributes(this SqlDataReader reader, TopicIndex topics, bool? markDirty) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var topicId = reader.GetTopicId(); + var version = reader.GetVersion(); - /*------------------------------------------------------------------------------------------------------------------------ - | Set attribute value - \-----------------------------------------------------------------------------------------------------------------------*/ - current.Attributes.SetValue(attributeKey, attributeValue, markDirty, version, false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Load SQL XML into XmlDocument + \-------------------------------------------------------------------------------------------------------------------------*/ + var xmlData = reader.GetSqlXml(1); + var xmlReader = xmlData.CreateReader(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify the current topic + \-------------------------------------------------------------------------------------------------------------------------*/ + var current = topics[topicId]; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle scenario where there isn't an element + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!xmlReader.ReadToFollowing("attribute")) return; - /*========================================================================================================================== - | METHOD: SET EXTENDED ATTRIBUTES + /*-------------------------------------------------------------------------------------------------------------------------- + | Loop through nodes to set attributes \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given an XML record from the ExtendedAttributeIndex view, finds the associated in the - /// collection, and sets each of the the corresponding value. - /// - /// - /// Values of arbitrary length are stored in an XML entry. This makes them more efficient to store, but more difficult to - /// query; as such, it's ideal for content-oriented data. The XML values are returned as a separate data set. - /// - /// The with output from the GetTopics stored procedure. - /// A of topics to be loaded. - /// - /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it - /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that - /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update - /// from being persisted to the data store on . - /// - private static void SetExtendedAttributes(this SqlDataReader reader, TopicIndex topics, bool? markDirty) { + do { /*------------------------------------------------------------------------------------------------------------------------ | Identify attributes \-----------------------------------------------------------------------------------------------------------------------*/ - var topicId = reader.GetTopicId(); - var version = reader.GetVersion(); + var attributeKey = (string?)xmlReader.GetAttribute("key"); + var attributeValue = WebUtility.HtmlDecode(xmlReader.ReadInnerXml()); /*------------------------------------------------------------------------------------------------------------------------ - | Load SQL XML into XmlDocument + | Validate assumptions \-----------------------------------------------------------------------------------------------------------------------*/ - var xmlData = reader.GetSqlXml(1); - var xmlReader = xmlData.CreateReader(); + Contract.Assume( + attributeKey, + $"The @key attribute of the element is missing for Topic '{topicId}'; the data is not in the " + + $"expected format." + ); /*------------------------------------------------------------------------------------------------------------------------ - | Identify the current topic + | Set attribute value \-----------------------------------------------------------------------------------------------------------------------*/ - var current = topics[topicId]; + if (String.IsNullOrEmpty(attributeValue)) continue; + current.Attributes.SetValue(attributeKey, attributeValue, markDirty, version, true); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle scenario where there isn't an element - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!xmlReader.ReadToFollowing("attribute")) return; + } while (xmlReader.Name is "attribute"); - /*------------------------------------------------------------------------------------------------------------------------ - | Loop through nodes to set attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - do { - - /*---------------------------------------------------------------------------------------------------------------------- - | Identify attributes - \---------------------------------------------------------------------------------------------------------------------*/ - var attributeKey = (string?)xmlReader.GetAttribute("key"); - var attributeValue = WebUtility.HtmlDecode(xmlReader.ReadInnerXml()); - - /*---------------------------------------------------------------------------------------------------------------------- - | Validate assumptions - \---------------------------------------------------------------------------------------------------------------------*/ - Contract.Assume( - attributeKey, - $"The @key attribute of the element is missing for Topic '{topicId}'; the data is not in the " + - $"expected format." - ); - - /*---------------------------------------------------------------------------------------------------------------------- - | Set attribute value - \---------------------------------------------------------------------------------------------------------------------*/ - if (String.IsNullOrEmpty(attributeValue)) continue; - current.Attributes.SetValue(attributeKey, attributeValue, markDirty, version, true); - - } while (xmlReader.Name is "attribute"); + } - } + /*============================================================================================================================ + | METHOD: SET RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds relationships retrieved from an individual relationship record to their associated topics. + /// + /// + /// Topics can be cross-referenced with each other via a many-to-many relationships. Once the topics are populated in + /// memory, loop through the data to create these associations. + /// + /// The with output from the GetTopics stored procedure. + /// A of topics to be loaded. + /// + /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it + /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that + /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update + /// from being persisted to the data store on . + /// + private static void SetRelationships(this IDataReader reader, TopicIndex topics, bool? markDirty = false) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var sourceTopicId = reader.GetTopicId("Source_TopicID"); + var targetTopicId = reader.GetTopicId("Target_TopicID"); + var relationshipKey = reader.GetString("RelationshipKey"); + var isDeleted = reader.GetBoolean("IsDeleted"); - /*========================================================================================================================== - | METHOD: SET RELATIONSHIPS + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify affected topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds relationships retrieved from an individual relationship record to their associated topics. - /// - /// - /// Topics can be cross-referenced with each other via a many-to-many relationships. Once the topics are populated in - /// memory, loop through the data to create these associations. - /// - /// The with output from the GetTopics stored procedure. - /// A of topics to be loaded. - /// - /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it - /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that - /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update - /// from being persisted to the data store on . - /// - private static void SetRelationships(this IDataReader reader, TopicIndex topics, bool? markDirty = false) { + var current = topics[sourceTopicId]; + var related = (Topic?)null; - /*------------------------------------------------------------------------------------------------------------------------ - | Identify attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var sourceTopicId = reader.GetTopicId("Source_TopicID"); - var targetTopicId = reader.GetTopicId("Target_TopicID"); - var relationshipKey = reader.GetString("RelationshipKey"); - var isDeleted = reader.GetBoolean("IsDeleted"); + // Fetch the related topic + if (topics.TryGetValue(targetTopicId, out var relatedTopic)) { + related = relatedTopic; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify affected topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var current = topics[sourceTopicId]; - var related = (Topic?)null; + // Bypass if the target object is missing + if (related is null) { + current.Relationships.IsFullyLoaded = false; + return; + } - // Fetch the related topic - if (topics.ContainsKey(targetTopicId)) { - related = topics[targetTopicId]; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Set relationship on object + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!isDeleted) { + current.Relationships.SetValue(relationshipKey, related, markDirty); + } + else if (current.Relationships.Contains(relationshipKey, related)) { + current.Relationships.Remove(relationshipKey, related); + } - // Bypass if the target object is missing - if (related is null) { - current.Relationships.IsFullyLoaded = false; - return; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Set relationship on object - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!isDeleted) { - current.Relationships.SetValue(relationshipKey, related, markDirty); - } - else if (current.Relationships.Contains(relationshipKey, related)) { - current.Relationships.Remove(relationshipKey, related); - } + /*============================================================================================================================ + | METHOD: SET REFERENCES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds topic references to their associated topics. + /// + /// + /// Topics can be cross-referenced with each other topics via a one-to-one associations. Once the topics are populated in + /// memory, loop through the data to create these associations. + /// + /// The with output from the GetTopics stored procedure. + /// A of topics to be loaded. + /// + /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it + /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that + /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update + /// from being persisted to the data store on . + /// + private static void SetReferences(this IDataReader reader, TopicIndex topics, bool? markDirty) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var sourceTopicId = reader.GetTopicId("Source_TopicID"); + var referenceKey = reader.GetString("ReferenceKey"); + var targetTopicId = reader.GetNullableTopicId("Target_TopicID"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify affected topics + \-------------------------------------------------------------------------------------------------------------------------*/ + var current = topics[sourceTopicId]; + var referenced = (Topic?)null; + + // Fetch the related topic + if (targetTopicId is null) { + } + else if (topics.TryGetValue(targetTopicId.Value, out var referencedTopic)) { + referenced = referencedTopic; + } + else { + current.References.IsFullyLoaded = false; + return; } - /*========================================================================================================================== - | METHOD: SET REFERENCES + /*-------------------------------------------------------------------------------------------------------------------------- + | Set reference on object \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds topic references to their associated topics. - /// - /// - /// Topics can be cross-referenced with each other topics via a one-to-one associations. Once the topics are populated in - /// memory, loop through the data to create these associations. - /// - /// The with output from the GetTopics stored procedure. - /// A of topics to be loaded. - /// - /// Specified whether the target collection value should be marked as dirty, assuming the value changes. By default, it - /// will be marked dirty if the value is new or has changed from a previous value. By setting this parameter, that - /// behavior is overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update - /// from being persisted to the data store on . - /// - private static void SetReferences(this IDataReader reader, TopicIndex topics, bool? markDirty) { + current.References.SetValue(referenceKey, referenced, markDirty); - /*------------------------------------------------------------------------------------------------------------------------ - | Identify attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var sourceTopicId = reader.GetTopicId("Source_TopicID"); - var referenceKey = reader.GetString("ReferenceKey"); - var targetTopicId = reader.GetNullableTopicId("Target_TopicID"); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify affected topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var current = topics[sourceTopicId]; - var referenced = (Topic?)null; + /*============================================================================================================================ + | METHOD: SET VERSION HISTORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds versions retrieved from an individual topic record to its associated topics. + /// + /// + /// Every time a value changes for an attribute, a new version is created, represented by the date of the change.This + /// version history is aggregated per topic to allow topic information to be rolled back to a specific date.While version + /// content is not exposed directly via the Load() method, the metadata is. + /// + /// The with output from the GetTopics stored procedure. + /// A of topics to be loaded. + private static void SetVersionHistory(this IDataReader reader, TopicIndex topics) { - // Fetch the related topic - if (targetTopicId is null) { - } - else if (topics.ContainsKey(targetTopicId.Value)) { - referenced = topics[targetTopicId.Value]; - } - else { - current.References.IsFullyLoaded = false; - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var topicId = reader.GetTopicId(); + var dateTime = reader.GetVersion(); - /*------------------------------------------------------------------------------------------------------------------------ - | Set reference on object - \-----------------------------------------------------------------------------------------------------------------------*/ - current.References.SetValue(referenceKey, referenced, markDirty); + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify topic + \-------------------------------------------------------------------------------------------------------------------------*/ + var current = topics[topicId]; + /*-------------------------------------------------------------------------------------------------------------------------- + | Set history + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!current.VersionHistory.Contains(dateTime)) { + current.VersionHistory.Add(dateTime); } - /*========================================================================================================================== - | METHOD: SET VERSION HISTORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds versions retrieved from an individual topic record to its associated topics. - /// - /// - /// Every time a value changes for an attribute, a new version is created, represented by the date of the change.This - /// version history is aggregated per topic to allow topic information to be rolled back to a specific date.While version - /// content is not exposed directly via the Load() method, the metadata is. - /// - /// The with output from the GetTopics stored procedure. - /// A of topics to be loaded. - private static void SetVersionHistory(this IDataReader reader, TopicIndex topics) { + } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicId = reader.GetTopicId(); - var dateTime = reader.GetVersion(); + /*============================================================================================================================ + | METHOD: GET STRING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a string value by column name. + /// + /// The object. + /// The name of the column to retrieve the value from. + private static string GetString(this IDataReader reader, string columnName) => + reader.GetString(reader.GetOrdinal(columnName)); - /*------------------------------------------------------------------------------------------------------------------------ - | Identify topic - \-----------------------------------------------------------------------------------------------------------------------*/ - var current = topics[topicId]; + /*============================================================================================================================ + | METHOD: GET NULLABLE STRING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a nullable string value by column name. + /// + /// The object. + /// The name of the column to retrieve the value from. + private static string? GetNullableString(this IDataReader reader, string columnName) => + reader.IsDBNull(reader.GetOrdinal(columnName)) ? null : reader.GetString(reader.GetOrdinal(columnName)); - /*------------------------------------------------------------------------------------------------------------------------ - | Set history - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!current.VersionHistory.Contains(dateTime)) { - current.VersionHistory.Add(dateTime); - } + /*============================================================================================================================ + | METHOD: GET BOOLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a boolean value by column name. + /// + /// The object. + /// The name of the column to retrieve the value from. + private static bool GetBoolean(this IDataReader reader, string columnName) => + reader.GetBoolean(reader.GetOrdinal(columnName)); - } + /*============================================================================================================================ + | METHOD: GET INTEGER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves an integer value by column name. + /// + /// The object. + /// The name of the column to retrieve the value from. + private static int GetInteger(this IDataReader reader, string columnName) => + Int32.TryParse(reader.GetValue(reader.GetOrdinal(columnName)).ToString(), out var output)? output : -1; - /*========================================================================================================================== - | METHOD: GET STRING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a string value by column name. - /// - /// The object. - /// The name of the column to retrieve the value from. - private static string GetString(this IDataReader reader, string columnName) => - reader.GetString(reader.GetOrdinal(columnName)); - - /*========================================================================================================================== - | METHOD: GET NULLABLE STRING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a nullable string value by column name. - /// - /// The object. - /// The name of the column to retrieve the value from. - private static string? GetNullableString(this IDataReader reader, string columnName) => - reader.IsDBNull(reader.GetOrdinal(columnName)) ? null : reader.GetString(reader.GetOrdinal(columnName)); - - /*========================================================================================================================== - | METHOD: GET BOOLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a boolean value by column name. - /// - /// The object. - /// The name of the column to retrieve the value from. - private static bool GetBoolean(this IDataReader reader, string columnName) => - reader.GetBoolean(reader.GetOrdinal(columnName)); - - /*========================================================================================================================== - | METHOD: GET INTEGER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves an integer value by column name. - /// - /// The object. - /// The name of the column to retrieve the value from. - private static int GetInteger(this IDataReader reader, string columnName) => - Int32.TryParse(reader.GetValue(reader.GetOrdinal(columnName)).ToString(), out var output)? output : -1; - - /*========================================================================================================================== - | METHOD: GET TOPIC ID - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a value by column name. - /// - /// The object. - /// The name of the column to retrieve the value from. - private static int GetTopicId(this IDataReader reader, string columnName = "TopicID") => - reader.GetInt32(reader.GetOrdinal(columnName)); - - /*========================================================================================================================== - | METHOD: GET NULLABLE TOPIC ID - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a value by column name, while accepting null values. - /// - /// The object. - /// The name of the column to retrieve the value from. - private static int? GetNullableTopicId(this IDataReader reader, string columnName = "TopicID") => - reader.IsDBNull(reader.GetOrdinal(columnName))? null : reader.GetInt32(reader.GetOrdinal(columnName)); - - /*========================================================================================================================== - | METHOD: GET VERSION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the version column, with precisions appropriate for setting the . - /// - /// The object. - private static DateTime GetVersion(this IDataReader reader) => - reader.GetDateTime(reader.GetOrdinal("Version")); - - } //Class -} //Namespace \ No newline at end of file + /*============================================================================================================================ + | METHOD: GET TOPIC ID + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a value by column name. + /// + /// The object. + /// The name of the column to retrieve the value from. + private static int GetTopicId(this IDataReader reader, string columnName = "TopicID") => + reader.GetInt32(reader.GetOrdinal(columnName)); + + /*============================================================================================================================ + | METHOD: GET NULLABLE TOPIC ID + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a value by column name, while accepting null values. + /// + /// The object. + /// The name of the column to retrieve the value from. + private static int? GetNullableTopicId(this IDataReader reader, string columnName = "TopicID") => + reader.IsDBNull(reader.GetOrdinal(columnName))? null : reader.GetInt32(reader.GetOrdinal(columnName)); + + /*============================================================================================================================ + | METHOD: GET VERSION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves the version column, with precisions appropriate for setting the . + /// + /// The object. + private static DateTime GetVersion(this IDataReader reader) => + reader.GetDateTime(reader.GetOrdinal("Version")); + +} //Class \ No newline at end of file diff --git a/OnTopic.Data.Sql/SqlTopicRepository.cs b/OnTopic.Data.Sql/SqlTopicRepository.cs index 7d61f6cc..ba5c00a1 100644 --- a/OnTopic.Data.Sql/SqlTopicRepository.cs +++ b/OnTopic.Data.Sql/SqlTopicRepository.cs @@ -10,721 +10,730 @@ using OnTopic.Querying; using OnTopic.Repositories; -namespace OnTopic.Data.Sql { +namespace OnTopic.Data.Sql; + +/*============================================================================================================================== +| CLASS: SQL TOPIC DATA REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides data access to topics stored in Microsoft SQL Server. +/// +/// +/// Concrete implementation of the class. +/// +public class SqlTopicRepository : TopicRepository, ITopicRepository { /*============================================================================================================================ - | CLASS: SQL TOPIC DATA REPOSITORY + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly string _connectionString; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides data access to topics stored in Microsoft SQL Server. + /// Instantiates a new instance of the SqlTopicRepository with a dependency on a connection string to provide necessary + /// access to a SQL database. /// - /// - /// Concrete implementation of the class. - /// - public class SqlTopicRepository : TopicRepository, ITopicRepository { + /// A connection string to a SQL server that contains the Topics database. + /// A new instance of the SqlTopicRepository. + public SqlTopicRepository(string connectionString) : base() { - /*========================================================================================================================== - | PRIVATE VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly string _connectionString; + Contract.Requires(!String.IsNullOrWhiteSpace(connectionString), nameof(connectionString)); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Set private fields \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the SqlTopicRepository with a dependency on a connection string to provide necessary - /// access to a SQL database. - /// - /// A connection string to a SQL server that contains the Topics database. - /// A new instance of the SqlTopicRepository. - public SqlTopicRepository(string connectionString) : base() { + _connectionString = connectionString; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(!String.IsNullOrWhiteSpace(connectionString), nameof(connectionString)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Set private fields - \-----------------------------------------------------------------------------------------------------------------------*/ - _connectionString = connectionString; - - } + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { - /*========================================================================================================================== - | METHOD: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(uniqueKey, nameof(uniqueKey)); - Contract.Requires(uniqueKey.Length > 0, nameof(uniqueKey)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish database connection - \-----------------------------------------------------------------------------------------------------------------------*/ - using var connection = new SqlConnection(_connectionString); - using var command = new SqlCommand("GetTopicID", connection); - - var topicId = -1; - - command.CommandType = CommandType.StoredProcedure; - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - command.AddParameter("UniqueKey", uniqueKey); - command.AddOutputParameter(); + Contract.Requires(uniqueKey, nameof(uniqueKey)); + Contract.Requires(uniqueKey.Length > 0, nameof(uniqueKey)); - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish database connection + \-------------------------------------------------------------------------------------------------------------------------*/ + using var connection = new SqlConnection(_connectionString); + using var command = new SqlCommand("GetTopicID", connection); - connection.Open(); - command.ExecuteNonQuery(); + var topicId = -1; - topicId = command.GetReturnCode(); + command.CommandType = CommandType.StoredProcedure; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + command.AddParameter("UniqueKey", uniqueKey); + command.AddOutputParameter(); - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException($"Topic(s) failed to load: '{exception.Message}'", exception); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query + \-------------------------------------------------------------------------------------------------------------------------*/ + try { - /*------------------------------------------------------------------------------------------------------------------------ - | Validate results - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topicId < 0) { - throw new TopicNotFoundException(uniqueKey); - } + connection.Open(); + command.ExecuteNonQuery(); - /*------------------------------------------------------------------------------------------------------------------------ - | Return topic - \-----------------------------------------------------------------------------------------------------------------------*/ - return Load(topicId, referenceTopic, isRecursive); + topicId = command.GetReturnCode(); } - /// - public override Topic Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish database connection - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = (Topic?)null; - - using var connection = new SqlConnection(_connectionString); - using var command = new SqlCommand("GetTopics", connection) { - CommandType = CommandType.StoredProcedure, - CommandTimeout = 120 - }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException($"Topic(s) failed to load: '{exception.Message}'", exception); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - command.AddParameter("TopicID", topicId); - command.AddParameter("DeepLoad", isRecursive); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate results + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topicId < 0) { + throw new TopicNotFoundException(uniqueKey); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { - connection.Open(); - using var reader = command.ExecuteReader(); - topic = reader.LoadTopicGraph(referenceTopic, false); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return topic + \-------------------------------------------------------------------------------------------------------------------------*/ + return Load(topicId, referenceTopic, isRecursive); - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException($"Topics failed to load: '{exception.Message}'", exception); - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate results - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) { - if (topicId == -1) { - topic = TopicFactory.Create("Root", "Container"); - } - else { - throw new TopicNotFoundException(topicId); - } - } + /// + public override Topic Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { - /*------------------------------------------------------------------------------------------------------------------------ - | Establish content type cache - >------------------------------------------------------------------------------------------------------------------------- - | If this load represents the entire topic graph, then relay the content type configuration to the TopicRepositoryBase in - | order to either update or establish the content type cache. Not only does this prevent the need for a separate redundant - | call later but, even more importantly, it helps ensure the same object references are maintained so that any updates to - | subsequently cached content types are available. - \-----------------------------------------------------------------------------------------------------------------------*/ - base.SetContentTypeDescriptors(topic); + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish database connection + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = (Topic?)null; - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - OnTopicLoaded(new(topic, isRecursive)); + using var connection = new SqlConnection(_connectionString); + using var command = new SqlCommand("GetTopics", connection) { + CommandType = CommandType.StoredProcedure, + CommandTimeout = 120 + }; - /*------------------------------------------------------------------------------------------------------------------------ - | Return objects - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic; + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + command.AddParameter("TopicID", topicId); + command.AddParameter("DeepLoad", isRecursive); + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query + \-------------------------------------------------------------------------------------------------------------------------*/ + try { + connection.Open(); + using var reader = command.ExecuteReader(); + topic = reader.LoadTopicGraph(referenceTopic, false); } - /// - public override Topic Load(int topicId, DateTime version, Topic? referenceTopic = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(version.Date < DateTime.Now, "The version requested must be a valid historical date."); - Contract.Requires( - version.Date >= new DateTime(2014, 12, 9), - "The version is expected to have been created since version support was introduced into the topic library." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Clear associations - >------------------------------------------------------------------------------------------------------------------------- - | Because we don't (currently) track version as part of the .NET data model for relationships or topic references, there's - | no easy way to determine if an association should be deleted when doing a rollback. As such, existing associations - | should be deleted, assuming a `referenceTopic` is passed, and it contains the `topicId`. - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = (Topic?)null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException($"Topics failed to load: '{exception.Message}'", exception); + } - if (referenceTopic?.Id == topicId) { - topic = referenceTopic; - } - else if (referenceTopic is not null) { - topic = referenceTopic.GetRootTopic().FindFirst(t => t.Id == topicId); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate results + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic is null) { + if (topicId == -1) { + topic = TopicFactory.Create("Root", "Container"); } - - if (topic is not null) { - foreach (var relationship in topic.Relationships) { - topic.Relationships.Clear(relationship.Key); - } - topic.References.Clear(); + else { + throw new TopicNotFoundException(topicId); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish database connection - \-----------------------------------------------------------------------------------------------------------------------*/ - using var connection = new SqlConnection(_connectionString); - using var command = new SqlCommand("GetTopicVersion", connection) { - CommandType = CommandType.StoredProcedure, - CommandTimeout = 120 - }; - - command.CommandType = CommandType.StoredProcedure; + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish content type cache + >------------------------------------------------------------------------------------------------------------------------- + | If this load represents the entire topic graph, then relay the content type configuration to the TopicRepositoryBase in + | order to either update or establish the content type cache. Not only does this prevent the need for a separate redundant + | call later but, even more importantly, it helps ensure the same object references are maintained so that any updates to + | subsequently cached content types are available. + \-------------------------------------------------------------------------------------------------------------------------*/ + base.SetContentTypeDescriptors(topic); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - command.AddParameter("TopicID", topicId); - command.AddParameter("Version", version); + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + OnTopicLoaded(new(topic, isRecursive)); - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { - connection.Open(); - using var reader = command.ExecuteReader(); - topic = reader.LoadTopicGraph(referenceTopic, includeExternalReferences: referenceTopic is not null); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return objects + \-------------------------------------------------------------------------------------------------------------------------*/ + return topic; - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - if (topic is not null) { - topic.Relationships.IsFullyLoaded = false; - topic.References.IsFullyLoaded = false; - } - throw new TopicRepositoryException($"Topics failed to load: '{exception.Message}'", exception); - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate result - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) { - throw new TopicNotFoundException(topicId); - } + /// + public override Topic Load(int topicId, DateTime version, Topic? referenceTopic = null) { - /*------------------------------------------------------------------------------------------------------------------------ - | Delete orphaned attributes - >------------------------------------------------------------------------------------------------------------------------- - | If a referenceTopic is passed, and it contains the `topicId`, then that instance will be updated with the previous - | version. In that case, however, any attributes which were first introduced after that version won't be overwritten. - | That's because there isn't a previous value associated with that key to overwrite the current value. In those cases, - | those attributes must be manually removed. - \-----------------------------------------------------------------------------------------------------------------------*/ - var orphanedAttributes = topic.Attributes.Where(a => a.LastModified > version).ToList(); - foreach (var attribute in orphanedAttributes) { - topic.Attributes.Remove(attribute.Key); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Normalize parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + version = NormalizeToUtc(version); - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - OnTopicLoaded(new(topic, false, version)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(version.Date < DateTime.UtcNow, "The version requested must be a valid historical date."); + Contract.Requires( + version.Date >= new DateTime(2014, 12, 9), + "The version is expected to have been created since version support was introduced into the topic library." + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Clear associations + >------------------------------------------------------------------------------------------------------------------------- + | Because we don't (currently) track version as part of the .NET data model for relationships or topic references, there's + | no easy way to determine if an association should be deleted when doing a rollback. As such, existing associations + | should be deleted, assuming a `referenceTopic` is passed, and it contains the `topicId`. + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = (Topic?)null; - /*------------------------------------------------------------------------------------------------------------------------ - | Return objects - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic; + if (referenceTopic?.Id == topicId) { + topic = referenceTopic; + } + else if (referenceTopic is not null) { + topic = referenceTopic.GetRootTopic().FindFirst(t => t.Id == topicId); + } + if (topic is not null) { + foreach (var relationship in topic.Relationships) { + topic.Relationships.Clear(relationship.Key); + } + topic.References.Clear(); } - /*========================================================================================================================== - | METHOD: REFRESH + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish database connection \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Refresh(Topic referenceTopic, DateTime since) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(referenceTopic, "A referenceTopic from the topic graph must be provided."); - Contract.Requires( - since.Date >= DateTime.Now.AddHours(-24), - "The since date is expected to be within the last twenty four hours." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish database connection - \-----------------------------------------------------------------------------------------------------------------------*/ - using var connection = new SqlConnection(_connectionString); - using var command = new SqlCommand("GetTopicUpdates", connection) { - CommandType = CommandType.StoredProcedure, - CommandTimeout = 120 - }; + using var connection = new SqlConnection(_connectionString); + using var command = new SqlCommand("GetTopicVersion", connection) { + CommandType = CommandType.StoredProcedure, + CommandTimeout = 120 + }; - command.CommandType = CommandType.StoredProcedure; + command.CommandType = CommandType.StoredProcedure; - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - command.AddParameter("Since", since); + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + command.AddParameter("TopicID", topicId); + command.AddParameter("Version", version); - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { - connection.Open(); - using var reader = command.ExecuteReader(); - reader.LoadTopicGraph(referenceTopic.GetRootTopic(), false); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query + \-------------------------------------------------------------------------------------------------------------------------*/ + try { + connection.Open(); + using var reader = command.ExecuteReader(); + topic = reader.LoadTopicGraph(referenceTopic, includeExternalReferences: referenceTopic is not null); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException($"Topics failed to update: '{exception.Message}'", exception); + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + if (topic is not null) { + topic.Relationships.IsFullyLoaded = false; + topic.References.IsFullyLoaded = false; } - + throw new TopicRepositoryException($"Topics failed to load: '{exception.Message}'", exception); } - /*========================================================================================================================== - | METHOD: SAVE + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate result \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override sealed void SaveTopic( - [NotNull]Topic topic, - DateTime version, - bool persistRelationships - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Define variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var isTopicDirty = topic.IsDirty(); - var areRelationshipsDirty = topic.Relationships.IsDirty(); - var areReferencesDirty = topic.References.IsDirty(); - var areAttributesDirty = topic.Attributes.IsDirty(true); - var extendedAttributeList = GetAttributes(topic, isExtendedAttribute: true); - var indexedAttributeList = GetAttributes( - topic : topic, - isExtendedAttribute : false, - isDirty : true, - excludeLastModified : !areAttributesDirty - ); + if (topic is null) { + throw new TopicNotFoundException(topicId); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Detect whether anything has changed - >------------------------------------------------------------------------------------------------------------------------- - | If no associations have changed, and no attributes values have changed, and there aren't any mismatched attributes in - | their respective lists, then there isn't anything new to persist to the database, and thus no benefit to executing the - | current command. A more aggressive version of this would wrap much of the below logic in this, but this is just meant - | as a quick fix to reduce the overhead of recursive saves. - \-----------------------------------------------------------------------------------------------------------------------*/ - areAttributesDirty = - areAttributesDirty || - indexedAttributeList.Any(a => a.IsExtendedAttribute == true) || - extendedAttributeList.Any(a => a.IsExtendedAttribute == false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Delete orphaned attributes + >------------------------------------------------------------------------------------------------------------------------- + | If a referenceTopic is passed, and it contains the `topicId`, then that instance will be updated with the previous + | version. In that case, however, any attributes which were first introduced after that version won't be overwritten. + | That's because there isn't a previous value associated with that key to overwrite the current value. In those cases, + | those attributes must be manually removed. + \-------------------------------------------------------------------------------------------------------------------------*/ + var orphanedAttributes = topic.Attributes.Where(a => a.LastModified > version).ToList(); + foreach (var attribute in orphanedAttributes) { + topic.Attributes.Remove(attribute.Key); + } - var isDirty = - isTopicDirty || - areRelationshipsDirty || - areReferencesDirty || - areAttributesDirty; + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + OnTopicLoaded(new(topic, false, version)); - /*------------------------------------------------------------------------------------------------------------------------ - | Bypass is not dirty - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!isDirty) { - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return objects + \-------------------------------------------------------------------------------------------------------------------------*/ + return topic; - /*------------------------------------------------------------------------------------------------------------------------ - | Add indexed attributes that are dirty - >------------------------------------------------------------------------------------------------------------------------- - | Loop through the content type's supported attributes and add attribute to null attributes if topic does not contain it. - \-----------------------------------------------------------------------------------------------------------------------*/ - using var attributeValues = new AttributeValuesDataTable(); + } - if (areAttributesDirty) { + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Refresh(Topic referenceTopic, DateTime since) { - foreach (var attributeValue in indexedAttributeList) { - attributeValues.AddRow(attributeValue.Key, attributeValue.Value); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Normalize parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + since = NormalizeToUtc(since); - foreach (var attribute in GetUnmatchedAttributes(topic)) { - attributeValues.AddRow(attribute.Key); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(referenceTopic, "A referenceTopic from the topic graph must be provided."); + Contract.Requires( + since.Date >= DateTime.UtcNow.AddHours(-24), + "The since date is expected to be within the last twenty four hours." + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish database connection + \-------------------------------------------------------------------------------------------------------------------------*/ + using var connection = new SqlConnection(_connectionString); + using var command = new SqlCommand("GetTopicUpdates", connection) { + CommandType = CommandType.StoredProcedure, + CommandTimeout = 120 + }; - } + command.CommandType = CommandType.StoredProcedure; - /*------------------------------------------------------------------------------------------------------------------------ - | Add extended attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var extendedAttributes = new StringBuilder(); - - if (areAttributesDirty) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + command.AddParameter("Since", since); - extendedAttributes.Append(""); + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query + \-------------------------------------------------------------------------------------------------------------------------*/ + try { + connection.Open(); + using var reader = command.ExecuteReader(); + reader.LoadTopicGraph(referenceTopic.GetRootTopic(), false); + } - foreach (var attributeValue in extendedAttributeList) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException($"Topics failed to update: '{exception.Message}'", exception); + } - extendedAttributes.Append( - "" - ); + } - //###NOTE JJC20200502: By treating extended attributes as unmatched, we ensure that any indexed attributes with the same - //value are overwritten with an empty attribute. This is useful for cases where an indexed attribute is moved to an - //extended attribute, as it persists that version history, while removing ambiguity over which record is authoritative. - //This is also useful for supporting arbitrary attribute values, since they may be moved from indexed to extended - //attributes if their length exceeds 255. - attributeValues.AddRow(attributeValue.Key); + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override sealed void SaveTopic( + [NotNull]Topic topic, + DateTime version, + bool persistRelationships + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Define variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var isTopicDirty = topic.IsDirty(); + var areRelationshipsDirty = topic.Relationships.IsDirty(); + var areReferencesDirty = topic.References.IsDirty(); + var areAttributesDirty = topic.Attributes.IsDirty(true); + var extendedAttributeList = GetAttributes(topic, isExtendedAttribute: true).ToList(); + var indexedAttributeList = GetAttributes( + topic : topic, + isExtendedAttribute : false, + isDirty : true, + excludeLastModified : !areAttributesDirty + ).ToList(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Detect whether anything has changed + >------------------------------------------------------------------------------------------------------------------------- + | If no associations have changed, and no attributes values have changed, and there aren't any mismatched attributes in + | their respective lists, then there isn't anything new to persist to the database, and thus no benefit to executing the + | current command. A more aggressive version of this would wrap much of the below logic in this, but this is just meant + | as a quick fix to reduce the overhead of recursive saves. + \-------------------------------------------------------------------------------------------------------------------------*/ + areAttributesDirty = + areAttributesDirty || + indexedAttributeList.Any(a => a.IsExtendedAttribute == true) || + extendedAttributeList.Any(a => a.IsExtendedAttribute == false); + + var isDirty = + isTopicDirty || + areRelationshipsDirty || + areReferencesDirty || + areAttributesDirty; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Bypass is not dirty + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!isDirty) { + return; + } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Add indexed attributes that are dirty + >------------------------------------------------------------------------------------------------------------------------- + | Loop through the content type's supported attributes and add attribute to null attributes if topic does not contain it. + \-------------------------------------------------------------------------------------------------------------------------*/ + using var attributeValues = new AttributeValuesDataTable(); - extendedAttributes.Append(""); + if (areAttributesDirty) { + foreach (var attributeValue in indexedAttributeList) { + attributeValues.AddRow(attributeValue.Key, attributeValue.Value); } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish database connection - \-----------------------------------------------------------------------------------------------------------------------*/ - using var connection = new SqlConnection(_connectionString); - var procedureName = topic.IsNew? "CreateTopic" : "UpdateTopic"; + foreach (var attribute in GetUnmatchedAttributes(topic)) { + attributeValues.AddRow(attribute.Key); + } - connection.Open(); + } - using var command = new SqlCommand(procedureName, connection) { - CommandType = CommandType.StoredProcedure - }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Add extended attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var extendedAttributes = new StringBuilder(); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!topic.IsNew) { - command.AddParameter("TopicID", topic.Id); - command.AddParameter("DeleteUnmatched", false); - } - else if (topic.Parent is not null) { - command.AddParameter("ParentID", topic.Parent.Id); - } - if (isTopicDirty || topic.IsNew) { - command.AddParameter("Key", topic.Key); - command.AddParameter("ContentType", topic.ContentType); - } - command.AddParameter("Version", version); - if (areAttributesDirty) { - command.AddParameter("Attributes", attributeValues); - command.AddParameter("ExtendedAttributes", extendedAttributes); - } - command.AddOutputParameter(); + if (areAttributesDirty) { - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { + extendedAttributes.Append(""); - if (topic.IsNew || isTopicDirty || areAttributesDirty) { - command.ExecuteNonQuery(); - topic.Id = command.GetReturnCode(); - } + foreach (var attributeValue in extendedAttributeList) { - Contract.Assume( - !topic.IsNew, - "The call to the CreateTopic stored procedure did not return the expected 'Id' parameter." + extendedAttributes.Append( + "" ); - if (persistRelationships && areRelationshipsDirty) { - PersistRelationships(topic, version, connection); - } - - if (persistRelationships && areReferencesDirty) { - PersistReferences(topic, version, connection); - } - - } + //###NOTE JJC20200502: By treating extended attributes as unmatched, we ensure that any indexed attributes with the same + //value are overwritten with an empty attribute. This is useful for cases where an indexed attribute is moved to an + //extended attribute, as it persists that version history, while removing ambiguity over which record is authoritative. + //This is also useful for supporting arbitrary attribute values, since they may be moved from indexed to extended + //attributes if their length exceeds 255. + attributeValues.AddRow(attributeValue.Key); - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException( - $"Failed to save Topic '{topic.Key}' ({topic.Id}) via '{_connectionString}': '{exception.Message}'", - exception - ); } - /*------------------------------------------------------------------------------------------------------------------------ - | Close connection - \-----------------------------------------------------------------------------------------------------------------------*/ - finally { - connection.Close(); - } + extendedAttributes.Append(""); } - /*========================================================================================================================== - | METHOD: MOVE TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish database connection \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override sealed void MoveTopic(Topic topic, Topic target, Topic? sibling) { + using var connection = new SqlConnection(_connectionString); + var procedureName = topic.IsNew? "CreateTopic" : "UpdateTopic"; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires(target, nameof(target)); + connection.Open(); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish database connection - \-----------------------------------------------------------------------------------------------------------------------*/ - using var connection = new SqlConnection(_connectionString); - using var command = new SqlCommand("MoveTopic", connection) { - CommandType = CommandType.StoredProcedure - }; + using var command = new SqlCommand(procedureName, connection) { + CommandType = CommandType.StoredProcedure + }; - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!topic.IsNew) { command.AddParameter("TopicID", topic.Id); - command.AddParameter("ParentID", target.Id); + command.AddParameter("DeleteUnmatched", false); + } + else if (topic.Parent is not null) { + command.AddParameter("ParentID", topic.Parent.Id); + } + if (isTopicDirty || topic.IsNew) { + command.AddParameter("Key", topic.Key); + command.AddParameter("ContentType", topic.ContentType); + } + command.AddParameter("Version", version); + if (areAttributesDirty) { + command.AddParameter("Attributes", attributeValues); + command.AddParameter("ExtendedAttributes", extendedAttributes); + } + command.AddOutputParameter(); - // Append sibling ID if set - if (sibling is not null) { - command.AddParameter("SiblingID", sibling.Id); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query + \-------------------------------------------------------------------------------------------------------------------------*/ + try { - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { - connection.Open(); + if (topic.IsNew || isTopicDirty || areAttributesDirty) { command.ExecuteNonQuery(); + topic.Id = command.GetReturnCode(); } - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException( - $"Failed to move Topic '{topic.Key}' ({topic.Id}) to '{target.Key}' ({target.Id}): '{exception.Message}'", - exception - ); + Contract.Assume( + !topic.IsNew, + "The call to the CreateTopic stored procedure did not return the expected 'Id' parameter." + ); + + if (persistRelationships && areRelationshipsDirty) { + PersistRelationships(topic, version, connection); + } + + if (persistRelationships && areReferencesDirty) { + PersistReferences(topic, version, connection); } } - /*========================================================================================================================== - | METHOD: DELETE TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override sealed void DeleteTopic(Topic topic) { + catch (SqlException exception) { + throw new TopicRepositoryException( + $"Failed to save Topic '{topic.Key}' ({topic.Id}) via '{_connectionString}': '{exception.Message}'", + exception + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Close connection + \-------------------------------------------------------------------------------------------------------------------------*/ + finally { + connection.Close(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Delete from database - \-----------------------------------------------------------------------------------------------------------------------*/ - using var connection = new SqlConnection(_connectionString); - using var command = new SqlCommand("DeleteTopic", connection) { - CommandType = CommandType.StoredProcedure - }; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish query parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - command.AddParameter("TopicID", topic.Id); + /*============================================================================================================================ + | METHOD: MOVE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override sealed void MoveTopic(Topic topic, Topic target, Topic? sibling) { - /*------------------------------------------------------------------------------------------------------------------------ - | Process database query - \-----------------------------------------------------------------------------------------------------------------------*/ - try { - connection.Open(); - command.ExecuteNonQuery(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); + Contract.Requires(target, nameof(target)); - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException( - $"Failed to delete Topic '{topic.Key}' ({topic.Id}): '{exception.Message}'", - exception - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish database connection + \-------------------------------------------------------------------------------------------------------------------------*/ + using var connection = new SqlConnection(_connectionString); + using var command = new SqlCommand("MoveTopic", connection) { + CommandType = CommandType.StoredProcedure + }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + command.AddParameter("TopicID", topic.Id); + command.AddParameter("ParentID", target.Id); + + // Append sibling ID if set + if (sibling is not null) { + command.AddParameter("SiblingID", sibling.Id); } - /*========================================================================================================================== - | METHOD: PERSIST RELATIONSHIPS + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Internal method that saves topic relationships to the n:n mapping table in SQL. - /// - /// The topic object whose relationships should be persisted. - /// The version that should be associated with the updated value. - /// The SQL connection. - private static void PersistRelationships(Topic topic, DateTime version, SqlConnection connection) { + try { + connection.Open(); + command.ExecuteNonQuery(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return blank if the topic has no relations. - \-----------------------------------------------------------------------------------------------------------------------*/ - // return if the topic has no relations - if (!topic.Relationships.Keys.Any()) { - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException( + $"Failed to move Topic '{topic.Key}' ({topic.Id}) to '{target.Key}' ({target.Id}): '{exception.Message}'", + exception + ); + } - try { + } - /*---------------------------------------------------------------------------------------------------------------------- - | Iterate through each scope and persist to SQL - \---------------------------------------------------------------------------------------------------------------------*/ - foreach (var key in topic.Relationships.Keys) { + /*============================================================================================================================ + | METHOD: DELETE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override sealed void DeleteTopic(Topic topic) { - using var targetIds = new TopicListDataTable(); - using var command = new SqlCommand("UpdateRelationships", connection) { - CommandType = CommandType.StoredProcedure - }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); - foreach (var targetTopic in topic.Relationships.GetValues(key)) { - if (!targetTopic.IsNew) { - targetIds.AddRow(targetTopic.Id); - } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Delete from database + \-------------------------------------------------------------------------------------------------------------------------*/ + using var connection = new SqlConnection(_connectionString); + using var command = new SqlCommand("DeleteTopic", connection) { + CommandType = CommandType.StoredProcedure + }; - // Add Parameters - command.AddParameter("TopicID", topic.Id.ToString(CultureInfo.InvariantCulture)); - command.AddParameter("RelationshipKey", key); - command.AddParameter("RelatedTopics", targetIds); - command.AddParameter("Version", version); - command.AddParameter("DeleteUnmatched", topic.Relationships.IsFullyLoaded); + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish query parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + command.AddParameter("TopicID", topic.Id); - command.ExecuteNonQuery(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Process database query + \-------------------------------------------------------------------------------------------------------------------------*/ + try { + connection.Open(); + command.ExecuteNonQuery(); + } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException( + $"Failed to delete Topic '{topic.Key}' ({topic.Id}): '{exception.Message}'", + exception + ); + } - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException( - $"Failed to persist relationships for Topic '{topic.Key}' ({topic.Id}): '{exception.Message}'", - exception - ); - } + /*============================================================================================================================ + | METHOD: PERSIST RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Internal method that saves topic relationships to the n:n mapping table in SQL. + /// + /// The topic object whose relationships should be persisted. + /// The version that should be associated with the updated value. + /// The SQL connection. + private static void PersistRelationships(Topic topic, DateTime version, SqlConnection connection) { - /*------------------------------------------------------------------------------------------------------------------------ - | Return - \-----------------------------------------------------------------------------------------------------------------------*/ + /*-------------------------------------------------------------------------------------------------------------------------- + | Return blank if the topic has no relations. + \-------------------------------------------------------------------------------------------------------------------------*/ + // return if the topic has no relations + if (topic.Relationships.Keys.Count == 0) { return; - } - /*========================================================================================================================== - | METHOD: PERSIST REFERENCES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Internal method that saves topic references to the 1:n mapping table in SQL. - /// - /// The topic object whose references should be persisted. - /// The version that should be associated with the updated value. - /// The SQL connection. - private static void PersistReferences(Topic topic, DateTime version, SqlConnection connection) { + try { /*------------------------------------------------------------------------------------------------------------------------ - | Persist relations to database + | Iterate through each scope and persist to SQL \-----------------------------------------------------------------------------------------------------------------------*/ - try { + foreach (var key in topic.Relationships.Keys) { - using var references = new TopicReferencesDataTable(); - using var command = new SqlCommand("UpdateReferences", connection) { + using var targetIds = new TopicListDataTable(); + using var command = new SqlCommand("UpdateRelationships", connection) { CommandType = CommandType.StoredProcedure }; - foreach (var relatedTopic in topic.References) { - if (!relatedTopic.Value?.IsNew?? false) { - references.AddRow(relatedTopic.Key, relatedTopic.Value!.Id); + foreach (var targetTopic in topic.Relationships.GetValues(key)) { + if (!targetTopic.IsNew) { + targetIds.AddRow(targetTopic.Id); } } // Add Parameters command.AddParameter("TopicID", topic.Id.ToString(CultureInfo.InvariantCulture)); - command.AddParameter("ReferencedTopics", references); + command.AddParameter("RelationshipKey", key); + command.AddParameter("RelatedTopics", targetIds); command.AddParameter("Version", version); - command.AddParameter("DeleteUnmatched", topic.References.IsFullyLoaded); + command.AddParameter("DeleteUnmatched", topic.Relationships.IsFullyLoaded); command.ExecuteNonQuery(); } - /*------------------------------------------------------------------------------------------------------------------------ - | Catch exception - \-----------------------------------------------------------------------------------------------------------------------*/ - catch (SqlException exception) { - throw new TopicRepositoryException( - $"Failed to persist references for Topic '{topic.Key}' ({topic.Id}): '{exception.Message}'", - exception - ); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException( + $"Failed to persist relationships for Topic '{topic.Key}' ({topic.Id}): '{exception.Message}'", + exception + ); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return + \-------------------------------------------------------------------------------------------------------------------------*/ + return; + + } + + /*============================================================================================================================ + | METHOD: PERSIST REFERENCES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Internal method that saves topic references to the 1:n mapping table in SQL. + /// + /// The topic object whose references should be persisted. + /// The version that should be associated with the updated value. + /// The SQL connection. + private static void PersistReferences(Topic topic, DateTime version, SqlConnection connection) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Persist relations to database + \-------------------------------------------------------------------------------------------------------------------------*/ + try { + + using var references = new TopicReferencesDataTable(); + using var command = new SqlCommand("UpdateReferences", connection) { + CommandType = CommandType.StoredProcedure + }; + + foreach (var relatedTopic in topic.References) { + if (!relatedTopic.Value?.IsNew?? false) { + references.AddRow(relatedTopic.Key, relatedTopic.Value!.Id); + } } - /*------------------------------------------------------------------------------------------------------------------------ - | Return - \-----------------------------------------------------------------------------------------------------------------------*/ - return; + // Add Parameters + command.AddParameter("TopicID", topic.Id.ToString(CultureInfo.InvariantCulture)); + command.AddParameter("ReferencedTopics", references); + command.AddParameter("Version", version); + command.AddParameter("DeleteUnmatched", topic.References.IsFullyLoaded); + + command.ExecuteNonQuery(); + + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Catch exception + \-------------------------------------------------------------------------------------------------------------------------*/ + catch (SqlException exception) { + throw new TopicRepositoryException( + $"Failed to persist references for Topic '{topic.Key}' ({topic.Id}): '{exception.Message}'", + exception + ); } - } //Class -} //Namespace \ No newline at end of file + /*-------------------------------------------------------------------------------------------------------------------------- + | Return + \-------------------------------------------------------------------------------------------------------------------------*/ + return; + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/DummyTopicMappingService.cs b/OnTopic.TestDoubles/DummyTopicMappingService.cs index f93b530a..2fdd0468 100644 --- a/OnTopic.TestDoubles/DummyTopicMappingService.cs +++ b/OnTopic.TestDoubles/DummyTopicMappingService.cs @@ -6,52 +6,51 @@ using OnTopic.Mapping; using OnTopic.Mapping.Annotations; -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously +#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously -namespace OnTopic.TestDoubles { +namespace OnTopic.TestDoubles; + +/*============================================================================================================================== +| DUMMY: TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The interface provides an abstraction for mapping instances to +/// Data Transfer Objects, such as View Models. +/// +[ExcludeFromCodeCoverage] +public class DummyTopicMappingService : ITopicMappingService { /*============================================================================================================================ - | DUMMY: TOPIC MAPPING SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The interface provides an abstraction for mapping instances to - /// Data Transfer Objects, such as View Models. + /// Establishes a new instance of a with required dependencies. /// - [ExcludeFromCodeCoverage] - public class DummyTopicMappingService : ITopicMappingService { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a with required dependencies. - /// - public DummyTopicMappingService() { - } - - /*========================================================================================================================== - | METHOD: MAP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [return: NotNullIfNotNull(nameof(topic))] - public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) - => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: MAP (T) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class - => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: MAP (OBJECTS) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) - => throw new NotImplementedException(); - - } //Class -} //Namespace - -#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously \ No newline at end of file + public DummyTopicMappingService() { + } + + /*============================================================================================================================ + | METHOD: MAP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [return: NotNullIfNotNull(nameof(topic))] + public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) + => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: MAP (T) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class + => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: MAP (OBJECTS) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) + => throw new NotImplementedException(); + +} //Class + +#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously \ No newline at end of file diff --git a/OnTopic.TestDoubles/DummyTopicRepository.cs b/OnTopic.TestDoubles/DummyTopicRepository.cs index bee868cc..f683903e 100644 --- a/OnTopic.TestDoubles/DummyTopicRepository.cs +++ b/OnTopic.TestDoubles/DummyTopicRepository.cs @@ -5,77 +5,76 @@ \=============================================================================================================================*/ using OnTopic.Repositories; -namespace OnTopic.TestDoubles { +namespace OnTopic.TestDoubles; + +/*============================================================================================================================== +| DUMMY: TOPIC DATA REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a basic, non-functional version of a which satisfies the interface requirements, +/// but is not intended to be called. +/// +[ExcludeFromCodeCoverage] +public class DummyTopicRepository : ObservableTopicRepository { /*============================================================================================================================ - | DUMMY: TOPIC DATA REPOSITORY + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a basic, non-functional version of a which satisfies the interface requirements, - /// but is not intended to be called. + /// Instantiates a new instance of the . /// - [ExcludeFromCodeCoverage] - public class DummyTopicRepository : ObservableTopicRepository { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public DummyTopicRepository() : base() { } + /// A new instance of the . + public DummyTopicRepository() : base() { } - /*========================================================================================================================== - | METHOD: GET CONTENT TYPE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override ContentTypeDescriptorCollection GetContentTypeDescriptors() => new(); + /*============================================================================================================================ + | METHOD: GET CONTENT TYPE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override ContentTypeDescriptorCollection GetContentTypeDescriptors() => new(); - /*========================================================================================================================== - | METHOD: LOAD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) => null; + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) => null; - /// - public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) => null; + /// + public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) => null; - /// - public override Topic? Load(Topic? topic, DateTime version) => throw new NotImplementedException(); + /// + public override Topic? Load(Topic? topic, DateTime version) => throw new NotImplementedException(); - /// - public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) => throw new NotImplementedException(); + /// + public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: ROLLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Rollback(Topic topic, DateTime version) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: ROLLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Rollback(Topic topic, DateTime version) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: REFRESH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Refresh(Topic referenceTopic, DateTime since) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Refresh(Topic referenceTopic, DateTime since) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: SAVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Save(Topic topic, bool isRecursive = false) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Save(Topic topic, bool isRecursive = false) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Move(Topic topic, Topic target, Topic? sibling = null) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Move(Topic topic, Topic target, Topic? sibling = null) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: DELETE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Delete(Topic topic, bool isRecursive = false) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Delete(Topic topic, bool isRecursive = false) => throw new NotImplementedException(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/Metadata/BooleanAttributeDescriptor.cs b/OnTopic.TestDoubles/Metadata/BooleanAttributeDescriptor.cs index 2c43fcb9..dd414dfd 100644 --- a/OnTopic.TestDoubles/Metadata/BooleanAttributeDescriptor.cs +++ b/OnTopic.TestDoubles/Metadata/BooleanAttributeDescriptor.cs @@ -4,38 +4,37 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.TestDoubles.Metadata { +namespace OnTopic.TestDoubles.Metadata; + +/*============================================================================================================================== +| CLASS: BOOLEAN (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents metadata for describing an boolean attribute type, including information on how it will be presented and +/// validated in the editor. +/// +/// +/// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the +/// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. +/// +[ExcludeFromCodeCoverage] +public class BooleanAttributeDescriptor : AttributeDescriptor { /*============================================================================================================================ - | CLASS: BOOLEAN (ATTRIBUTE DESCRIPTOR) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents metadata for describing an boolean attribute type, including information on how it will be presented and - /// validated in the editor. - /// - /// - /// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the - /// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. - /// - [ExcludeFromCodeCoverage] - public class BooleanAttributeDescriptor : AttributeDescriptor { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public BooleanAttributeDescriptor( - string key, - string contentType, - Topic parent, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - } + /// + public BooleanAttributeDescriptor( + string key, + string contentType, + Topic parent, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/Metadata/NestedTopicListAttributeDescriptor.cs b/OnTopic.TestDoubles/Metadata/NestedTopicListAttributeDescriptor.cs index d7c295a8..46185fd9 100644 --- a/OnTopic.TestDoubles/Metadata/NestedTopicListAttributeDescriptor.cs +++ b/OnTopic.TestDoubles/Metadata/NestedTopicListAttributeDescriptor.cs @@ -4,44 +4,43 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.TestDoubles.Metadata { +namespace OnTopic.TestDoubles.Metadata; + +/*============================================================================================================================== +| CLASS: NESTED TOPIC LIST (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents metadata for describing a nested topic list attribute type, including information on how it will be presented +/// and validated in the editor. +/// +/// +/// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the +/// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. +/// +[ExcludeFromCodeCoverage] +public class NestedTopicListAttributeDescriptor : AttributeDescriptor { /*============================================================================================================================ - | CLASS: NESTED TOPIC LIST (ATTRIBUTE DESCRIPTOR) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents metadata for describing a nested topic list attribute type, including information on how it will be presented - /// and validated in the editor. - /// - /// - /// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the - /// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. - /// - [ExcludeFromCodeCoverage] - public class NestedTopicListAttributeDescriptor : AttributeDescriptor { + /// + public NestedTopicListAttributeDescriptor( + string key, + string contentType, + Topic parent, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize values \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public NestedTopicListAttributeDescriptor( - string key, - string contentType, - Topic parent, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize values - \-----------------------------------------------------------------------------------------------------------------------*/ - ModelType = ModelType.NestedTopic; + ModelType = ModelType.NestedTopic; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/Metadata/RelationshipAttributeDescriptor.cs b/OnTopic.TestDoubles/Metadata/RelationshipAttributeDescriptor.cs index 788aa167..8f47bb28 100644 --- a/OnTopic.TestDoubles/Metadata/RelationshipAttributeDescriptor.cs +++ b/OnTopic.TestDoubles/Metadata/RelationshipAttributeDescriptor.cs @@ -4,44 +4,43 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.TestDoubles.Metadata { +namespace OnTopic.TestDoubles.Metadata; + +/*============================================================================================================================== +| CLASS: RELATIONSHIP (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents metadata for describing a relationship attribute type, including information on how it will be presented and +/// validated in the editor. +/// +/// +/// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the +/// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. +/// +[ExcludeFromCodeCoverage] +public class RelationshipAttributeDescriptor : AttributeDescriptor { /*============================================================================================================================ - | CLASS: RELATIONSHIP (ATTRIBUTE DESCRIPTOR) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents metadata for describing a relationship attribute type, including information on how it will be presented and - /// validated in the editor. - /// - /// - /// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the - /// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. - /// - [ExcludeFromCodeCoverage] - public class RelationshipAttributeDescriptor : AttributeDescriptor { + /// + public RelationshipAttributeDescriptor( + string key, + string contentType, + Topic parent, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize values \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public RelationshipAttributeDescriptor( - string key, - string contentType, - Topic parent, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize values - \-----------------------------------------------------------------------------------------------------------------------*/ - ModelType = ModelType.Relationship; + ModelType = ModelType.Relationship; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/Metadata/TextAttributeDescriptor.cs b/OnTopic.TestDoubles/Metadata/TextAttributeDescriptor.cs index 37413fb6..d116628e 100644 --- a/OnTopic.TestDoubles/Metadata/TextAttributeDescriptor.cs +++ b/OnTopic.TestDoubles/Metadata/TextAttributeDescriptor.cs @@ -4,38 +4,37 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.TestDoubles.Metadata { +namespace OnTopic.TestDoubles.Metadata; + +/*============================================================================================================================== +| CLASS: TEXT (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents metadata for describing a text attribute type, including information on how it will be presented and +/// validated in the editor. +/// +/// +/// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the +/// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. +/// +[ExcludeFromCodeCoverage] +public class TextAttributeDescriptor : AttributeDescriptor { /*============================================================================================================================ - | CLASS: TEXT (ATTRIBUTE DESCRIPTOR) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents metadata for describing a text attribute type, including information on how it will be presented and - /// validated in the editor. - /// - /// - /// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the - /// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. - /// - [ExcludeFromCodeCoverage] - public class TextAttributeDescriptor : AttributeDescriptor { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public TextAttributeDescriptor( - string key, - string contentType, - Topic? parent = null, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - } + /// + public TextAttributeDescriptor( + string key, + string contentType, + Topic? parent = null, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/Metadata/TopicReferenceAttributeDescriptor.cs b/OnTopic.TestDoubles/Metadata/TopicReferenceAttributeDescriptor.cs index 4ac8e46b..fbab6629 100644 --- a/OnTopic.TestDoubles/Metadata/TopicReferenceAttributeDescriptor.cs +++ b/OnTopic.TestDoubles/Metadata/TopicReferenceAttributeDescriptor.cs @@ -4,44 +4,43 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.TestDoubles.Metadata { +namespace OnTopic.TestDoubles.Metadata; + +/*============================================================================================================================== +| CLASS: TOPIC REFERENCE (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents metadata for describing a topic reference attribute type, including information on how it will be presented +/// and validated in the editor. +/// +/// +/// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the +/// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. +/// +[ExcludeFromCodeCoverage] +public class TopicReferenceAttributeDescriptor : AttributeDescriptor { /*============================================================================================================================ - | CLASS: TOPIC REFERENCE (ATTRIBUTE DESCRIPTOR) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents metadata for describing a topic reference attribute type, including information on how it will be presented - /// and validated in the editor. - /// - /// - /// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of the - /// CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. - /// - [ExcludeFromCodeCoverage] - public class TopicReferenceAttributeDescriptor : AttributeDescriptor { + /// + public TopicReferenceAttributeDescriptor( + string key, + string contentType, + Topic parent, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize values \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public TopicReferenceAttributeDescriptor( - string key, - string contentType, - Topic parent, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize values - \-----------------------------------------------------------------------------------------------------------------------*/ - ModelType = ModelType.Reference; + ModelType = ModelType.Reference; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.TestDoubles/StubTopicRepository.cs b/OnTopic.TestDoubles/StubTopicRepository.cs index b9bc47b8..e7fe9482 100644 --- a/OnTopic.TestDoubles/StubTopicRepository.cs +++ b/OnTopic.TestDoubles/StubTopicRepository.cs @@ -9,352 +9,351 @@ using OnTopic.Querying; using OnTopic.Repositories; -namespace OnTopic.TestDoubles { +namespace OnTopic.TestDoubles; + +/*============================================================================================================================== +| CLASS: STUB TOPIC DATA REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides data access to topics hard-coded in this stub implementation of a . +/// +/// +/// Allows testing of services that depend on without maintaining a dependency on a live +/// database, or working against actual data. This is faster and safer for test methods since it doesn't maintain a +/// dependency on a live database or persistent data. +/// +[ExcludeFromCodeCoverage] +public class StubTopicRepository : TopicRepository, ITopicRepository { /*============================================================================================================================ - | CLASS: STUB TOPIC DATA REPOSITORY + | VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private int _identity = 1; + private readonly Topic _cache ; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides data access to topics hard-coded in this stub implementation of a . + /// Instantiates a new instance of the StubTopicRepository. /// - /// - /// Allows testing of services that depend on without maintaining a dependency on a live - /// database, or working against actual data. This is faster and safer for test methods since it doesn't maintain a - /// dependency on a live database or persistent data. - /// - [ExcludeFromCodeCoverage] - public class StubTopicRepository : TopicRepository, ITopicRepository { + /// A new instance of the StubTopicRepository. + public StubTopicRepository() : base() { + _cache = CreateFakeData(); + Contract.Assume(_cache); + } - /*========================================================================================================================== - | VARIABLES + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup by TopicId \-------------------------------------------------------------------------------------------------------------------------*/ - private int _identity = 1; - private readonly Topic _cache ; + var topic = _cache; + + if (topicId > 0) { + topic = _cache.FindFirst(t => t.Id.Equals(topicId)); + } - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the StubTopicRepository. - /// - /// A new instance of the StubTopicRepository. - public StubTopicRepository() : base() { - _cache = CreateFakeData(); - Contract.Assume(_cache); + if (topic != null) { + OnTopicLoaded(new(topic, isRecursive)); } - /*========================================================================================================================== - | METHOD: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) { + return topic; - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup by TopicId - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = _cache; + } - if (topicId > 0) { - topic = _cache.FindFirst(t => t.Id.Equals(topicId)); - } + /// + public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic != null) { - OnTopicLoaded(new(topic, isRecursive)); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + if (String.IsNullOrEmpty(uniqueKey)) { + return null; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return value - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic; + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup by TopicKey + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = _cache.GetByUniqueKey(uniqueKey); + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic != null) { + OnTopicLoaded(new(topic, isRecursive)); } - /// - public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Return topic + \-------------------------------------------------------------------------------------------------------------------------*/ + return topic; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - if (String.IsNullOrEmpty(uniqueKey)) { - return null; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup by TopicKey - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = _cache.GetByUniqueKey(uniqueKey); + /// + public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) { - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic != null) { - OnTopicLoaded(new(topic, isRecursive)); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(version.Date < DateTime.UtcNow, "The version requested must be a valid historical date."); + Contract.Requires( + version.Date > new DateTime(2014, 12, 9), + "The version is expected to have been created since version support was introduced into the topic library." + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup by TopicId + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = _cache; - /*------------------------------------------------------------------------------------------------------------------------ - | Return topic - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic; + if (topicId > 0) { + topic = _cache.FindFirst(t => t.Id.Equals(topicId)); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic != null) { + OnTopicLoaded(new(topic, false, version)); } - /// - public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(version.Date < DateTime.UtcNow, "The version requested must be a valid historical date."); - Contract.Requires( - version.Date > new DateTime(2014, 12, 9), - "The version is expected to have been created since version support was introduced into the topic library." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup by TopicId - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = _cache; - - if (topicId > 0) { - topic = _cache.FindFirst(t => t.Id.Equals(topicId)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Reset version + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic is not null) { + if (!topic.VersionHistory.Contains(version)) { + topic.VersionHistory.Add(version); } + topic.LastModified = version; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic != null) { - OnTopicLoaded(new(topic, false, version)); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return objects + \-------------------------------------------------------------------------------------------------------------------------*/ + return topic?? throw new TopicNotFoundException(topicId); - /*------------------------------------------------------------------------------------------------------------------------ - | Reset version - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is not null) { - if (!topic.VersionHistory.Contains(version)) { - topic.VersionHistory.Add(version); - } - topic.LastModified = version; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return objects - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic?? throw new TopicNotFoundException(topicId); + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Refresh(Topic referenceTopic, DateTime since) { } - } + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void SaveTopic([NotNull]Topic topic, DateTime version, bool persistRelationships) { - /*========================================================================================================================== - | METHOD: REFRESH + /*-------------------------------------------------------------------------------------------------------------------------- + | Assign faux identity \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Refresh(Topic referenceTopic, DateTime since) { } + if (topic.IsNew) { + topic.Id = _identity++; + } - /*========================================================================================================================== - | METHOD: SAVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void SaveTopic([NotNull]Topic topic, DateTime version, bool persistRelationships) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Assign faux identity - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic.IsNew) { - topic.Id = _identity++; - } + } - } + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void MoveTopic(Topic topic, Topic target, Topic? sibling = null) { } - /*========================================================================================================================== - | METHOD: MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void MoveTopic(Topic topic, Topic target, Topic? sibling = null) { } + /*============================================================================================================================ + | METHOD: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void DeleteTopic(Topic topic) { } - /*========================================================================================================================== - | METHOD: DELETE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void DeleteTopic(Topic topic) { } + /*============================================================================================================================ + | METHOD: GET ATTRIBUTES (PROXY) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public IEnumerable GetAttributesProxy( + Topic topic, + bool? isExtendedAttribute, + bool? isDirty = null, + bool excludeLastModified = false + ) => base.GetAttributes(topic, isExtendedAttribute, isDirty, excludeLastModified); - /*========================================================================================================================== - | METHOD: GET ATTRIBUTES (PROXY) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public IEnumerable GetAttributesProxy( - Topic topic, - bool? isExtendedAttribute, - bool? isDirty = null, - bool excludeLastModified = false - ) => base.GetAttributes(topic, isExtendedAttribute, isDirty, excludeLastModified); - - /*========================================================================================================================== - | METHOD: GET UNMATCHED ATTRIBUTES (PROXY) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public IEnumerable GetUnmatchedAttributesProxy(Topic topic) => base.GetUnmatchedAttributes(topic); + /*============================================================================================================================ + | METHOD: GET UNMATCHED ATTRIBUTES (PROXY) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public IEnumerable GetUnmatchedAttributesProxy(Topic topic) => base.GetUnmatchedAttributes(topic); - /*========================================================================================================================== - | METHOD: GET CONTENT TYPE DESCRIPTORS (PROXY) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"Deprecated. Instead, use the new {nameof(SetContentTypeDescriptorsProxy)}, which provides the same function.", - true - )] - public ContentTypeDescriptorCollection GetContentTypeDescriptorsProxy(ContentTypeDescriptor topicGraph) => - base.SetContentTypeDescriptors(topicGraph); - - /*========================================================================================================================== - | METHOD: SET CONTENT TYPE DESCRIPTORS (PROXY) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public ContentTypeDescriptorCollection SetContentTypeDescriptorsProxy(ContentTypeDescriptor topicGraph) => - base.SetContentTypeDescriptors(topicGraph); + /*============================================================================================================================ + | METHOD: GET CONTENT TYPE DESCRIPTORS (PROXY) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"Deprecated. Instead, use the new {nameof(SetContentTypeDescriptorsProxy)}, which provides the same function.", + true + )] + public ContentTypeDescriptorCollection GetContentTypeDescriptorsProxy(ContentTypeDescriptor topicGraph) => + base.SetContentTypeDescriptors(topicGraph); + + /*============================================================================================================================ + | METHOD: SET CONTENT TYPE DESCRIPTORS (PROXY) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public ContentTypeDescriptorCollection SetContentTypeDescriptorsProxy(ContentTypeDescriptor topicGraph) => + base.SetContentTypeDescriptors(topicGraph); + + /*============================================================================================================================ + | METHOD: GET CONTENT TYPE DESCRIPTOR (PROXY) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public ContentTypeDescriptor? GetContentTypeDescriptorProxy(Topic sourceTopic) => + base.GetContentTypeDescriptor(sourceTopic); - /*========================================================================================================================== - | METHOD: GET CONTENT TYPE DESCRIPTOR (PROXY) + /*============================================================================================================================ + | METHOD: CREATE FAKE DATA + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a collection of fake data that loosely mimics a bare bones database. + /// + private static Topic CreateFakeData() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish root \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public ContentTypeDescriptor? GetContentTypeDescriptorProxy(Topic sourceTopic) => - base.GetContentTypeDescriptor(sourceTopic); + var currentAttributeId = 800; + var rootTopic = new Topic("Root", "Container", null, currentAttributeId++); - /*========================================================================================================================== - | METHOD: CREATE FAKE DATA + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a collection of fake data that loosely mimics a bare bones database. - /// - private Topic CreateFakeData() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish root - \-----------------------------------------------------------------------------------------------------------------------*/ - var currentAttributeId = 800; - var rootTopic = new Topic("Root", "Container", null, currentAttributeId++); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = new Topic("Configuration", "Container", rootTopic, currentAttributeId++); - var contentTypes = new ContentTypeDescriptor("ContentTypes", "ContentTypeDescriptor", configuration, currentAttributeId++); - - addAttribute(contentTypes, "Key", "TextAttributeDescriptor", false, true); - addAttribute(contentTypes, "ContentType", "TextAttributeDescriptor", false, true); - addAttribute(contentTypes, "Title", "TextAttributeDescriptor", true, true); - addAttribute(contentTypes, "BaseTopic", "TopicReferenceAttributeDescriptor", false); - - var contentTypeDescriptor = new ContentTypeDescriptor("ContentTypeDescriptor", "ContentTypeDescriptor", contentTypes, currentAttributeId++); - - addAttribute(contentTypeDescriptor, "ContentTypes", "RelationshipAttributeDescriptor"); - addAttribute(contentTypeDescriptor, "Attributes", "NestedTopicListAttributeDescriptor"); - - TopicFactory.Create("Container", "ContentTypeDescriptor", contentTypes); - TopicFactory.Create("Lookup", "ContentTypeDescriptor", contentTypes); - TopicFactory.Create("LookupListItem", "ContentTypeDescriptor", contentTypes); - TopicFactory.Create("List", "ContentTypeDescriptor", contentTypes); - - var attributeDescriptor = new ContentTypeDescriptor("AttributeDescriptor", "ContentTypeDescriptor", contentTypes, currentAttributeId++); - - addAttribute(attributeDescriptor, "DefaultValue", "TextAttributeDescriptor", false, true); - addAttribute(attributeDescriptor, "IsRequired", "TextAttributeDescriptor", false, true); - - TopicFactory.Create("BooleanAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); - TopicFactory.Create("NestedTopicListAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); - TopicFactory.Create("NumberAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); - TopicFactory.Create("RelationshipAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); - TopicFactory.Create("TextAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); - TopicFactory.Create("TopicReferenceAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); - - var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", contentTypes, currentAttributeId++); - - addAttribute(pageContentType, "MetaTitle"); - addAttribute(pageContentType, "MetaDescription"); - addAttribute(pageContentType, "IsHidden", "TextAttributeDescriptor", false); - addAttribute(pageContentType, "TopicReference", "TopicReferenceAttributeDescriptor", false); - - var contactContentType = new ContentTypeDescriptor("Contact", "ContentTypeDescriptor", contentTypes, currentAttributeId++); - - addAttribute(contactContentType, "Name", isExtended: false); - addAttribute(contactContentType, "AlternateEmail", isExtended: false); - addAttribute(contactContentType, "BillingContactEmail", isExtended: false); - - pageContentType.Relationships.SetValue("ContentTypes", pageContentType); - pageContentType.Relationships.SetValue("ContentTypes", contactContentType); - contactContentType.Relationships.SetValue("ContentTypes", pageContentType); - - /*------------------------------------------------------------------------------------------------------------------------ - | Local addAttribute() helper function - \-----------------------------------------------------------------------------------------------------------------------*/ - AttributeDescriptor addAttribute( - Topic contentType, - string attributeKey, - string editorType = "TextAttributeDescriptor", - bool isExtended = true, - bool isRequired = false - ) { - var container = contentType.Children.GetValue("Attributes"); - if (container is null) { - container = TopicFactory.Create("Attributes", "List", contentType); - container.Attributes.SetBoolean("IsHidden", true); - } - var attribute = (AttributeDescriptor)TopicFactory.Create(attributeKey, editorType, container, currentAttributeId++); - attribute.IsRequired = isRequired; - attribute.IsExtendedAttribute = isExtended; - return attribute; - } + var configuration = new Topic("Configuration", "Container", rootTopic, currentAttributeId++); + var contentTypes = new ContentTypeDescriptor("ContentTypes", "ContentTypeDescriptor", configuration, currentAttributeId++); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish metadata - \-----------------------------------------------------------------------------------------------------------------------*/ - var metadata = new Topic("Metadata", "Container", configuration, currentAttributeId++); - var categories = new Topic("Categories", "Lookup", metadata, currentAttributeId++); - var lookup = new Topic("LookupList", "List", categories, currentAttributeId++); + addAttribute(contentTypes, "Key", "TextAttributeDescriptor", false, true); + addAttribute(contentTypes, "ContentType", "TextAttributeDescriptor", false, true); + addAttribute(contentTypes, "Title", "TextAttributeDescriptor", true, true); + addAttribute(contentTypes, "BaseTopic", "TopicReferenceAttributeDescriptor", false); - for (var i=1; i<=5; i++) { - _ = new Topic("Category" + i, "LookupListItem", lookup); - } + var contentTypeDescriptor = new ContentTypeDescriptor("ContentTypeDescriptor", "ContentTypeDescriptor", contentTypes, currentAttributeId++); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish content - \-----------------------------------------------------------------------------------------------------------------------*/ - var web = TopicFactory.Create("Web", "Page", rootTopic, 10000); + addAttribute(contentTypeDescriptor, "ContentTypes", "RelationshipAttributeDescriptor"); + addAttribute(contentTypeDescriptor, "Attributes", "NestedTopicListAttributeDescriptor"); - CreateFakeData(web, 2, 3); + TopicFactory.Create("Container", "ContentTypeDescriptor", contentTypes); + TopicFactory.Create("Lookup", "ContentTypeDescriptor", contentTypes); + TopicFactory.Create("LookupListItem", "ContentTypeDescriptor", contentTypes); + TopicFactory.Create("List", "ContentTypeDescriptor", contentTypes); - var pageGroup = new Topic("Web_3", "PageGroup", web, currentAttributeId++); - _ = new Topic("Web_3_0", "Page", pageGroup, currentAttributeId++); - var childPage = new Topic("Web_3_1", "Page", pageGroup, currentAttributeId++); - var leafPage = new Topic("Web_3_1_0", "Page", childPage, currentAttributeId++); + var attributeDescriptor = new ContentTypeDescriptor("AttributeDescriptor", "ContentTypeDescriptor", contentTypes, currentAttributeId++); - leafPage.Attributes.SetValue("NavigationRoot", "Configuration"); + addAttribute(attributeDescriptor, "DefaultValue", "TextAttributeDescriptor", false, true); + addAttribute(attributeDescriptor, "IsRequired", "TextAttributeDescriptor", false, true); - /*------------------------------------------------------------------------------------------------------------------------ - | Set to cache - \-----------------------------------------------------------------------------------------------------------------------*/ - return rootTopic; + TopicFactory.Create("BooleanAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); + TopicFactory.Create("NestedTopicListAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); + TopicFactory.Create("NumberAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); + TopicFactory.Create("RelationshipAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); + TopicFactory.Create("TextAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); + TopicFactory.Create("TopicReferenceAttributeDescriptor", "ContentTypeDescriptor", attributeDescriptor); + var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", contentTypes, currentAttributeId++); + + addAttribute(pageContentType, "MetaTitle"); + addAttribute(pageContentType, "MetaDescription"); + addAttribute(pageContentType, "IsHidden", "TextAttributeDescriptor", false); + addAttribute(pageContentType, "TopicReference", "TopicReferenceAttributeDescriptor", false); + + var contactContentType = new ContentTypeDescriptor("Contact", "ContentTypeDescriptor", contentTypes, currentAttributeId++); + + addAttribute(contactContentType, "Name", isExtended: false); + addAttribute(contactContentType, "AlternateEmail", isExtended: false); + addAttribute(contactContentType, "BillingContactEmail", isExtended: false); + + pageContentType.Relationships.SetValue("ContentTypes", pageContentType); + pageContentType.Relationships.SetValue("ContentTypes", contactContentType); + contactContentType.Relationships.SetValue("ContentTypes", pageContentType); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Local addAttribute() helper function + \-------------------------------------------------------------------------------------------------------------------------*/ + AttributeDescriptor addAttribute( + Topic contentType, + string attributeKey, + string editorType = "TextAttributeDescriptor", + bool isExtended = true, + bool isRequired = false + ) { + var container = contentType.Children.GetValue("Attributes"); + if (container is null) { + container = TopicFactory.Create("Attributes", "List", contentType); + container.Attributes.SetBoolean("IsHidden", true); + } + var attribute = (AttributeDescriptor)TopicFactory.Create(attributeKey, editorType, container, currentAttributeId++); + attribute.IsRequired = isRequired; + attribute.IsExtendedAttribute = isExtended; + return attribute; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish metadata + \-------------------------------------------------------------------------------------------------------------------------*/ + var metadata = new Topic("Metadata", "Container", configuration, currentAttributeId++); + var categories = new Topic("Categories", "Lookup", metadata, currentAttributeId++); + var lookup = new Topic("LookupList", "List", categories, currentAttributeId++); + + for (var i=1; i<=5; i++) { + _ = new Topic("Category" + i, "LookupListItem", lookup); } - /*========================================================================================================================== - | METHOD: CREATE FAKE DATA + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish content \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a collection of fake data recursively based on a parent topic, and set number of levels. - /// - private void CreateFakeData(Topic parent, int count = 3, int depth = 3) { - for (var i = 0; i < count; i++) { - var topic = new Topic(parent.Key + "_" + i, "Page", parent, parent.Id + (int)Math.Pow(10, depth) * i); - topic.Attributes.SetValue("ParentKey", parent.Key); - topic.Attributes.SetValue("DepthCount", (depth+i).ToString(CultureInfo.InvariantCulture)); - if (depth > 0) { - CreateFakeData(topic, count, depth - 1); - } + var web = TopicFactory.Create("Web", "Page", rootTopic, 10000); + + CreateFakeData(web, 2, 3); + + var pageGroup = new Topic("Web_3", "PageGroup", web, currentAttributeId++); + _ = new Topic("Web_3_0", "Page", pageGroup, currentAttributeId++); + var childPage = new Topic("Web_3_1", "Page", pageGroup, currentAttributeId++); + var leafPage = new Topic("Web_3_1_0", "Page", childPage, currentAttributeId++); + + leafPage.Attributes.SetValue("NavigationRoot", "Configuration"); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set to cache + \-------------------------------------------------------------------------------------------------------------------------*/ + return rootTopic; + + } + + /*============================================================================================================================ + | METHOD: CREATE FAKE DATA + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a collection of fake data recursively based on a parent topic, and set number of levels. + /// + private static void CreateFakeData(Topic parent, int count = 3, int depth = 3) { + for (var i = 0; i < count; i++) { + var topic = new Topic(parent.Key + "_" + i, "Page", parent, parent.Id + (int)Math.Pow(10, depth) * i); + topic.Attributes.SetValue("ParentKey", parent.Key); + topic.Attributes.SetValue("DepthCount", (depth+i).ToString(CultureInfo.InvariantCulture)); + if (depth > 0) { + CreateFakeData(topic, count, depth - 1); } } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/AttributeCollectionTest.cs b/OnTopic.Tests/AttributeCollectionTest.cs index 56343b2a..b89423b0 100644 --- a/OnTopic.Tests/AttributeCollectionTest.cs +++ b/OnTopic.Tests/AttributeCollectionTest.cs @@ -9,1164 +9,1163 @@ using OnTopic.Tests.Entities; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE COLLECTION TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AttributeCollectionTest { /*============================================================================================================================ - | CLASS: ATTRIBUTE COLLECTION TEST + | TEST: GET VALUE: CORRECT VALUE: IS RETURNED \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Creates a new attribute via an [AttributeSetter] and ensures that the attribute can be returned. /// - [ExcludeFromCodeCoverage] - public class AttributeCollectionTest { - - /*========================================================================================================================== - | TEST: GET VALUE: CORRECT VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a new attribute via an [AttributeSetter] and ensures that the attribute can be returned. - /// - [Fact] - public void GetValue_CorrectValue_IsReturned() { - var topic = new Topic("Test", "Container") { - View = "Test" - }; - Assert.Equal("Test", topic.Attributes.GetValue("View")); - } + [Fact] + public void GetValue_CorrectValue_IsReturned() { + var topic = new Topic("Test", "Container") { + View = "Test" + }; + Assert.Equal("Test", topic.Attributes.GetValue("View")); + } - /*========================================================================================================================== - | TEST: GET VALUE: INHERITED VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that values can be set and retrieved as expected via inheritance, both via and . - /// - [Fact] - public void GetValue_InheritedValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET VALUE: INHERITED VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that values can be set and retrieved as expected via inheritance, both via and . + /// + [Fact] + public void GetValue_InheritedValue_IsReturned() { - var baseTopic = new Topic("Base", "Container"); - var topic = new Topic("Test", "Container"); - var childTopic = new Topic("Child", "Container", topic); + var baseTopic = new Topic("Base", "Container"); + var topic = new Topic("Test", "Container"); + var childTopic = new Topic("Child", "Container", topic); - topic.BaseTopic = baseTopic; + topic.BaseTopic = baseTopic; - baseTopic.View = "Test"; + baseTopic.View = "Test"; - Assert.Equal("Test", topic.Attributes.GetValue("View")); - Assert.Equal("Test", childTopic.Attributes.GetValue("View", "Invalid", true)); - Assert.Null(topic.Attributes.GetValue("View", null, inheritFromBase: false)); + Assert.Equal("Test", topic.Attributes.GetValue("View")); + Assert.Equal("Test", childTopic.Attributes.GetValue("View", "Invalid", true)); + Assert.Null(topic.Attributes.GetValue("View", null, inheritFromBase: false)); - } + } - /*========================================================================================================================== - | TEST: GET VALUE: MISSING VALUE: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a new topic and requests an invalid attribute; ensures falls back to the default. - /// - [Fact] - public void GetValue_MissingValue_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET VALUE: MISSING VALUE: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a new topic and requests an invalid attribute; ensures falls back to the default. + /// + [Fact] + public void GetValue_MissingValue_ReturnsDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - Assert.Null(topic.Attributes.GetValue("InvalidAttribute")); - Assert.Equal("Foo", topic.Attributes.GetValue("InvalidAttribute", "Foo")); + Assert.Null(topic.Attributes.GetValue("InvalidAttribute")); + Assert.Equal("Foo", topic.Attributes.GetValue("InvalidAttribute", "Foo")); - } + } - /*========================================================================================================================== - | TEST: GET VALUE: EMPTY VALUE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// If the is , then should return null. - /// - [Fact] - public void GetValue_EmptyValue_ReturnsNull() { + /*============================================================================================================================ + | TEST: GET VALUE: EMPTY VALUE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// If the is , then should return null. + /// + [Fact] + public void GetValue_EmptyValue_ReturnsNull() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.Add(new("EmptyValue", "")); + topic.Attributes.Add(new("EmptyValue", "")); - Assert.Null(topic.Attributes.GetValue("EmptyValue")); + Assert.Null(topic.Attributes.GetValue("EmptyValue")); - } + } - /*========================================================================================================================== - | TEST: GET INTEGER: CORRECT VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that integer values can be set and retrieved as expected. - /// - [Fact] - public void GetInteger_CorrectValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET INTEGER: CORRECT VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that integer values can be set and retrieved as expected. + /// + [Fact] + public void GetInteger_CorrectValue_IsReturned() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetInteger("Number1", 1); + topic.Attributes.SetInteger("Number1", 1); - Assert.Equal(1, topic.Attributes.GetInteger("Number1", 5)); + Assert.Equal(1, topic.Attributes.GetInteger("Number1", 5)); - } + } - /*========================================================================================================================== - | TEST: GET DOUBLE: INHERITED VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that integer values can be set and retrieved as expected via inheritance, both via - /// and . - /// - [Fact] - public void GetInteger_InheritedValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET DOUBLE: INHERITED VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that integer values can be set and retrieved as expected via inheritance, both via + /// and . + /// + [Fact] + public void GetInteger_InheritedValue_IsReturned() { - var baseTopic = new Topic("Base", "Container"); - var topic = new Topic("Test", "Container"); - var childTopic = new Topic("Child", "Container", topic); + var baseTopic = new Topic("Base", "Container"); + var topic = new Topic("Test", "Container"); + var childTopic = new Topic("Child", "Container", topic); - topic.BaseTopic = baseTopic; + topic.BaseTopic = baseTopic; - baseTopic.Attributes.SetInteger("Number1", 1); + baseTopic.Attributes.SetInteger("Number1", 1); - Assert.Equal(1, topic.Attributes.GetInteger("Number1", 5)); - Assert.Equal(1, childTopic.Attributes.GetInteger("Number1", 5, true)); - Assert.Equal(0, topic.Attributes.GetInteger("Number1", inheritFromBase: false)); + Assert.Equal(1, topic.Attributes.GetInteger("Number1", 5)); + Assert.Equal(1, childTopic.Attributes.GetInteger("Number1", 5, true)); + Assert.Equal(0, topic.Attributes.GetInteger("Number1", inheritFromBase: false)); - } + } - /*========================================================================================================================== - | TEST: GET INTEGER: INCORRECT VALUE: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that invalid values return the default. - /// - [Fact] - public void GetInteger_IncorrectValue_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET INTEGER: INCORRECT VALUE: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that invalid values return the default. + /// + [Fact] + public void GetInteger_IncorrectValue_ReturnsDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Number3", "Invalid"); + topic.Attributes.SetValue("Number3", "Invalid"); - Assert.Equal(0, topic.Attributes.GetInteger("Number3")); - Assert.Equal(5, topic.Attributes.GetInteger("Number3", 5)); + Assert.Equal(0, topic.Attributes.GetInteger("Number3")); + Assert.Equal(5, topic.Attributes.GetInteger("Number3", 5)); - } + } - /*========================================================================================================================== - | TEST: GET INTEGER: INCORRECT KEY: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that incorrect key names return the default. - /// - [Fact] - public void GetInteger_IncorrectKey_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET INTEGER: INCORRECT KEY: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that incorrect key names return the default. + /// + [Fact] + public void GetInteger_IncorrectKey_ReturnsDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - Assert.Equal(0, topic.Attributes.GetInteger("InvalidKey")); - Assert.Equal(5, topic.Attributes.GetInteger("InvalidKey", 5)); + Assert.Equal(0, topic.Attributes.GetInteger("InvalidKey")); + Assert.Equal(5, topic.Attributes.GetInteger("InvalidKey", 5)); - } + } - /*========================================================================================================================== - | TEST: GET DOUBLE: CORRECT VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that double values can be set and retrieved as expected. - /// - [Fact] - public void GetDouble_CorrectValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET DOUBLE: CORRECT VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that double values can be set and retrieved as expected. + /// + [Fact] + public void GetDouble_CorrectValue_IsReturned() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetDouble("Number1", 1); + topic.Attributes.SetDouble("Number1", 1); - Assert.Equal(1.0, topic.Attributes.GetDouble("Number1", 5.0)); + Assert.Equal(1.0, topic.Attributes.GetDouble("Number1", 5.0)); - } + } - /*========================================================================================================================== - | TEST: GET DOUBLE: INHERITED VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that double values can be set and retrieved as expected via inheritance, both via - /// and . - /// - [Fact] - public void GetDouble_InheritedValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET DOUBLE: INHERITED VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that double values can be set and retrieved as expected via inheritance, both via + /// and . + /// + [Fact] + public void GetDouble_InheritedValue_IsReturned() { - var baseTopic = new Topic("Base", "Container"); - var topic = new Topic("Test", "Container"); - var childTopic = new Topic("Child", "Container", topic); + var baseTopic = new Topic("Base", "Container"); + var topic = new Topic("Test", "Container"); + var childTopic = new Topic("Child", "Container", topic); - topic.BaseTopic = baseTopic; + topic.BaseTopic = baseTopic; - baseTopic.Attributes.SetDouble("Number1", 1); + baseTopic.Attributes.SetDouble("Number1", 1); - Assert.Equal(1.0, topic.Attributes.GetDouble("Number1", 5.0)); - Assert.Equal(1.0, childTopic.Attributes.GetDouble("Number1", 5.0, true)); - Assert.Equal(0.0, topic.Attributes.GetInteger("Number1", inheritFromBase: false)); + Assert.Equal(1.0, topic.Attributes.GetDouble("Number1", 5.0)); + Assert.Equal(1.0, childTopic.Attributes.GetDouble("Number1", 5.0, true)); + Assert.Equal(0.0, topic.Attributes.GetInteger("Number1", inheritFromBase: false)); - } + } - /*========================================================================================================================== - | TEST: GET DOUBLE: INCORRECT VALUE: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that double values return the default. - /// - [Fact] - public void GetDouble_IncorrectValue_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET DOUBLE: INCORRECT VALUE: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that double values return the default. + /// + [Fact] + public void GetDouble_IncorrectValue_ReturnsDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Number3", "Invalid"); + topic.Attributes.SetValue("Number3", "Invalid"); - Assert.Equal(0.0, topic.Attributes.GetDouble("Number3")); - Assert.Equal(5.0, topic.Attributes.GetDouble("Number3", 5.0)); + Assert.Equal(0.0, topic.Attributes.GetDouble("Number3")); + Assert.Equal(5.0, topic.Attributes.GetDouble("Number3", 5.0)); - } + } - /*========================================================================================================================== - | TEST: GET DOUBLE: INCORRECT KEY: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that double key names return the default. - /// - [Fact] - public void GetDouble_IncorrectKey_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET DOUBLE: INCORRECT KEY: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that double key names return the default. + /// + [Fact] + public void GetDouble_IncorrectKey_ReturnsDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - Assert.Equal(0.0, topic.Attributes.GetDouble("InvalidKey")); - Assert.Equal(5.0, topic.Attributes.GetDouble("InvalidKey", 5.0)); + Assert.Equal(0.0, topic.Attributes.GetDouble("InvalidKey")); + Assert.Equal(5.0, topic.Attributes.GetDouble("InvalidKey", 5.0)); - } + } - /*========================================================================================================================== - | TEST: GET DATETIME: CORRECT VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that Date/Time values can be set and retrieved as expected. - /// - [Fact] - public void GetDateTime_CorrectValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET DATETIME: CORRECT VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that Date/Time values can be set and retrieved as expected. + /// + [Fact] + public void GetDateTime_CorrectValue_IsReturned() { - var topic = new Topic("Test", "Container"); - var dateTime1 = new DateTime(1976, 10, 15); + var topic = new Topic("Test", "Container"); + var dateTime1 = new DateTime(1976, 10, 15); - topic.Attributes.SetDateTime("DateTime1", dateTime1); + topic.Attributes.SetDateTime("DateTime1", dateTime1); - Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime1", DateTime.MinValue)); + Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime1", DateTime.MinValue)); - } + } - /*========================================================================================================================== - | TEST: GET DATETIME: INHERITED VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that Date/Time values can be set and retrieved as expected via inheritance, both via - /// and . - /// - [Fact] - public void GetDateTime_InheritedValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET DATETIME: INHERITED VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that Date/Time values can be set and retrieved as expected via inheritance, both via + /// and . + /// + [Fact] + public void GetDateTime_InheritedValue_IsReturned() { - var baseTopic = new Topic("Base", "Container"); - var topic = new Topic("Test", "Container"); - var childTopic = new Topic("Child", "Container", topic); - var dateTime1 = new DateTime(1976, 10, 15); + var baseTopic = new Topic("Base", "Container"); + var topic = new Topic("Test", "Container"); + var childTopic = new Topic("Child", "Container", topic); + var dateTime1 = new DateTime(1976, 10, 15); - topic.BaseTopic = baseTopic; + topic.BaseTopic = baseTopic; - baseTopic.Attributes.SetDateTime("DateTime1", dateTime1); + baseTopic.Attributes.SetDateTime("DateTime1", dateTime1); - Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime1", DateTime.Now)); - Assert.Equal(dateTime1, childTopic.Attributes.GetDateTime("DateTime1", DateTime.Now, true)); - Assert.Equal(new DateTime(), topic.Attributes.GetDateTime("DateTime1", inheritFromBase: false)); + Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime1", DateTime.Now)); + Assert.Equal(dateTime1, childTopic.Attributes.GetDateTime("DateTime1", DateTime.Now, true)); + Assert.Equal(new DateTime(), topic.Attributes.GetDateTime("DateTime1", inheritFromBase: false)); - } + } - /*========================================================================================================================== - | TEST: GET DATETIME: INCORRECT VALUE: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that invalid values return the default. - /// - [Fact] - public void GetDateTime_IncorrectValue_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET DATETIME: INCORRECT VALUE: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that invalid values return the default. + /// + [Fact] + public void GetDateTime_IncorrectValue_ReturnsDefault() { - var topic = new Topic("Test", "Container"); - var dateTime1 = new DateTime(1976, 10, 15); + var topic = new Topic("Test", "Container"); + var dateTime1 = new DateTime(1976, 10, 15); - topic.Attributes.SetValue("DateTime2", "IncorrectValue"); + topic.Attributes.SetValue("DateTime2", "IncorrectValue"); - Assert.Equal(new DateTime(), topic.Attributes.GetDateTime("DateTime2")); - Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime2", dateTime1)); + Assert.Equal(new DateTime(), topic.Attributes.GetDateTime("DateTime2")); + Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime2", dateTime1)); - } + } - /*========================================================================================================================== - | TEST: GET DATETIME: INCORRECT KEY: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that incorrect key names return the default. - /// - [Fact] - public void GetDateTime_IncorrectKey_ReturnsDefault() { + /*============================================================================================================================ + | TEST: GET DATETIME: INCORRECT KEY: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that incorrect key names return the default. + /// + [Fact] + public void GetDateTime_IncorrectKey_ReturnsDefault() { - var topic = new Topic("Test", "Container"); - var dateTime1 = new DateTime(1976, 10, 15); - var dateTime2 = new DateTime(1981, 06, 03); + var topic = new Topic("Test", "Container"); + var dateTime1 = new DateTime(1976, 10, 15); + var dateTime2 = new DateTime(1981, 06, 03); - topic.Attributes.SetDateTime("DateTime2", dateTime2); + topic.Attributes.SetDateTime("DateTime2", dateTime2); - Assert.Equal(new DateTime(), topic.Attributes.GetDateTime("DateTime3")); - Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime3", dateTime1)); + Assert.Equal(new DateTime(), topic.Attributes.GetDateTime("DateTime3")); + Assert.Equal(dateTime1, topic.Attributes.GetDateTime("DateTime3", dateTime1)); - } + } - /*========================================================================================================================== - | TEST: GET BOOLEAN: CORRECT VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that boolean values can be set and retrieved as expected. - /// - [Fact] - public void GetBoolean_CorrectValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET BOOLEAN: CORRECT VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that boolean values can be set and retrieved as expected. + /// + [Fact] + public void GetBoolean_CorrectValue_IsReturned() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetBoolean("IsValue1", true); - topic.Attributes.SetBoolean("IsValue2", false); + topic.Attributes.SetBoolean("IsValue1", true); + topic.Attributes.SetBoolean("IsValue2", false); - Assert.True(topic.Attributes.GetBoolean("IsValue1")); - Assert.True(topic.Attributes.GetBoolean("IsValue1", false)); - Assert.False(topic.Attributes.GetBoolean("IsValue2", true)); + Assert.True(topic.Attributes.GetBoolean("IsValue1")); + Assert.True(topic.Attributes.GetBoolean("IsValue1", false)); + Assert.False(topic.Attributes.GetBoolean("IsValue2", true)); - } + } - /*========================================================================================================================== - | TEST: GET BOOLEAN: INHERITED VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that boolean values can be set and retrieved as expected via inheritance, both via - /// and . - /// - [Fact] - public void GetBoolean_InheritedValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET BOOLEAN: INHERITED VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that boolean values can be set and retrieved as expected via inheritance, both via + /// and . + /// + [Fact] + public void GetBoolean_InheritedValue_IsReturned() { - var baseTopic = new Topic("Base", "Container"); - var topic = new Topic("Test", "Container"); - var childTopic = new Topic("Child", "Container", topic); + var baseTopic = new Topic("Base", "Container"); + var topic = new Topic("Test", "Container"); + var childTopic = new Topic("Child", "Container", topic); - topic.BaseTopic = baseTopic; + topic.BaseTopic = baseTopic; - baseTopic.Attributes.SetBoolean("IsValue1", true); + baseTopic.Attributes.SetBoolean("IsValue1", true); - Assert.True(topic.Attributes.GetBoolean("IsValue1")); - Assert.True(childTopic.Attributes.GetBoolean("IsValue1", false, true)); - Assert.False(topic.Attributes.GetBoolean("IsValue1", inheritFromBase: false)); + Assert.True(topic.Attributes.GetBoolean("IsValue1")); + Assert.True(childTopic.Attributes.GetBoolean("IsValue1", false, true)); + Assert.False(topic.Attributes.GetBoolean("IsValue1", inheritFromBase: false)); - } + } - /*========================================================================================================================== - | TEST: GET BOOLEAN: INCORRECT VALUE: RETURN DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that invalid values return the default. - /// - [Fact] - public void GetBoolean_IncorrectValue_ReturnDefault() { + /*============================================================================================================================ + | TEST: GET BOOLEAN: INCORRECT VALUE: RETURN DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that invalid values return the default. + /// + [Fact] + public void GetBoolean_IncorrectValue_ReturnDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("IsValue", "Invalid"); + topic.Attributes.SetValue("IsValue", "Invalid"); - Assert.False(topic.Attributes.GetBoolean("IsValue")); - Assert.True(topic.Attributes.GetBoolean("IsValue", true)); - Assert.False(topic.Attributes.GetBoolean("IsValue", false)); + Assert.False(topic.Attributes.GetBoolean("IsValue")); + Assert.True(topic.Attributes.GetBoolean("IsValue", true)); + Assert.False(topic.Attributes.GetBoolean("IsValue", false)); - } + } - /*========================================================================================================================== - | TEST: GET BOOLEAN: INCORRECT KEY: RETURN DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that incorrect key names return the default. - /// - [Fact] - public void GetBoolean_IncorrectKey_ReturnDefault() { + /*============================================================================================================================ + | TEST: GET BOOLEAN: INCORRECT KEY: RETURN DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that incorrect key names return the default. + /// + [Fact] + public void GetBoolean_IncorrectKey_ReturnDefault() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - Assert.False(topic.Attributes.GetBoolean("InvalidKey")); - Assert.True(topic.Attributes.GetBoolean("InvalidKey", true)); - Assert.False(topic.Attributes.GetBoolean("InvalidKey", false)); + Assert.False(topic.Attributes.GetBoolean("InvalidKey")); + Assert.True(topic.Attributes.GetBoolean("InvalidKey", true)); + Assert.False(topic.Attributes.GetBoolean("InvalidKey", false)); - } + } - /*========================================================================================================================== - | TEST: GET URI: INHERITED VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that URI values can be set and retrieved as expected via inheritance, both via - /// and . - /// - [Fact] - public void GetUri_InheritedValue_IsReturned() { + /*============================================================================================================================ + | TEST: GET URI: INHERITED VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that URI values can be set and retrieved as expected via inheritance, both via + /// and . + /// + [Fact] + public void GetUri_InheritedValue_IsReturned() { - var baseTopic = new Topic("Base", "Container"); - var topic = new Topic("Test", "Container"); - var childTopic = new Topic("Child", "Container", topic); - var url = "https://www.github.com/OnTopicCMS/"; - var uri = new Uri(url); + var baseTopic = new Topic("Base", "Container"); + var topic = new Topic("Test", "Container"); + var childTopic = new Topic("Child", "Container", topic); + var url = "https://www.github.com/OnTopicCMS/"; + var uri = new Uri(url); - topic.BaseTopic = baseTopic; + topic.BaseTopic = baseTopic; - baseTopic.Attributes.SetUri("Url", uri); + baseTopic.Attributes.SetUri("Url", uri); - Assert.Equal(uri, topic.Attributes.GetUri("Url")); - Assert.Equal(uri, childTopic.Attributes.GetUri("Url", inheritFromParent: true)); - Assert.Null(topic.Attributes.GetUri("Url", inheritFromBase: false)); + Assert.Equal(uri, topic.Attributes.GetUri("Url")); + Assert.Equal(uri, childTopic.Attributes.GetUri("Url", inheritFromParent: true)); + Assert.Null(topic.Attributes.GetUri("Url", inheritFromBase: false)); - } + } - /*========================================================================================================================== - | TEST: GET URI: INCORRECT VALUE: RETURN DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that invalid values return the default. - /// - [Fact] - public void GetUri_IncorrectValue_ReturnDefault() { + /*============================================================================================================================ + | TEST: GET URI: INCORRECT VALUE: RETURN DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that invalid values return the default. + /// + [Fact] + public void GetUri_IncorrectValue_ReturnDefault() { - var topic = new Topic("Test", "Container"); - var url = "https://www.github.com/OnTopicCMS/"; - var uri = new Uri(url); + var topic = new Topic("Test", "Container"); + var url = "https://www.github.com/OnTopicCMS/"; + var uri = new Uri(url); - Assert.Null(topic.Attributes.GetUri("InvalidUrl")); - Assert.Equal(uri, topic.Attributes.GetUri("InvalidUrl", uri)); + Assert.Null(topic.Attributes.GetUri("InvalidUrl")); + Assert.Equal(uri, topic.Attributes.GetUri("InvalidUrl", uri)); - } + } - /*========================================================================================================================== - | TEST: SET VALUE: CORRECT VALUE: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a custom attribute on a topic and ensures it can be retrieved. - /// - [Fact] - public void SetValue_CorrectValue_IsReturned() { - var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Foo", "Bar"); - Assert.Equal("Bar", topic.Attributes.GetValue("Foo")); - } + /*============================================================================================================================ + | TEST: SET VALUE: CORRECT VALUE: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a custom attribute on a topic and ensures it can be retrieved. + /// + [Fact] + public void SetValue_CorrectValue_IsReturned() { + var topic = new Topic("Test", "Container"); + topic.Attributes.SetValue("Foo", "Bar"); + Assert.Equal("Bar", topic.Attributes.GetValue("Foo")); + } - /*========================================================================================================================== - | TEST: SET VALUE: VALUE CHANGED: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Modifies the value of a custom attribute on a topic and ensures it is marked as IsDirty. - /// - [Fact] - public void SetValue_ValueChanged_IsDirty() { + /*============================================================================================================================ + | TEST: SET VALUE: VALUE CHANGED: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Modifies the value of a custom attribute on a topic and ensures it is marked as IsDirty. + /// + [Fact] + public void SetValue_ValueChanged_IsDirty() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Foo", "Bar", false); - topic.Attributes.SetValue("Foo", "Baz"); + topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("Foo", "Baz"); - Assert.True(topic.Attributes["Foo"].IsDirty); + Assert.True(topic.Attributes["Foo"].IsDirty); - } + } - /*========================================================================================================================== - | TEST: CLEAR: NON-NULLABLE VALUE WITH BUSINESS LOGIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets an attribute on a topic instance with an valid value, and then attempts to clear all attributes. Ensures that the - /// business logic is enforced by throwing an exception on the non-nullable property. - /// - [Fact] - public void Clear_NonNullableValueWithBusinessLogic_ThrowsException() { + /*============================================================================================================================ + | TEST: CLEAR: NON-NULLABLE VALUE WITH BUSINESS LOGIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets an attribute on a topic instance with an valid value, and then attempts to clear all attributes. Ensures that the + /// business logic is enforced by throwing an exception on the non-nullable property. + /// + [Fact] + public void Clear_NonNullableValueWithBusinessLogic_ThrowsException() { - var topic = new CustomTopic("Test", "Page") { - NonNullableAttribute = "Test" - }; + var topic = new CustomTopic("Test", "Page") { + NonNullableAttribute = "Test" + }; - Assert.Throws(() => - topic.Attributes.Clear() - ); + Assert.Throws(() => + topic.Attributes.Clear() + ); - } + } - /*========================================================================================================================== - | TEST: CLEAR: EXISTING VALUES: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls and confirms that the collection is marked as dirty, due to deleted attrbutes. - /// - [Fact] - public void Clear_ExistingValues_IsDirty() { + /*============================================================================================================================ + | TEST: CLEAR: EXISTING VALUES: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls and confirms that the collection is marked as dirty, due to deleted attrbutes. + /// + [Fact] + public void Clear_ExistingValues_IsDirty() { - var topic = new Topic("Test", "Container", null, 1); + var topic = new Topic("Test", "Container", null, 1); - topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("Foo", "Bar", false); - topic.Attributes.Clear(); + topic.Attributes.Clear(); - Assert.True(topic.Attributes.IsDirty()); - Assert.Contains("Foo", topic.Attributes.DeletedItems); + Assert.True(topic.Attributes.IsDirty()); + Assert.Contains("Foo", topic.Attributes.DeletedItems); - } + } - /*========================================================================================================================== - | TEST: SET VALUE: VALUE UNCHANGED: IS NOT DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets the value of a custom to the existing value and ensures it is not marked as - /// . - /// - [Fact] - public void SetValue_ValueUnchanged_IsNotDirty() { + /*============================================================================================================================ + | TEST: SET VALUE: VALUE UNCHANGED: IS NOT DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets the value of a custom to the existing value and ensures it is not marked as + /// . + /// + [Fact] + public void SetValue_ValueUnchanged_IsNotDirty() { - var topic = new Topic("Test", "Container", null, 1); + var topic = new Topic("Test", "Container", null, 1); - topic.Attributes.SetValue("Fah", "Bar", false); - topic.Attributes.SetValue("Fah", "Bar"); + topic.Attributes.SetValue("Fah", "Bar", false); + topic.Attributes.SetValue("Fah", "Bar"); - Assert.False(topic.Attributes["Fah"].IsDirty); + Assert.False(topic.Attributes["Fah"].IsDirty); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: DIRTY VALUES: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a that is marked as . Confirms that returns true. - /// - [Fact] - public void IsDirty_DirtyValues_ReturnsTrue() { + /*============================================================================================================================ + | TEST: IS DIRTY: DIRTY VALUES: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a that is marked as . Confirms that returns true. + /// + [Fact] + public void IsDirty_DirtyValues_ReturnsTrue() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.SetValue("Foo", "Bar"); - Assert.True(topic.Attributes.IsDirty()); + Assert.True(topic.Attributes.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: IS NEW: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a that is not marked as . Confirms that returns - /// true if , even if was called. - /// - [Fact] - public void IsDirty_IsNew_ReturnsTrue() { + /*============================================================================================================================ + | TEST: IS DIRTY: IS NEW: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a that is not marked as . Confirms that returns + /// true if , even if was called. + /// + [Fact] + public void IsDirty_IsNew_ReturnsTrue() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("Foo", "Bar", false); - topic.Attributes.MarkClean("Foo"); - topic.Attributes.MarkClean(); + topic.Attributes.MarkClean("Foo"); + topic.Attributes.MarkClean(); - Assert.True(topic.Attributes.IsDirty()); - Assert.True(topic.Attributes.IsDirty(true)); + Assert.True(topic.Attributes.IsDirty()); + Assert.True(topic.Attributes.IsDirty(true)); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: DELETED VALUES: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a and then deletes it. Confirms - /// that returns true. - /// - [Fact] - public void IsDirty_DeletedValues_ReturnsTrue() { + /*============================================================================================================================ + | TEST: IS DIRTY: DELETED VALUES: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a and then deletes it. Confirms + /// that returns true. + /// + [Fact] + public void IsDirty_DeletedValues_ReturnsTrue() { - var topic = new Topic("Test", "Container", null, 1); + var topic = new Topic("Test", "Container", null, 1); - topic.Attributes.SetValue("Foo", "Bar"); - topic.Attributes.Remove("Foo"); + topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.Remove("Foo"); - Assert.True(topic.Attributes.IsDirty()); - Assert.True(topic.Attributes.IsDirty(true)); + Assert.True(topic.Attributes.IsDirty()); + Assert.True(topic.Attributes.IsDirty(true)); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: UNDELETED VALUES: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a and then deletes it. Confirms - /// that returns false after recreating the value. - /// - [Fact] - public void IsDirty_UndeletedValues_ReturnsFalse() { + /*============================================================================================================================ + | TEST: IS DIRTY: UNDELETED VALUES: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a and then deletes it. Confirms + /// that returns false after recreating the value. + /// + [Fact] + public void IsDirty_UndeletedValues_ReturnsFalse() { - var topic = new Topic("Test", "Container", null, 1); + var topic = new Topic("Test", "Container", null, 1); - topic.Attributes.SetValue("Foo", "Bar"); - topic.Attributes.Remove("Foo"); - topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.Remove("Foo"); + topic.Attributes.SetValue("Foo", "Bar", false); - Assert.False(topic.Attributes.IsDirty()); - Assert.False(topic.Attributes.IsDirty(true)); - Assert.DoesNotContain("Foo", topic.Attributes.DeletedItems); + Assert.False(topic.Attributes.IsDirty()); + Assert.False(topic.Attributes.IsDirty(true)); + Assert.DoesNotContain("Foo", topic.Attributes.DeletedItems); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: NO DIRTY VALUES: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a that is not marked as . Confirms that returns - /// false. - /// - [Fact] - public void IsDirty_NoDirtyValues_ReturnsFalse() { + /*============================================================================================================================ + | TEST: IS DIRTY: NO DIRTY VALUES: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a that is not marked as . Confirms that returns + /// false. + /// + [Fact] + public void IsDirty_NoDirtyValues_ReturnsFalse() { - var topic = new Topic("Test", "Container", null, 1); + var topic = new Topic("Test", "Container", null, 1); - topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("Foo", "Bar", false); - Assert.False(topic.Attributes.IsDirty()); + Assert.False(topic.Attributes.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: IS NEW: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a that is not marked as . Confirms that still returns - /// true if the associated is . New topics cannot be clean. - /// - [Fact] - public void IsDirty_IsNew_ReturnsFalse() { + /*============================================================================================================================ + | TEST: IS DIRTY: IS NEW: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a that is not marked as . Confirms that still returns + /// true if the associated is . New topics cannot be clean. + /// + [Fact] + public void IsDirty_IsNew_ReturnsFalse() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("Foo", "Bar", false); - Assert.True(topic.Attributes.IsDirty()); + Assert.True(topic.Attributes.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: MISSING KEY: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Confirms that calling with an invalid - /// key returns false. - /// - [Fact] - public void IsDirty_MissingKey_ReturnsFalse() { + /*============================================================================================================================ + | TEST: IS DIRTY: MISSING KEY: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Confirms that calling with an invalid + /// key returns false. + /// + [Fact] + public void IsDirty_MissingKey_ReturnsFalse() { - var topic = new Topic("Test", "Container"); + var topic = new Topic("Test", "Container"); - Assert.False(topic.Attributes.IsDirty("MissingKey")); + Assert.False(topic.Attributes.IsDirty("MissingKey")); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: EXCLUDE LAST MODIFIED: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a that is not marked as . Updates the LastModified attributes, thus marking the collection as . Confirms that returns false. - /// - [Fact] - public void IsDirty_ExcludeLastModified_ReturnsFalse() { + /*============================================================================================================================ + | TEST: IS DIRTY: EXCLUDE LAST MODIFIED: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a that is not marked as . Updates the LastModified attributes, thus marking the collection as . Confirms that returns false. + /// + [Fact] + public void IsDirty_ExcludeLastModified_ReturnsFalse() { - var topic = new Topic("Test", "Container", null, 1); + var topic = new Topic("Test", "Container", null, 1); - topic.Attributes.SetValue("Foo", "Bar", false); - topic.Attributes.SetValue("LastModified", DateTime.Now.ToString(CultureInfo.InvariantCulture)); - topic.Attributes.SetValue("LastModifiedBy", "System"); + topic.Attributes.SetValue("Foo", "Bar", false); + topic.Attributes.SetValue("LastModified", DateTime.Now.ToString(CultureInfo.InvariantCulture)); + topic.Attributes.SetValue("LastModifiedBy", "System"); - Assert.True(topic.Attributes.IsDirty()); - Assert.False(topic.Attributes.IsDirty(true)); + Assert.True(topic.Attributes.IsDirty()); + Assert.False(topic.Attributes.IsDirty(true)); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: MARK CLEAN: UPDATES LAST MODIFIED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a and then deletes it. Confirms - /// that the returns the new version after calling . - /// - [Fact] - public void IsDirty_MarkClean_UpdatesLastModified() { - - var topic = new Topic("Test", "Container", null, 1); - var firstVersion = DateTime.Now.AddDays(5); - var secondVersion = DateTime.Now.AddDays(10); - var thirdVersion = DateTime.Now.AddDays(15); - - topic.Attributes.SetValue("Foo", "Qux", false, firstVersion); - topic.Attributes.SetValue("Bar", "Quux"); - topic.Attributes.SetValue("Baz", "Quuz"); - - topic.Attributes.MarkClean("Bar", secondVersion); - topic.Attributes.MarkClean(thirdVersion); - - topic.Attributes.TryGetValue("Foo", out var cleanedAttribute1); - topic.Attributes.TryGetValue("Bar", out var cleanedAttribute2); - topic.Attributes.TryGetValue("Baz", out var cleanedAttribute3); - - Assert.Equal(firstVersion, cleanedAttribute1?.LastModified); - Assert.Equal(secondVersion, cleanedAttribute2?.LastModified); - Assert.Equal(thirdVersion, cleanedAttribute3?.LastModified); + /*============================================================================================================================ + | TEST: IS DIRTY: MARK CLEAN: UPDATES LAST MODIFIED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a and then deletes it. Confirms + /// that the returns the new version after calling . + /// + [Fact] + public void IsDirty_MarkClean_UpdatesLastModified() { - } + var topic = new Topic("Test", "Container", null, 1); + var firstVersion = DateTime.Now.AddDays(5); + var secondVersion = DateTime.Now.AddDays(10); + var thirdVersion = DateTime.Now.AddDays(15); - /*========================================================================================================================== - | TEST: IS DIRTY: MARK CLEAN: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a and then deletes it. Confirms - /// that returns false after calling . - /// - [Fact] - public void IsDirty_MarkClean_ReturnsFalse() { + topic.Attributes.SetValue("Foo", "Qux", false, firstVersion); + topic.Attributes.SetValue("Bar", "Quux"); + topic.Attributes.SetValue("Baz", "Quuz"); - var topic = new Topic("Test", "Container", null, 1); + topic.Attributes.MarkClean("Bar", secondVersion); + topic.Attributes.MarkClean(thirdVersion); - topic.Attributes.SetValue("Foo", "Bar"); - topic.Attributes.SetValue("Baz", "Foo"); + topic.Attributes.TryGetValue("Foo", out var cleanedAttribute1); + topic.Attributes.TryGetValue("Bar", out var cleanedAttribute2); + topic.Attributes.TryGetValue("Baz", out var cleanedAttribute3); - topic.Attributes.Remove("Foo"); + Assert.Equal(firstVersion, cleanedAttribute1?.LastModified); + Assert.Equal(secondVersion, cleanedAttribute2?.LastModified); + Assert.Equal(thirdVersion, cleanedAttribute3?.LastModified); - topic.Attributes.MarkClean(); + } - Assert.False(topic.Attributes.IsDirty()); - Assert.Empty(topic.Attributes.DeletedItems); + /*============================================================================================================================ + | TEST: IS DIRTY: MARK CLEAN: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a and then deletes it. Confirms + /// that returns false after calling . + /// + [Fact] + public void IsDirty_MarkClean_ReturnsFalse() { - } + var topic = new Topic("Test", "Container", null, 1); - /*========================================================================================================================== - | TEST: IS DIRTY: MARK CLEAN: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an to a associated with a - /// that is . Confirms that returns true - /// even after calling since new - /// topics cannot be clean. - /// - [Fact] - public void IsDirty_MarkClean_ReturnsTrue() { + topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.SetValue("Baz", "Foo"); - var topic = new Topic("Test", "Container"); + topic.Attributes.Remove("Foo"); - topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.MarkClean(); - topic.Attributes.MarkClean("Foo"); + Assert.False(topic.Attributes.IsDirty()); + Assert.Empty(topic.Attributes.DeletedItems); - Assert.True(topic.Attributes.IsDirty("Foo")); + } - } + /*============================================================================================================================ + | TEST: IS DIRTY: MARK CLEAN: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an to a associated with a + /// that is . Confirms that returns true + /// even after calling since new + /// topics cannot be clean. + /// + [Fact] + public void IsDirty_MarkClean_ReturnsTrue() { - /*========================================================================================================================== - | TEST: IS DIRTY: MARK ATTRIBUTE CLEAN: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates the with a and then confirms that returns false for that attribute after - /// calling . - /// - [Fact] - public void IsDirty_MarkAttributeClean_ReturnsFalse() { + var topic = new Topic("Test", "Container"); - var topic = new Topic("Test", "Container", null, 1); + topic.Attributes.SetValue("Foo", "Bar"); - topic.Attributes.SetValue("Foo", "Bar"); - topic.Attributes.MarkClean("Foo"); + topic.Attributes.MarkClean("Foo"); - Assert.False(topic.Attributes.IsDirty("Foo")); + Assert.True(topic.Attributes.IsDirty("Foo")); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: ADD CLEAN ATTRIBUTE TO NEW TOPIC: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates a associated with an with a - /// that is not marked as and then confirms that returns true. - /// - [Fact] - public void IsDirty_AddCleanAttributeToNewTopic_ReturnsTrue() { - - var topic = new Topic("Test", "Container"); - - topic.Attributes.Add( - new() { - Key = "Foo", - Value = "Bar", - IsDirty = false - } - ); - - Assert.True(topic.Attributes.IsDirty()); + /*============================================================================================================================ + | TEST: IS DIRTY: MARK ATTRIBUTE CLEAN: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates the with a and then confirms that returns false for that attribute after + /// calling . + /// + [Fact] + public void IsDirty_MarkAttributeClean_ReturnsFalse() { - } + var topic = new Topic("Test", "Container", null, 1); - /*========================================================================================================================== - | TEST: IS DIRTY: MARK NEW TOPIC AS CLEAN: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Populates a associated with an with a - /// and then confirms that returns true for that attribute after calling . - /// - [Fact] - public void IsDirty_MarkNewTopicAsClean_ReturnsTrue() { + topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.MarkClean("Foo"); - var topic = new Topic("Test", "Container"); + Assert.False(topic.Attributes.IsDirty("Foo")); - topic.Attributes.SetValue("Foo", "Bar"); - topic.Attributes.MarkClean(); + } - Assert.True(topic.Attributes.IsDirty()); + /*============================================================================================================================ + | TEST: IS DIRTY: ADD CLEAN ATTRIBUTE TO NEW TOPIC: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates a associated with an with a + /// that is not marked as and then confirms that returns true. + /// + [Fact] + public void IsDirty_AddCleanAttributeToNewTopic_ReturnsTrue() { - } + var topic = new Topic("Test", "Container"); - /*========================================================================================================================== - | TEST: SET VALUE: INVALID VALUE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to violate the business logic by bypassing the property setter; ensures that business logic is enforced. - /// - [Fact] - public void SetValue_InvalidValue_ThrowsException() { + topic.Attributes.Add( + new() { + Key = "Foo", + Value = "Bar", + IsDirty = false + } + ); - var topic = new Topic("Test", "Container"); + Assert.True(topic.Attributes.IsDirty()); - Assert.Throws(() => - topic.Attributes.SetValue("View", "# ?") - ); + } - } + /*============================================================================================================================ + | TEST: IS DIRTY: MARK NEW TOPIC AS CLEAN: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Populates a associated with an with a + /// and then confirms that returns true for that attribute after calling . + /// + [Fact] + public void IsDirty_MarkNewTopicAsClean_ReturnsTrue() { - /*========================================================================================================================== - | TEST: SET VALUE: DUPLICATE VALUE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to insert a with the same as an existing - /// value, and confirms that the expected is thrown. - /// - [Fact] - public void SetValue_DuplicateValue_ThrowsException() { + var topic = new Topic("Test", "Container"); - var topic = new Topic("Test", "Container"); + topic.Attributes.SetValue("Foo", "Bar"); + topic.Attributes.MarkClean(); - topic.Attributes.Add(new("Test", "Original")); + Assert.True(topic.Attributes.IsDirty()); - Assert.Throws(() => - topic.Attributes.Add(new("Test", "New")) - ); + } - } + /*============================================================================================================================ + | TEST: SET VALUE: INVALID VALUE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to violate the business logic by bypassing the property setter; ensures that business logic is enforced. + /// + [Fact] + public void SetValue_InvalidValue_ThrowsException() { - /*========================================================================================================================== - | TEST: ADD: VALID ATTRIBUTE RECORD: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a custom attribute on a topic by directly adding an instance; ensures it can be - /// retrieved. - /// - [Fact] - public void Add_ValidAttributeRecord_IsReturned() { + var topic = new Topic("Test", "Container"); - var topic = new Topic("Test", "Container"); + Assert.Throws(() => + topic.Attributes.SetValue("View", "# ?") + ); - topic.Attributes.Add(new("View", "NewKey", false)); + } - Assert.Equal("NewKey", topic.View); + /*============================================================================================================================ + | TEST: SET VALUE: DUPLICATE VALUE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to insert a with the same as an existing + /// value, and confirms that the expected is thrown. + /// + [Fact] + public void SetValue_DuplicateValue_ThrowsException() { - } + var topic = new Topic("Test", "Container"); - /*========================================================================================================================== - | TEST: ADD: NUMERIC VALUE WITH BUSINESS LOGIC: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a numeric attribute on a topic instance; ensures it is routed through the corresponding property and correctly - /// retrieved. - /// - [Fact] - public void Add_NumericValueWithBusinessLogic_IsReturned() { + topic.Attributes.Add(new("Test", "Original")); - var topic = new CustomTopic("Test", "Page"); + Assert.Throws(() => + topic.Attributes.Add(new("Test", "New")) + ); - topic.Attributes.SetInteger("NumericAttribute", 1); + } - Assert.Equal(1, topic.NumericAttribute); + /*============================================================================================================================ + | TEST: ADD: VALID ATTRIBUTE RECORD: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a custom attribute on a topic by directly adding an instance; ensures it can be + /// retrieved. + /// + [Fact] + public void Add_ValidAttributeRecord_IsReturned() { - } + var topic = new Topic("Test", "Container"); + + topic.Attributes.Add(new("View", "NewKey", false)); + + Assert.Equal("NewKey", topic.View); + + } + + /*============================================================================================================================ + | TEST: ADD: NUMERIC VALUE WITH BUSINESS LOGIC: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a numeric attribute on a topic instance; ensures it is routed through the corresponding property and correctly + /// retrieved. + /// + [Fact] + public void Add_NumericValueWithBusinessLogic_IsReturned() { - /*========================================================================================================================== - | TEST: ADD: BOOLEAN VALUE WITH BUSINESS LOGIC: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a Boolean attribute on a topic instance; ensures it is routed through the corresponding property and correctly - /// retrieved. - /// - [Fact] - public void Add_BooleanValueWithBusinessLogic_IsReturned() { + var topic = new CustomTopic("Test", "Page"); - var topic = new CustomTopic("Test", "Page"); + topic.Attributes.SetInteger("NumericAttribute", 1); - topic.Attributes.SetBoolean("BooleanAttribute", true); + Assert.Equal(1, topic.NumericAttribute); - Assert.True(topic.BooleanAttribute); + } - } + /*============================================================================================================================ + | TEST: ADD: BOOLEAN VALUE WITH BUSINESS LOGIC: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a Boolean attribute on a topic instance; ensures it is routed through the corresponding property and correctly + /// retrieved. + /// + [Fact] + public void Add_BooleanValueWithBusinessLogic_IsReturned() { - /*========================================================================================================================== - | TEST: ADD: NUMERIC VALUE WITH BUSINESS LOGIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a numeric attribute on a topic instance with an invalid value; ensures an exception is thrown. - /// - [Fact] - public void Add_NumericValueWithBusinessLogic_ThrowsException() { + var topic = new CustomTopic("Test", "Page"); - var topic = new CustomTopic("Test", "Page"); + topic.Attributes.SetBoolean("BooleanAttribute", true); - Assert.Throws(() => - topic.Attributes.SetInteger("NumericAttribute", -1) - ); + Assert.True(topic.BooleanAttribute); - } + } - /*========================================================================================================================== - | TEST: ADD: DATE/TIME VALUE WITH BUSINESS LOGIC: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a Date/Time attribute on a topic instance; ensures it is routed through the corresponding property and correctly - /// retrieved. - /// - [Fact] - public void Add_DateTimeValueWithBusinessLogic_IsReturned() { + /*============================================================================================================================ + | TEST: ADD: NUMERIC VALUE WITH BUSINESS LOGIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a numeric attribute on a topic instance with an invalid value; ensures an exception is thrown. + /// + [Fact] + public void Add_NumericValueWithBusinessLogic_ThrowsException() { - var topic = new CustomTopic("Test", "Page"); - var dateTime = new DateTime(2021, 1, 5); + var topic = new CustomTopic("Test", "Page"); - topic.Attributes.SetDateTime("DateTimeAttribute", dateTime); + Assert.Throws(() => + topic.Attributes.SetInteger("NumericAttribute", -1) + ); - Assert.Equal(dateTime, topic.DateTimeAttribute); + } - } + /*============================================================================================================================ + | TEST: ADD: DATE/TIME VALUE WITH BUSINESS LOGIC: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a Date/Time attribute on a topic instance; ensures it is routed through the corresponding property and correctly + /// retrieved. + /// + [Fact] + public void Add_DateTimeValueWithBusinessLogic_IsReturned() { - /*========================================================================================================================== - | TEST: ADD: DATE/TIME VALUE WITH BUSINESS LOGIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a attribute on a topic instance with an invalid value; ensures an exception is thrown. - /// - [Fact] - public void Add_DateTimeValueWithBusinessLogic_ThrowsException() { + var topic = new CustomTopic("Test", "Page"); + var dateTime = new DateTime(2021, 1, 5); - var topic = new CustomTopic("Test", "Page"); + topic.Attributes.SetDateTime("DateTimeAttribute", dateTime); - Assert.Throws(() => - topic.Attributes.SetDateTime("DateTimeAttribute", DateTime.MinValue) - ); + Assert.Equal(dateTime, topic.DateTimeAttribute); - } + } - /*========================================================================================================================== - | TEST: ATTRIBUTE RECORD: LAST MODIFIED: DEFAULT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a new and ensures that the is set to - /// . - /// - [Fact] - public void AttributeRecord_LastModified_DefaultValue() { + /*============================================================================================================================ + | TEST: ADD: DATE/TIME VALUE WITH BUSINESS LOGIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a attribute on a topic instance with an invalid value; ensures an exception is thrown. + /// + [Fact] + public void Add_DateTimeValueWithBusinessLogic_ThrowsException() { - var beforeDate = DateTime.UtcNow; - var attribute = new AttributeRecord("Test", "Value"); - var afterDate = DateTime.UtcNow; + var topic = new CustomTopic("Test", "Page"); - Assert.True(attribute.LastModified > beforeDate); - Assert.True(attribute.LastModified < afterDate); + Assert.Throws(() => + topic.Attributes.SetDateTime("DateTimeAttribute", DateTime.MinValue) + ); - } + } + + /*============================================================================================================================ + | TEST: ATTRIBUTE RECORD: LAST MODIFIED: DEFAULT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a new and ensures that the is set to + /// . + /// + [Fact] + public void AttributeRecord_LastModified_DefaultValue() { - /*========================================================================================================================== - | TEST: SET VALUE: INSERT INVALID ATTRIBUTE RECORD: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to violate the business logic by bypassing entirely; ensures that business logic is enforced. - /// - [Fact] - public void Add_InvalidAttributeRecord_ThrowsException() { + var beforeDate = DateTime.UtcNow; + var attribute = new AttributeRecord("Test", "Value"); + var afterDate = DateTime.UtcNow; - var topic = new Topic("Test", "Container"); + Assert.True(attribute.LastModified >= beforeDate); + Assert.True(attribute.LastModified <= afterDate); - Assert.Throws(() => - topic.Attributes.Add(new("View", "# ?")) - ); + } - } + /*============================================================================================================================ + | TEST: SET VALUE: INSERT INVALID ATTRIBUTE RECORD: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to violate the business logic by bypassing entirely; ensures that business logic is enforced. + /// + [Fact] + public void Add_InvalidAttributeRecord_ThrowsException() { + + var topic = new Topic("Test", "Container"); + + Assert.Throws(() => + topic.Attributes.Add(new("View", "# ?")) + ); - /*========================================================================================================================== - | TEST: REPLACE VALUE: WITH BUSINESS LOGIC: MAINTAINS ISDIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new which maps to directly to a and confirms that the original is replaced if the changes. - /// - [Fact] - public void Add_WithBusinessLogic_MaintainsIsDirty() { + } - var topic = new Topic("Test", "Container", null, 1) { - View = "Test" - }; + /*============================================================================================================================ + | TEST: REPLACE VALUE: WITH BUSINESS LOGIC: MAINTAINS ISDIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new which maps to directly to a and confirms that the original is replaced if the changes. + /// + [Fact] + public void Add_WithBusinessLogic_MaintainsIsDirty() { - topic.Attributes.TryGetValue("View", out var originalValue); + var topic = new Topic("Test", "Container", null, 1) { + View = "Test" + }; - Contract.Assume(originalValue); + topic.Attributes.TryGetValue("View", out var originalValue); - var index = topic.Attributes.IndexOf(originalValue); + Contract.Assume(originalValue); - topic.Attributes[index] = new AttributeRecord("View", "NewValue", false); - topic.Attributes.TryGetValue("View", out var newAttribute); + var index = topic.Attributes.IndexOf(originalValue); - topic.Attributes.SetValue("View", "NewerValue", false); - topic.Attributes.TryGetValue("View", out var newerAttribute); + topic.Attributes[index] = new AttributeRecord("View", "NewValue", false); + topic.Attributes.TryGetValue("View", out var newAttribute); - Assert.False(newAttribute?.IsDirty); - Assert.False(newerAttribute?.IsDirty); + topic.Attributes.SetValue("View", "NewerValue", false); + topic.Attributes.TryGetValue("View", out var newerAttribute); - } + Assert.False(newAttribute?.IsDirty); + Assert.False(newerAttribute?.IsDirty); - /*========================================================================================================================== - | TEST: SET VALUE: EMPTY ATTRIBUTE RECORD: SKIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new attribute with an empty value, and confirms that it is not added as a new . Empty values are treated as the same as non-existent attributes. They are stored for the sake of tracking - /// deleted attributes, but should not be stored for new attributes. - /// - [Fact] - public void SetValue_EmptyAttributeRecord_Skips() { + } - var topic = new Topic("Test", "Container"); + /*============================================================================================================================ + | TEST: SET VALUE: EMPTY ATTRIBUTE RECORD: SKIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new attribute with an empty value, and confirms that it is not added as a new . Empty values are treated as the same as non-existent attributes. They are stored for the sake of tracking + /// deleted attributes, but should not be stored for new attributes. + /// + [Fact] + public void SetValue_EmptyAttributeRecord_Skips() { - topic.Attributes.SetValue("Attribute", ""); + var topic = new Topic("Test", "Container"); - Assert.False(topic.Attributes.Contains("Attribute")); + topic.Attributes.SetValue("Attribute", ""); - } + Assert.False(topic.Attributes.Contains("Attribute")); - /*========================================================================================================================== - | TEST: SET VALUE: UPDATE EMPTY ATTRIBUTE RECORD: REPLACES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new attribute with an empty value, and confirms that it is is added as a new assuming the value previously existed. Empty values are treated as the same as non-existent attributes, but they - /// should be stored for the sake of tracking deleted attributes. - /// - [Fact] - public void SetValue_EmptyAttributeRecord_Replaces() { + } - var topic = new Topic("Test", "Container"); + /*============================================================================================================================ + | TEST: SET VALUE: UPDATE EMPTY ATTRIBUTE RECORD: REPLACES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new attribute with an empty value, and confirms that it is is added as a new assuming the value previously existed. Empty values are treated as the same as non-existent attributes, but they + /// should be stored for the sake of tracking deleted attributes. + /// + [Fact] + public void SetValue_EmptyAttributeRecord_Replaces() { - topic.Attributes.SetValue("Attribute", "New Value"); - topic.Attributes.SetValue("Attribute", ""); + var topic = new Topic("Test", "Container"); - Assert.True(topic.Attributes.Contains("Attribute")); + topic.Attributes.SetValue("Attribute", "New Value"); + topic.Attributes.SetValue("Attribute", ""); - } + Assert.True(topic.Attributes.Contains("Attribute")); - /*========================================================================================================================== - | TEST: GET VALUE: INHERIT FROM PARENT: RETURNS PARENT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets an attribute on the parent of a topic and ensures it can be retrieved using inheritance. - /// - [Fact] - public void GetValue_InheritFromParent_ReturnsParentValue() { - - var topics = new Topic[8]; - - for (var i = 0; i <= 7; i++) { - var topic = new Topic("Topic" + i, "Container"); - if (i > 0) topic.Parent = topics[i - 1]; - topics[i] = topic; - } + } - topics[0].Attributes.SetValue("Foo", "Bar"); + /*============================================================================================================================ + | TEST: GET VALUE: INHERIT FROM PARENT: RETURNS PARENT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets an attribute on the parent of a topic and ensures it can be retrieved using inheritance. + /// + [Fact] + public void GetValue_InheritFromParent_ReturnsParentValue() { - Assert.Null(topics[4].Attributes.GetValue("Foo", null)); - Assert.Equal("Bar", topics[7].Attributes.GetValue("Foo", true)); - Assert.NotEqual("Bar", topics[7].Attributes.GetValue("Foo", false)); + var topics = new Topic[8]; + for (var i = 0; i <= 7; i++) { + var topic = new Topic("Topic" + i, "Container"); + if (i > 0) topic.Parent = topics[i - 1]; + topics[i] = topic; } - /*========================================================================================================================== - | TEST: GET VALUE: INHERIT FROM BASE: RETURNS INHERITED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a long tree of derived topics, and ensures that the inherited value is returned. - /// - [Fact] - public void GetValue_InheritFromBase_ReturnsInheritedValue() { - - var topics = new Topic[5]; - - for (var i = 0; i <= 4; i++) { - var topic = new Topic("Topic" + i, "Container"); - if (i > 0) topics[i - 1].BaseTopic = topic; - topics[i] = topic; - } + topics[0].Attributes.SetValue("Foo", "Bar"); - topics[4].Attributes.SetValue("Foo", "Bar"); + Assert.Null(topics[4].Attributes.GetValue("Foo", null)); + Assert.Equal("Bar", topics[7].Attributes.GetValue("Foo", true)); + Assert.NotEqual("Bar", topics[7].Attributes.GetValue("Foo", false)); - Assert.Equal("Bar", topics[0].Attributes.GetValue("Foo", null, true, true)); + } + /*============================================================================================================================ + | TEST: GET VALUE: INHERIT FROM BASE: RETURNS INHERITED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a long tree of derived topics, and ensures that the inherited value is returned. + /// + [Fact] + public void GetValue_InheritFromBase_ReturnsInheritedValue() { + + var topics = new Topic[5]; + + for (var i = 0; i <= 4; i++) { + var topic = new Topic("Topic" + i, "Container"); + if (i > 0) topics[i - 1].BaseTopic = topic; + topics[i] = topic; } - /*========================================================================================================================== - | TEST: GET VALUE: EXCEEDS MAX HOPS: RETURNS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a long tree of derives topics, and ensures that inheritance will pursue no more than five hops. - /// - [Fact] - public void GetValue_ExceedsMaxHops_ReturnsDefault() { - - var topics = new Topic[8]; - - for (var i = 0; i <= 7; i++) { - var topic = new Topic("Topic" + i, "Container"); - if (i > 0) topics[i - 1].BaseTopic = topic; - topics[i] = topic; - } + topics[4].Attributes.SetValue("Foo", "Bar"); - topics[7].Attributes.SetValue("Foo", "Bar"); + Assert.Equal("Bar", topics[0].Attributes.GetValue("Foo", null, true, true)); - Assert.Null(topics[0].Attributes.GetValue("Foo", null, true, true)); + } + /*============================================================================================================================ + | TEST: GET VALUE: EXCEEDS MAX HOPS: RETURNS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a long tree of derives topics, and ensures that inheritance will pursue no more than five hops. + /// + [Fact] + public void GetValue_ExceedsMaxHops_ReturnsDefault() { + + var topics = new Topic[8]; + + for (var i = 0; i <= 7; i++) { + var topic = new Topic("Topic" + i, "Container"); + if (i > 0) topics[i - 1].BaseTopic = topic; + topics[i] = topic; } - } //Class -} //Namespace \ No newline at end of file + topics[7].Attributes.SetValue("Foo", "Bar"); + + Assert.Null(topics[0].Attributes.GetValue("Foo", null, true, true)); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/AttributeDictionaryTest.cs b/OnTopic.Tests/AttributeDictionaryTest.cs index 5df95d71..a8e5539a 100644 --- a/OnTopic.Tests/AttributeDictionaryTest.cs +++ b/OnTopic.Tests/AttributeDictionaryTest.cs @@ -5,224 +5,223 @@ \=============================================================================================================================*/ using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE DICTIONARY TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AttributeDictionaryTest { + + /*============================================================================================================================ + | TEST: GET VALUE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a based on the data and confirms that returns the value. + /// + /// The value to add to the dictionary. + /// The value expected to be returned. + [Theory] + [InlineData(null, null)] + [InlineData("", null)] + [InlineData(" ", null)] + [InlineData("0", "0")] + [InlineData("True", "True")] + [InlineData("Hello", "Hello")] + public void GetValue_ReturnsExpectedValue(string? input, string? expected) { + + var attributes = new AttributeDictionary() {{"Key", input}}; + + Assert.Equal(expected, attributes.GetValue("Key")); + + } /*============================================================================================================================ - | CLASS: ATTRIBUTE DICTIONARY TEST + | TEST: GET BOOLEAN: RETURNS EXPECTED VALUE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Constructs a based on the data and confirms that returns the value. /// - [ExcludeFromCodeCoverage] - public class AttributeDictionaryTest { - - /*========================================================================================================================== - | TEST: GET VALUE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the data and confirms that returns the value. - /// - /// The value to add to the dictionary. - /// The value expected to be returned. - [Theory] - [InlineData(null, null)] - [InlineData("", null)] - [InlineData(" ", null)] - [InlineData("0", "0")] - [InlineData("True", "True")] - [InlineData("Hello", "Hello")] - public void GetValue_ReturnsExpectedValue(string? input, string? expected) { - - var attributes = new AttributeDictionary() {{"Key", input}}; - - Assert.Equal(expected, attributes.GetValue("Key")); - - } - - /*========================================================================================================================== - | TEST: GET BOOLEAN: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the data and confirms that returns the value. - /// - /// The value to add to the dictionary. - /// The value expected to be returned. - [Theory] - [InlineData("0", false)] - [InlineData("1", true)] - [InlineData("False", false)] - [InlineData("True", true)] - [InlineData("", null)] - [InlineData("Hello", null)] - public void GetBoolean_ReturnsExpectedValue(string input, bool? expected) { - - var attributes = new AttributeDictionary() {{"Key", input}}; - - Assert.Equal(expected, attributes.GetBoolean("Key")); - - } - - /*========================================================================================================================== - | TEST: GET INTEGER: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the data and confirms that returns the value. - /// - /// The value to add to the dictionary. - /// The value expected to be returned. - [Theory] - [InlineData("0", 0)] - [InlineData("1", 1)] - [InlineData("2.4", null)] - [InlineData("", null)] - [InlineData("Hello", null)] - public void GetInteger_ReturnsExpectedValue(string input, int? expected) { - - var attributes = new AttributeDictionary() {{"Key", input}}; - - Assert.Equal(expected, attributes.GetInteger("Key")); - - } - - /*========================================================================================================================== - | TEST: GET DOUBLE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the data and confirms that returns the value. - /// - /// The value to add to the dictionary. - /// The value expected to be returned. - [Theory] - [InlineData("0.0", 0.0)] - [InlineData("1.0", 1.0)] - [InlineData("1", 1.0)] - [InlineData("1.4", 1.4)] - [InlineData("", null)] - [InlineData("Hello", null)] - public void GetDouble_ReturnsExpectedValue(string input, double? expected) { - - var attributes = new AttributeDictionary() {{"Key", input}}; - - Assert.Equal(expected, attributes.GetDouble("Key")); - - } - - /*========================================================================================================================== - | TEST: GET DATE/TIME: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the data and confirms that returns the expected value. - /// - /// The value to add to the dictionary. - /// Determines whether a valid is expected in response. - [Theory] - [InlineData("1976-10-15 01:02:03", true)] - [InlineData("October 15, 1976 01:02:03 AM", true)] - [InlineData("15 Oct 1976 01:02:03", true)] - [InlineData("10/15/1976 01:02:03 AM", true)] - [InlineData("", false)] - [InlineData("Hello", false)] - public void GetDate_ReturnsExpectedValue(string input, bool isSet) { - - var attributes = new AttributeDictionary() {{"Key", input}}; - - Assert.Equal(isSet? new DateTime(1976, 10, 15, 1, 2, 3) : null, attributes.GetDateTime("Key")); - - } - - /*========================================================================================================================== - | TEST: GET URI: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the data and confirms that returns the expected value. - /// - /// The value to add to the dictionary. - [Theory] - [InlineData("https://www.github.com/OnTopicCMS")] - [InlineData("Some:\\\\URL")] - public void GetUri_ReturnsExpectedValue(string input) { - - var attributes = new AttributeDictionary() {{"Key", input}}; - - Assert.Equal(new Uri(input), attributes.GetUri("Key")); - - } - - /*========================================================================================================================== - | TEST: GET {TYPE}: INVALID KEY: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a and confirms that each of the methods return null if an invalid key is passed. - /// - [Fact] - public void GetType_InvalidKey_ReturnsNull() { - - var attributes = new AttributeDictionary(); - - Assert.Null(attributes.GetValue("MissingKey")); - Assert.Null(attributes.GetBoolean("MissingKey")); - Assert.Null(attributes.GetInteger("MissingKey")); - Assert.Null(attributes.GetDouble("MissingKey")); - Assert.Null(attributes.GetDateTime("MissingKey")); - Assert.Null(attributes.GetUri("MissingKey")); - - } - - /*========================================================================================================================== - | TEST: AS ATTRIBUTE DICTIONARY: EXCLUDED KEYS: EXCLUDED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a using - /// and confirms that doesn't include the excluded values. - /// - [Fact] - public void AsAttributeDictionary_ExcludedKeys_Excluded() { - - var topic = new Topic("Test", "Page"); - - topic.Attributes.SetValue("Title", "Page Title"); - topic.Attributes.SetValue("LastModified", "October 15, 1976"); - topic.Attributes.SetValue("Subtitle", "Subtitle"); - - var attributes = topic.Attributes.AsAttributeDictionary(); - - Assert.Single(attributes.Keys); - Assert.Null(attributes.GetValue("Title")); - Assert.Null(attributes.GetValue("LastModified")); - Assert.Equal("Subtitle", attributes.GetValue("Subtitle")); - - } - - /*========================================================================================================================== - | TEST: AS ATTRIBUTE DICTIONARY: INHERIT FROM BASE: INHERITS VALUES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a using - /// and confirms that correctly inherits values. - /// - [Fact] - public void AsAttributeDictionary_InheritFromBase_InheritsValues() { - - var baseTopic = new Topic("BaseTopic", "Page"); - var topic = new Topic("Test", "Page") { - BaseTopic = baseTopic - }; - - baseTopic.Attributes.SetValue("Subtitle", "Subtitle"); - - var attributes = topic.Attributes.AsAttributeDictionary(true); - - Assert.Single(attributes.Keys); - Assert.Equal("Subtitle", attributes.GetValue("Subtitle")); - - } - - } //Class -} //Namespace \ No newline at end of file + /// The value to add to the dictionary. + /// The value expected to be returned. + [Theory] + [InlineData("0", false)] + [InlineData("1", true)] + [InlineData("False", false)] + [InlineData("True", true)] + [InlineData("", null)] + [InlineData("Hello", null)] + public void GetBoolean_ReturnsExpectedValue(string input, bool? expected) { + + var attributes = new AttributeDictionary() {{"Key", input}}; + + Assert.Equal(expected, attributes.GetBoolean("Key")); + + } + + /*============================================================================================================================ + | TEST: GET INTEGER: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a based on the data and confirms that returns the value. + /// + /// The value to add to the dictionary. + /// The value expected to be returned. + [Theory] + [InlineData("0", 0)] + [InlineData("1", 1)] + [InlineData("2.4", null)] + [InlineData("", null)] + [InlineData("Hello", null)] + public void GetInteger_ReturnsExpectedValue(string input, int? expected) { + + var attributes = new AttributeDictionary() {{"Key", input}}; + + Assert.Equal(expected, attributes.GetInteger("Key")); + + } + + /*============================================================================================================================ + | TEST: GET DOUBLE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a based on the data and confirms that returns the value. + /// + /// The value to add to the dictionary. + /// The value expected to be returned. + [Theory] + [InlineData("0.0", 0.0)] + [InlineData("1.0", 1.0)] + [InlineData("1", 1.0)] + [InlineData("1.4", 1.4)] + [InlineData("", null)] + [InlineData("Hello", null)] + public void GetDouble_ReturnsExpectedValue(string input, double? expected) { + + var attributes = new AttributeDictionary() {{"Key", input}}; + + Assert.Equal(expected, attributes.GetDouble("Key")); + + } + + /*============================================================================================================================ + | TEST: GET DATE/TIME: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a based on the data and confirms that returns the expected value. + /// + /// The value to add to the dictionary. + /// Determines whether a valid is expected in response. + [Theory] + [InlineData("1976-10-15 01:02:03", true)] + [InlineData("October 15, 1976 01:02:03 AM", true)] + [InlineData("15 Oct 1976 01:02:03", true)] + [InlineData("10/15/1976 01:02:03 AM", true)] + [InlineData("", false)] + [InlineData("Hello", false)] + public void GetDate_ReturnsExpectedValue(string input, bool isSet) { + + var attributes = new AttributeDictionary() {{"Key", input}}; + + Assert.Equal(isSet? new DateTime(1976, 10, 15, 1, 2, 3) : null, attributes.GetDateTime("Key")); + + } + + /*============================================================================================================================ + | TEST: GET URI: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a based on the data and confirms that returns the expected value. + /// + /// The value to add to the dictionary. + [Theory] + [InlineData("https://www.github.com/OnTopicCMS")] + [InlineData("Some:\\\\URL")] + public void GetUri_ReturnsExpectedValue(string input) { + + var attributes = new AttributeDictionary() {{"Key", input}}; + + Assert.Equal(new Uri(input), attributes.GetUri("Key")); + + } + + /*============================================================================================================================ + | TEST: GET {TYPE}: INVALID KEY: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a and confirms that each of the methods return null if an invalid key is passed. + /// + [Fact] + public void GetType_InvalidKey_ReturnsNull() { + + var attributes = new AttributeDictionary(); + + Assert.Null(attributes.GetValue("MissingKey")); + Assert.Null(attributes.GetBoolean("MissingKey")); + Assert.Null(attributes.GetInteger("MissingKey")); + Assert.Null(attributes.GetDouble("MissingKey")); + Assert.Null(attributes.GetDateTime("MissingKey")); + Assert.Null(attributes.GetUri("MissingKey")); + + } + + /*============================================================================================================================ + | TEST: AS ATTRIBUTE DICTIONARY: EXCLUDED KEYS: EXCLUDED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a using + /// and confirms that doesn't include the excluded values. + /// + [Fact] + public void AsAttributeDictionary_ExcludedKeys_Excluded() { + + var topic = new Topic("Test", "Page"); + + topic.Attributes.SetValue("Title", "Page Title"); + topic.Attributes.SetValue("LastModified", "October 15, 1976"); + topic.Attributes.SetValue("Subtitle", "Subtitle"); + + var attributes = topic.Attributes.AsAttributeDictionary(); + + Assert.Single(attributes.Keys); + Assert.Null(attributes.GetValue("Title")); + Assert.Null(attributes.GetValue("LastModified")); + Assert.Equal("Subtitle", attributes.GetValue("Subtitle")); + + } + + /*============================================================================================================================ + | TEST: AS ATTRIBUTE DICTIONARY: INHERIT FROM BASE: INHERITS VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a using + /// and confirms that correctly inherits values. + /// + [Fact] + public void AsAttributeDictionary_InheritFromBase_InheritsValues() { + + var baseTopic = new Topic("BaseTopic", "Page"); + var topic = new Topic("Test", "Page") { + BaseTopic = baseTopic + }; + + baseTopic.Attributes.SetValue("Subtitle", "Subtitle"); + + var attributes = topic.Attributes.AsAttributeDictionary(true); + + Assert.Single(attributes.Keys); + Assert.Equal("Subtitle", attributes.GetValue("Subtitle")); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/AttributeValueConverterTest.cs b/OnTopic.Tests/AttributeValueConverterTest.cs index 028b80a0..c8db7cce 100644 --- a/OnTopic.Tests/AttributeValueConverterTest.cs +++ b/OnTopic.Tests/AttributeValueConverterTest.cs @@ -5,150 +5,149 @@ \=============================================================================================================================*/ using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE VALUE CONVERTER TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AttributeValueConverterTest { /*============================================================================================================================ - | CLASS: ATTRIBUTE VALUE CONVERTER TEST + | TEST: IS CONVERTIBLE? TYPE: RETURNS EXPECTED \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Passes a into the method and + /// confirms that result matches the . + /// true /// - [ExcludeFromCodeCoverage] - public class AttributeValueConverterTest { - - /*========================================================================================================================== - | TEST: IS CONVERTIBLE? TYPE: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes a into the method and - /// confirms that result matches the . - /// true - /// - [Theory] - [InlineData( typeof(string), true)] - [InlineData( typeof(int), true)] - [InlineData( typeof(bool), true)] - [InlineData( typeof(DateTime), true)] - [InlineData( typeof(Uri), true)] - [InlineData( typeof(int?), true)] - [InlineData( typeof(bool?), true)] - [InlineData( typeof(DateTime?), true)] - [InlineData( typeof(object), false)] - public void IsConvertible_Type_ReturnsExpected(Type type, bool result) => - Assert.True(AttributeValueConverter.IsConvertible(type) == result); + [Theory] + [InlineData( typeof(string), true)] + [InlineData( typeof(int), true)] + [InlineData( typeof(bool), true)] + [InlineData( typeof(DateTime), true)] + [InlineData( typeof(Uri), true)] + [InlineData( typeof(int?), true)] + [InlineData( typeof(bool?), true)] + [InlineData( typeof(DateTime?), true)] + [InlineData( typeof(object), false)] + public void IsConvertible_Type_ReturnsExpected(Type type, bool result) => + Assert.True(AttributeValueConverter.IsConvertible(type) == result); - /*========================================================================================================================== - | TEST: CONVERT: FROM STRING VALUE: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes a valid into based on a - /// and confirms that the result matches the . - /// - [Theory] - [InlineData( typeof(string), "String", "String")] - [InlineData( typeof(int), "1", 1)] - [InlineData( typeof(bool), "1", true)] - [InlineData( typeof(bool), "0", false)] - [InlineData( typeof(bool), "true", true)] - [InlineData( typeof(bool), "false", false)] - [InlineData( typeof(string), "", "")] - [InlineData( typeof(string), null, null)] - [InlineData( typeof(int?), "", null)] - [InlineData( typeof(bool?), "", null)] - [InlineData( typeof(DateTime?), "", null)] - [InlineData( typeof(object), "Value", null)] - public void Convert_FromStringValue_Succeeds(Type type, string? input, object? expected) => - Assert.Equal(expected, AttributeValueConverter.Convert(input, type)); + /*============================================================================================================================ + | TEST: CONVERT: FROM STRING VALUE: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Passes a valid into based on a + /// and confirms that the result matches the . + /// + [Theory] + [InlineData( typeof(string), "String", "String")] + [InlineData( typeof(int), "1", 1)] + [InlineData( typeof(bool), "1", true)] + [InlineData( typeof(bool), "0", false)] + [InlineData( typeof(bool), "true", true)] + [InlineData( typeof(bool), "false", false)] + [InlineData( typeof(string), "", "")] + [InlineData( typeof(string), null, null)] + [InlineData( typeof(int?), "", null)] + [InlineData( typeof(bool?), "", null)] + [InlineData( typeof(DateTime?), "", null)] + [InlineData( typeof(object), "Value", null)] + public void Convert_FromStringValue_Succeeds(Type type, string? input, object? expected) => + Assert.Equal(expected, AttributeValueConverter.Convert(input, type)); - /*========================================================================================================================== - | TEST: CONVERT: TO DATE/TIME: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes a valid valid string into - /// and confirms that the result matches the expected value. - /// - [Theory] - [InlineData( "1976-10-15 01:02:03")] - [InlineData( "October 15, 1976 01:02:03 AM")] - [InlineData( "15 Oct 1976 01:02:03")] - [InlineData( "10/15/1976 01:02:03 AM")] - public void Convert_ToDateTime_Succeeds(string? input) => - Assert.Equal(new DateTime(1976, 10, 15, 1, 2, 3), AttributeValueConverter.Convert(input, typeof(DateTime))); + /*============================================================================================================================ + | TEST: CONVERT: TO DATE/TIME: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Passes a valid valid string into + /// and confirms that the result matches the expected value. + /// + [Theory] + [InlineData( "1976-10-15 01:02:03")] + [InlineData( "October 15, 1976 01:02:03 AM")] + [InlineData( "15 Oct 1976 01:02:03")] + [InlineData( "10/15/1976 01:02:03 AM")] + public void Convert_ToDateTime_Succeeds(string? input) => + Assert.Equal(new DateTime(1976, 10, 15, 1, 2, 3), AttributeValueConverter.Convert(input)); - /*========================================================================================================================== - | TEST: CONVERT: TO URI: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes a valid input string into and confirms that the - /// result matches the expected value. - /// - [Fact] - public void Convert_ToUri_Succeeds() { - Assert.Equal("/OnTopicCMS/", ((Uri?)AttributeValueConverter.Convert("https://www.github.com/OnTopicCMS/", typeof(Uri)))?.LocalPath); - Assert.False(((Uri?)AttributeValueConverter.Convert("/OnTopicCMS/", typeof(Uri)))?.IsAbsoluteUri); - } + /*============================================================================================================================ + | TEST: CONVERT: TO URI: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Passes a valid input string into and confirms that the + /// result matches the expected value. + /// + [Fact] + public void Convert_ToUri_Succeeds() { + Assert.Equal("/OnTopicCMS/", AttributeValueConverter.Convert("https://www.github.com/OnTopicCMS/")?.LocalPath); + Assert.False(AttributeValueConverter.Convert("/OnTopicCMS/")?.IsAbsoluteUri); + } - /*========================================================================================================================== - | TEST: CONVERT: FROM STRING VALUE: FAILS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes an invalid value into based on a and confirms that the result is null. - /// - [Theory] - [InlineData( typeof(int))] - [InlineData( typeof(bool))] - [InlineData( typeof(DateTime))] - [InlineData( typeof(int?))] - [InlineData( typeof(bool?))] - [InlineData( typeof(DateTime?))] - [InlineData( typeof(object))] - public void Convert_FromString_Fails(Type type) => - Assert.Null(AttributeValueConverter.Convert("ABC", type)); + /*============================================================================================================================ + | TEST: CONVERT: FROM STRING VALUE: FAILS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Passes an invalid value into based on a and confirms that the result is null. + /// + [Theory] + [InlineData( typeof(int))] + [InlineData( typeof(bool))] + [InlineData( typeof(DateTime))] + [InlineData( typeof(int?))] + [InlineData( typeof(bool?))] + [InlineData( typeof(DateTime?))] + [InlineData( typeof(object))] + public void Convert_FromString_Fails(Type type) => + Assert.Null(AttributeValueConverter.Convert("ABC", type)); - /*========================================================================================================================== - | TEST: CONVERT: FROM VALUE TYPE: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes a valid into and confirms that - /// the result matches the string. - /// - [Theory] - [InlineData( "String", "String")] - [InlineData( true, "1")] - [InlineData( false, "0")] - [InlineData( 1, "1")] - [InlineData( null, null)] - [InlineData( typeof(string), "System.String")] - public void Convert_FromValueType_Succeeds(object input, string? expected) => - Assert.Equal(expected, AttributeValueConverter.Convert(input)); + /*============================================================================================================================ + | TEST: CONVERT: FROM VALUE TYPE: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Passes a valid into and confirms that + /// the result matches the string. + /// + [Theory] + [InlineData( "String", "String")] + [InlineData( true, "1")] + [InlineData( false, "0")] + [InlineData( 1, "1")] + [InlineData( null, null)] + [InlineData( typeof(string), "System.String")] + public void Convert_FromValueType_Succeeds(object? input, string? expected) => + Assert.Equal(expected, AttributeValueConverter.Convert(input)); - /*========================================================================================================================== - | TEST: CONVERT: FROM DATE/TIME: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Passes a valid valid to and confirms the - /// result matches the expected value. - /// - [Fact] - public void Convert_FromDateTime_Succeeds() => - Assert.Equal("10/15/1976 01:02:03", AttributeValueConverter.Convert(new DateTime(1976, 10, 15, 1, 2, 3))); + /*============================================================================================================================ + | TEST: CONVERT: FROM DATE/TIME: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Passes a valid valid to and confirms the + /// result matches the expected value. + /// + [Fact] + public void Convert_FromDateTime_Succeeds() => + Assert.Equal("10/15/1976 01:02:03", AttributeValueConverter.Convert(new DateTime(1976, 10, 15, 1, 2, 3))); - /*========================================================================================================================== - | TEST: CONVERT: FROM URI: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a based on the and confirms returns the expected value. - /// - [Theory] - [InlineData( "https://www.github.com/OnTopicCMS")] - [InlineData( "https://github.com/OnTopicCMS/OnTopic-Library/issues?q=is%3Aopen+is%3Aissue+no%3Amilestone")] - [InlineData( "/OnTopicCMS/")] - public void Convert_FromUri_Succeeds(string input) => - Assert.Equal(input, AttributeValueConverter.Convert(new Uri(input, UriKind.RelativeOrAbsolute))); + /*============================================================================================================================ + | TEST: CONVERT: FROM URI: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a based on the and confirms returns the expected value. + /// + [Theory] + [InlineData( "https://www.github.com/OnTopicCMS")] + [InlineData( "https://github.com/OnTopicCMS/OnTopic-Library/issues?q=is%3Aopen+is%3Aissue+no%3Amilestone")] + [InlineData( "/OnTopicCMS/")] + public void Convert_FromUri_Succeeds(string input) => + Assert.Equal(input, AttributeValueConverter.Convert(new Uri(input, UriKind.RelativeOrAbsolute))); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/AttributeDescriptorTopicBindingModel.cs b/OnTopic.Tests/BindingModels/AttributeDescriptorTopicBindingModel.cs index fd4449d1..aaa03b6f 100644 --- a/OnTopic.Tests/BindingModels/AttributeDescriptorTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/AttributeDescriptorTopicBindingModel.cs @@ -5,27 +5,26 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: ATTRIBUTE DESCRIPTOR TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with a couple of scalar values mapping to properties - /// on the content type. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class AttributeDescriptorTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: ATTRIBUTE DESCRIPTOR TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with a couple of scalar values mapping to properties +/// on the content type. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class AttributeDescriptorTopicBindingModel : BasicTopicBindingModel { - public AttributeDescriptorTopicBindingModel(string key, string attributeType) : base(key, attributeType) { } + public AttributeDescriptorTopicBindingModel(string key, string attributeType) : base(key, attributeType) { } - public string? Title { get; set; } + public string? Title { get; set; } - public string? DefaultValue { get; set; } + public string? DefaultValue { get; set; } - public bool IsRequired { get; set; } + public bool IsRequired { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/BasicTopicBindingModel.cs b/OnTopic.Tests/BindingModels/BasicTopicBindingModel.cs index f3be7bd0..03d94e48 100644 --- a/OnTopic.Tests/BindingModels/BasicTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/BasicTopicBindingModel.cs @@ -6,31 +6,30 @@ using System.ComponentModel.DataAnnotations; using OnTopic.Models; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | VIEW MODEL: DEFAULT VALUE TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views properties annotated with default value attributes. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class BasicTopicBindingModel : ITopicBindingModel { +/*============================================================================================================================== +| VIEW MODEL: DEFAULT VALUE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views properties annotated with default value attributes. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class BasicTopicBindingModel : ITopicBindingModel { - public BasicTopicBindingModel() { } + public BasicTopicBindingModel() { } - public BasicTopicBindingModel(string key, string contentType) { - Key = key; - ContentType = contentType; - } + public BasicTopicBindingModel(string key, string contentType) { + Key = key; + ContentType = contentType; + } - [Required] - public string Key { get; init; } = default!; + [Required] + public string Key { get; init; } = default!; - [Required] - public string ContentType { get; init; } = default!; + [Required] + public string ContentType { get; init; } = default!; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/ContactTopicBindingModel.cs b/OnTopic.Tests/BindingModels/ContactTopicBindingModel.cs index 0236ffc4..f83461b6 100644 --- a/OnTopic.Tests/BindingModels/ContactTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/ContactTopicBindingModel.cs @@ -4,21 +4,20 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: CONTACT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with a single property intended to be called from - /// . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ContactTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: CONTACT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with a single property intended to be called from +/// . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ContactTopicBindingModel { - public string? Name { get; set; } + public string? Name { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/ContentTypeDescriptorTopicBindingModel.cs b/OnTopic.Tests/BindingModels/ContentTypeDescriptorTopicBindingModel.cs index da463089..5716ab81 100644 --- a/OnTopic.Tests/BindingModels/ContentTypeDescriptorTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/ContentTypeDescriptorTopicBindingModel.cs @@ -5,24 +5,23 @@ \=============================================================================================================================*/ using OnTopic.ViewModels.BindingModels; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: CONTENT TYPE DESCRIPTOR TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with a relationship property. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ContentTypeDescriptorTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: CONTENT TYPE DESCRIPTOR TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with a relationship property. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ContentTypeDescriptorTopicBindingModel : BasicTopicBindingModel { - public ContentTypeDescriptorTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } + public ContentTypeDescriptorTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } - public Collection ContentTypes { get; } = new(); + public Collection ContentTypes { get; } = new(); - public Collection Attributes { get; } = new(); + public Collection Attributes { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/DisabledAttributeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/DisabledAttributeTopicBindingModel.cs index b2c49135..9f6ca3aa 100644 --- a/OnTopic.Tests/BindingModels/DisabledAttributeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/DisabledAttributeTopicBindingModel.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: DISABLED ATTRIBUTE TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid property—i.e., one that doesn't map to a valid attribute. It is, - /// however, decorated with the and, thus, should simply be ignored, instead of - /// throwing an . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class DisabledAttributeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: DISABLED ATTRIBUTE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid property—i.e., one that doesn't map to a valid attribute. It is, +/// however, decorated with the and, thus, should simply be ignored, instead of +/// throwing an . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class DisabledAttributeTopicBindingModel : BasicTopicBindingModel { - public DisabledAttributeTopicBindingModel(string key) : base(key, "Page") { } + public DisabledAttributeTopicBindingModel(string key) : base(key, "Page") { } - [DisableMapping] - public string? UnmappedAttribute { get; set; } + [DisableMapping] + public string? UnmappedAttribute { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/EmailTopicBindingModel.cs b/OnTopic.Tests/BindingModels/EmailTopicBindingModel.cs index d63dd800..6519b87b 100644 --- a/OnTopic.Tests/BindingModels/EmailTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/EmailTopicBindingModel.cs @@ -4,21 +4,20 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: EMAIL - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with a single property intended to be called from - /// . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class EmailTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: EMAIL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with a single property intended to be called from +/// . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class EmailTopicBindingModel { - public string? Email { get; set; } + public string? Email { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidAttributeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidAttributeTopicBindingModel.cs index b5eb55ae..b73cd87f 100644 --- a/OnTopic.Tests/BindingModels/InvalidAttributeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidAttributeTopicBindingModel.cs @@ -4,23 +4,22 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: ATTRIBUTE TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid property—i.e., one that doesn't map to a valid attribute. An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidAttributeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: ATTRIBUTE TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid property—i.e., one that doesn't map to a valid attribute. An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidAttributeTopicBindingModel : BasicTopicBindingModel { - public InvalidAttributeTopicBindingModel(string key) : base(key, "Page") { } + public InvalidAttributeTopicBindingModel(string key) : base(key, "Page") { } - public string? UnmappedAttribute { get; set; } + public string? UnmappedAttribute { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidChildrenTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidChildrenTopicBindingModel.cs index 84f3d0ce..93b689d7 100644 --- a/OnTopic.Tests/BindingModels/InvalidChildrenTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidChildrenTopicBindingModel.cs @@ -4,23 +4,22 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: CHILDREN TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid property. An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidChildrenTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: CHILDREN TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid property. An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidChildrenTopicBindingModel : BasicTopicBindingModel { - public InvalidChildrenTopicBindingModel(string key) : base(key, "Page") { } + public InvalidChildrenTopicBindingModel(string key) : base(key, "Page") { } - public Collection Children { get; } = new(); + public Collection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidNestedTopicListTypeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidNestedTopicListTypeTopicBindingModel.cs index 516ffae2..4f6c2660 100644 --- a/OnTopic.Tests/BindingModels/InvalidNestedTopicListTypeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidNestedTopicListTypeTopicBindingModel.cs @@ -5,24 +5,23 @@ \=============================================================================================================================*/ using System.Collections; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: NESTED TOPIC LIST TYPE TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid collection type—i.e., it implements a , even though nested topics are expected to return a type implementing . An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidNestedTopicListTypeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: NESTED TOPIC LIST TYPE TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid collection type—i.e., it implements a , even though nested topics are expected to return a type implementing . An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidNestedTopicListTypeTopicBindingModel : BasicTopicBindingModel { - public InvalidNestedTopicListTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } + public InvalidNestedTopicListTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } - public Dictionary Attributes { get; } = new(); + public Dictionary Attributes { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidParentTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidParentTopicBindingModel.cs index a31cb977..b78eadec 100644 --- a/OnTopic.Tests/BindingModels/InvalidParentTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidParentTopicBindingModel.cs @@ -4,23 +4,22 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: PARENT TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid property. An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidParentTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: PARENT TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid property. An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidParentTopicBindingModel : BasicTopicBindingModel { - public InvalidParentTopicBindingModel(string key) : base(key, "Page") { } + public InvalidParentTopicBindingModel(string key) : base(key, "Page") { } - public BasicTopicBindingModel? Parent { get; set; } + public BasicTopicBindingModel? Parent { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidReferenceTypeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidReferenceTypeTopicBindingModel.cs index 1df246f9..725bb867 100644 --- a/OnTopic.Tests/BindingModels/InvalidReferenceTypeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidReferenceTypeTopicBindingModel.cs @@ -6,23 +6,22 @@ using OnTopic.Models; using OnTopic.Tests.ViewModels; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: REFERENCE TYPE TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid reference type—i.e., one that doesn't implement . An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidReferenceTypeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: REFERENCE TYPE TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid reference type—i.e., one that doesn't implement . An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidReferenceTypeTopicBindingModel : BasicTopicBindingModel { - public InvalidReferenceTypeTopicBindingModel(string key) : base(key, "Page") { } + public InvalidReferenceTypeTopicBindingModel(string key) : base(key, "Page") { } - public EmptyViewModel BaseTopic { get; } = new(); + public EmptyViewModel BaseTopic { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidRelationshipBaseTypeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidRelationshipBaseTypeTopicBindingModel.cs index d18328a5..1e3c59ad 100644 --- a/OnTopic.Tests/BindingModels/InvalidRelationshipBaseTypeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidRelationshipBaseTypeTopicBindingModel.cs @@ -6,23 +6,22 @@ using OnTopic.Models; using OnTopic.Tests.ViewModels; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: RELATIONSHIP BASE TYPE TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid base type for an association—i.e., one that doesn't implement the . An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidRelationshipBaseTypeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: RELATIONSHIP BASE TYPE TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid base type for an association—i.e., one that doesn't implement the . An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidRelationshipBaseTypeTopicBindingModel : BasicTopicBindingModel { - public InvalidRelationshipBaseTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } + public InvalidRelationshipBaseTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } - public Collection ContentTypes { get; } = new(); + public Collection ContentTypes { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidRelationshipListTypeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidRelationshipListTypeTopicBindingModel.cs index bfa407f0..120a3bb3 100644 --- a/OnTopic.Tests/BindingModels/InvalidRelationshipListTypeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidRelationshipListTypeTopicBindingModel.cs @@ -6,24 +6,23 @@ using System.Collections; using OnTopic.ViewModels.BindingModels; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: RELATIONSHIP LIST TYPE TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid collection type—i.e., it implements a , even though relationships are expected to return a type implementing . An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidRelationshipListTypeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: RELATIONSHIP LIST TYPE TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid collection type—i.e., it implements a , even though relationships are expected to return a type implementing . An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidRelationshipListTypeTopicBindingModel : BasicTopicBindingModel { - public InvalidRelationshipListTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } + public InvalidRelationshipListTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } - public Dictionary ContentTypes { get; } = new(); + public Dictionary ContentTypes { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/InvalidRelationshipTypeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/InvalidRelationshipTypeTopicBindingModel.cs index 7c0690ca..2b414c8c 100644 --- a/OnTopic.Tests/BindingModels/InvalidRelationshipTypeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/InvalidRelationshipTypeTopicBindingModel.cs @@ -5,25 +5,24 @@ \=============================================================================================================================*/ using OnTopic.ViewModels.BindingModels; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: RELATIONSHIP TYPE TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a custom binding model with an invalid —i.e., it refers to , even though the property is associated with a . - /// An should be thrown when it is mapped. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InvalidRelationshipTypeTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: RELATIONSHIP TYPE TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a custom binding model with an invalid —i.e., it refers to , even though the property is associated with a . +/// An should be thrown when it is mapped. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InvalidRelationshipTypeTopicBindingModel : BasicTopicBindingModel { - public InvalidRelationshipTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } + public InvalidRelationshipTypeTopicBindingModel(string key) : base(key, "ContentTypeDescriptor") { } - [Collection(CollectionType.NestedTopics)] - public Collection ContentTypes { get; } = new(); + [Collection(CollectionType.NestedTopics)] + public Collection ContentTypes { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/MapToParentTopicBindingModel.cs b/OnTopic.Tests/BindingModels/MapToParentTopicBindingModel.cs index f4d436e7..b655fea6 100644 --- a/OnTopic.Tests/BindingModels/MapToParentTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/MapToParentTopicBindingModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: MAP TO PARENT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with mapped complex properties. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MapToParentTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: MAP TO PARENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with mapped complex properties. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MapToParentTopicBindingModel : BasicTopicBindingModel { - [MapToParent(AttributePrefix="")] - public ContactTopicBindingModel PrimaryContact { get; set; } = new(); + [MapToParent(AttributePrefix="")] + public ContactTopicBindingModel PrimaryContact { get; set; } = new(); - [MapToParent(AttributePrefix="Alternate")] - public EmailTopicBindingModel AlternateContact { get; set; } = new(); + [MapToParent(AttributePrefix="Alternate")] + public EmailTopicBindingModel AlternateContact { get; set; } = new(); - [MapToParent] - public EmailTopicBindingModel BillingContact { get; set; } = new(); + [MapToParent] + public EmailTopicBindingModel BillingContact { get; set; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/MinimumLengthPropertyTopicBindingModel.cs b/OnTopic.Tests/BindingModels/MinimumLengthPropertyTopicBindingModel.cs index 7f38db67..e577bd1e 100644 --- a/OnTopic.Tests/BindingModels/MinimumLengthPropertyTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/MinimumLengthPropertyTopicBindingModel.cs @@ -5,23 +5,22 @@ \=============================================================================================================================*/ using System.ComponentModel.DataAnnotations; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | VIEW MODEL: MINIMUM VALUE PROPERTY TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing view properties annotated with minimum value attributes. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MinimumLengthPropertyTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| VIEW MODEL: MINIMUM VALUE PROPERTY TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing view properties annotated with minimum value attributes. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MinimumLengthPropertyTopicBindingModel : BasicTopicBindingModel { - public MinimumLengthPropertyTopicBindingModel(string key) : base(key, "Page") { } + public MinimumLengthPropertyTopicBindingModel(string key) : base(key, "Page") { } - [MinLength(13)] - public string? Title { get; set; } + [MinLength(13)] + public string? Title { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/PageTopicBindingModel.cs b/OnTopic.Tests/BindingModels/PageTopicBindingModel.cs index a091d352..9cbcbff4 100644 --- a/OnTopic.Tests/BindingModels/PageTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/PageTopicBindingModel.cs @@ -6,32 +6,31 @@ using System.ComponentModel; using System.ComponentModel.DataAnnotations; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: PAGE TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with a couple of scalar values mapping to properties - /// on the Page content type. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class PageTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: PAGE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with a couple of scalar values mapping to properties +/// on the Page content type. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class PageTopicBindingModel : BasicTopicBindingModel { - public PageTopicBindingModel(string key) : base(key, "Page") { } + public PageTopicBindingModel(string key) : base(key, "Page") { } - [Required] - public string? Title { get; set; } + [Required] + public string? Title { get; set; } - [AttributeKey("MetaTitle")] - public string? BrowserTitle { get; set; } + [AttributeKey("MetaTitle")] + public string? BrowserTitle { get; set; } - [DefaultValue("Default page description")] - public string? MetaDescription { get; set; } + [DefaultValue("Default page description")] + public string? MetaDescription { get; set; } - public bool IsHidden { get; set; } + public bool IsHidden { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/RecordTopicBindingModel.cs b/OnTopic.Tests/BindingModels/RecordTopicBindingModel.cs index 9eb83dc8..12cc6f06 100644 --- a/OnTopic.Tests/BindingModels/RecordTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/RecordTopicBindingModel.cs @@ -6,27 +6,26 @@ using System.ComponentModel.DataAnnotations; using OnTopic.Models; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: RECORD - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed binding model based on a C# 9.0 record data type to ensure that it can be properly - /// mapped from. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class RecordTopicBindingModel : ITopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: RECORD +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed binding model based on a C# 9.0 record data type to ensure that it can be properly +/// mapped from. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class RecordTopicBindingModel : ITopicBindingModel { - public RecordTopicBindingModel() { } + public RecordTopicBindingModel() { } - [Required] - public string Key { get; init; } = default!; + [Required] + public string Key { get; init; } = default!; - [Required] - public string ContentType { get; init; } = default!; + [Required] + public string ContentType { get; init; } = default!; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/ReferenceTopicBindingModel.cs b/OnTopic.Tests/BindingModels/ReferenceTopicBindingModel.cs index 587c4fc8..fc7c2bea 100644 --- a/OnTopic.Tests/BindingModels/ReferenceTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/ReferenceTopicBindingModel.cs @@ -5,23 +5,22 @@ \=============================================================================================================================*/ using OnTopic.ViewModels.BindingModels; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | VIEW MODEL: REFERENCE TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing a property associated with a topic pointer—i.e. a reference - /// to another topic. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ReferenceTopicBindingModel : BasicTopicBindingModel { +/*============================================================================================================================== +| VIEW MODEL: REFERENCE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing a property associated with a topic pointer—i.e. a reference +/// to another topic. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ReferenceTopicBindingModel : BasicTopicBindingModel { - public ReferenceTopicBindingModel(string key) : base(key, "TextAttributeDescriptor") { } + public ReferenceTopicBindingModel(string key) : base(key, "TextAttributeDescriptor") { } - public AssociatedTopicBindingModel? BaseTopic { get; set; } + public AssociatedTopicBindingModel? BaseTopic { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/BindingModels/TextAttributeTopicBindingModel.cs b/OnTopic.Tests/BindingModels/TextAttributeTopicBindingModel.cs index 0dc18c0b..2502a9e7 100644 --- a/OnTopic.Tests/BindingModels/TextAttributeTopicBindingModel.cs +++ b/OnTopic.Tests/BindingModels/TextAttributeTopicBindingModel.cs @@ -5,21 +5,20 @@ \=============================================================================================================================*/ using OnTopic.TestDoubles.Metadata; -namespace OnTopic.Tests.BindingModels { +namespace OnTopic.Tests.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: TEXT ATTRIBUTE (DESCRIPTOR) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a minimal implementation of a custom topic binding model with a couple of scalar values mapping to properties - /// on the content type. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class TextAttributeTopicBindingModel : AttributeDescriptorTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: TEXT ATTRIBUTE (DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a minimal implementation of a custom topic binding model with a couple of scalar values mapping to properties +/// on the content type. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class TextAttributeTopicBindingModel : AttributeDescriptorTopicBindingModel { - public TextAttributeTopicBindingModel(string key) : base(key, "TextAttributeDescriptor") { } + public TextAttributeTopicBindingModel(string key) : base(key, "TextAttributeDescriptor") { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ContentTypeDescriptorTest.cs b/OnTopic.Tests/ContentTypeDescriptorTest.cs index 0d928dbc..7a803b6a 100644 --- a/OnTopic.Tests/ContentTypeDescriptorTest.cs +++ b/OnTopic.Tests/ContentTypeDescriptorTest.cs @@ -6,248 +6,247 @@ using OnTopic.Metadata; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: CONTENT TYPE DESCRIPTOR TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class and other types associated with it, such as , , and . +/// +[ExcludeFromCodeCoverage] +public class ContentTypeDescriptorTest { /*============================================================================================================================ - | CLASS: CONTENT TYPE DESCRIPTOR TEST + | TEST: CONTENT TYPE DESCRIPTOR: PERMITTED CONTENT TYPES: RETURNS COLLECTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class and other types associated with it, such as , , and . + /// Creates a hierarchy of s, and ensures that returns all instances from the associated ContentTypes + /// collection in . /// - [ExcludeFromCodeCoverage] - public class ContentTypeDescriptorTest { - - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR: PERMITTED CONTENT TYPES: RETURNS COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a hierarchy of s, and ensures that returns all instances from the associated ContentTypes - /// collection in . - /// - [Fact] - public void ContentTypeDescriptor_PermittedContentTypes_ReturnsCollection() { - - var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); - var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); - - page.Relationships.SetValue("ContentTypes", page); - page.Relationships.SetValue("ContentTypes", video); - - Assert.Equal(2, page.PermittedContentTypes.Count); - Assert.Empty(video.PermittedContentTypes); - Assert.Contains(page, page.PermittedContentTypes); - Assert.Contains(video, page.PermittedContentTypes); + [Fact] + public void ContentTypeDescriptor_PermittedContentTypes_ReturnsCollection() { - } + var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); + var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR: RESET PERMITTED CONTENT TYPES: RETURNS UPDATED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a hierarchy of s, and ensures that returns all updated instances from the associated - /// ContentTypes collection in after calling . - /// - [Fact] - public void ContentTypeDescriptor_ResetPermittedContentTypes_ReturnsUpdated() { - - var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); - var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); - var slideshow = new ContentTypeDescriptor("Slideshow", "ContentTypeDescriptor", page); - - page.Relationships.SetValue("ContentTypes", page); - page.Relationships.SetValue("ContentTypes", video); - - var initialCollection = page.PermittedContentTypes.ToList(); - - page.ResetPermittedContentTypes(); - page.Relationships.Remove("ContentTypes", page); - page.Relationships.SetValue("ContentTypes", slideshow); - - Assert.Equal(2, page.PermittedContentTypes.Count); - Assert.Contains(video, page.PermittedContentTypes); - Assert.Contains(slideshow, page.PermittedContentTypes); - Assert.DoesNotContain(page, page.PermittedContentTypes); - Assert.Contains(page, initialCollection); - Assert.DoesNotContain(slideshow, initialCollection); + page.Relationships.SetValue("ContentTypes", page); + page.Relationships.SetValue("ContentTypes", video); - } + Assert.Equal(2, page.PermittedContentTypes.Count); + Assert.Empty(video.PermittedContentTypes); + Assert.Contains(page, page.PermittedContentTypes); + Assert.Contains(video, page.PermittedContentTypes); - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR: ATTRIBUTE DESCRIPTORS: RETURNS INHERITED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a hierarchy of s, and ensures that returns all instances from the associated Attributes - /// collection in , as well as those from each . - /// - [Fact] - public void ContentTypeDescriptor_AttributeDescriptors_ReturnsInherited() { - - var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); - var pageAttributes = new ContentTypeDescriptor("Attributes", "List", page); - var titleAttribute = new AttributeDescriptor("Title", "AttributeDescriptor", pageAttributes); - - var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); - var videoAttributes = new ContentTypeDescriptor("Attributes", "List", video); - var urlAttribute = new AttributeDescriptor("Url", "AttributeDescriptor", videoAttributes); - - Assert.Single(page.AttributeDescriptors); - Assert.Equal(2, video.AttributeDescriptors.Count); - Assert.Contains(titleAttribute, video.AttributeDescriptors); - Assert.Contains(urlAttribute, video.AttributeDescriptors); + } - } + /*============================================================================================================================ + | TEST: CONTENT TYPE DESCRIPTOR: RESET PERMITTED CONTENT TYPES: RETURNS UPDATED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a hierarchy of s, and ensures that returns all updated instances from the associated + /// ContentTypes collection in after calling . + /// + [Fact] + public void ContentTypeDescriptor_ResetPermittedContentTypes_ReturnsUpdated() { - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR: RESET ATTRIBUTE DESCRIPTORS: RETURNS UPDATED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a hierarchy of s, and ensures that returns all new instances from the associated Attributes - /// collection in , as well as those from each , after - /// calling . - /// - [Fact] - public void ContentTypeDescriptor_ResetAttributeDescriptors_ReturnsUpdated() { - - var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); - var pageAttributes = new ContentTypeDescriptor("Attributes", "List", page); - var titleAttribute = new AttributeDescriptor("Title", "AttributeDescriptor", pageAttributes); - - var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); - var videoAttributes = new ContentTypeDescriptor("Attributes", "List", video); - var urlAttribute = new AttributeDescriptor("Url", "AttributeDescriptor", videoAttributes); - - var initialCollection = video.AttributeDescriptors.ToList(); - - var descriptionAttribute = new AttributeDescriptor("Description", "AttributeDescriptor", pageAttributes); - - pageAttributes.Children.Remove(titleAttribute); - page.ResetAttributeDescriptors(); - - Assert.Single(page.AttributeDescriptors); - Assert.Equal(2, video.AttributeDescriptors.Count); - Assert.Contains(descriptionAttribute, video.AttributeDescriptors); - Assert.Contains(urlAttribute, video.AttributeDescriptors); - Assert.DoesNotContain(titleAttribute, video.AttributeDescriptors); - Assert.Contains(titleAttribute, initialCollection); - Assert.DoesNotContain(descriptionAttribute, initialCollection); + var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); + var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); + var slideshow = new ContentTypeDescriptor("Slideshow", "ContentTypeDescriptor", page); - } + page.Relationships.SetValue("ContentTypes", page); + page.Relationships.SetValue("ContentTypes", video); + + var initialCollection = page.PermittedContentTypes.ToList(); + + page.ResetPermittedContentTypes(); + page.Relationships.Remove("ContentTypes", page); + page.Relationships.SetValue("ContentTypes", slideshow); + + Assert.Equal(2, page.PermittedContentTypes.Count); + Assert.Contains(video, page.PermittedContentTypes); + Assert.Contains(slideshow, page.PermittedContentTypes); + Assert.DoesNotContain(page, page.PermittedContentTypes); + Assert.Contains(page, initialCollection); + Assert.DoesNotContain(slideshow, initialCollection); + + } + + /*============================================================================================================================ + | TEST: CONTENT TYPE DESCRIPTOR: ATTRIBUTE DESCRIPTORS: RETURNS INHERITED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a hierarchy of s, and ensures that returns all instances from the associated Attributes + /// collection in , as well as those from each . + /// + [Fact] + public void ContentTypeDescriptor_AttributeDescriptors_ReturnsInherited() { + + var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); + var pageAttributes = new ContentTypeDescriptor("Attributes", "List", page); + var titleAttribute = new AttributeDescriptor("Title", "AttributeDescriptor", pageAttributes); + + var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); + var videoAttributes = new ContentTypeDescriptor("Attributes", "List", video); + var urlAttribute = new AttributeDescriptor("Url", "AttributeDescriptor", videoAttributes); + + Assert.Single(page.AttributeDescriptors); + Assert.Equal(2, video.AttributeDescriptors.Count); + Assert.Contains(titleAttribute, video.AttributeDescriptors); + Assert.Contains(urlAttribute, video.AttributeDescriptors); + + } + + /*============================================================================================================================ + | TEST: CONTENT TYPE DESCRIPTOR: RESET ATTRIBUTE DESCRIPTORS: RETURNS UPDATED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a hierarchy of s, and ensures that returns all new instances from the associated Attributes + /// collection in , as well as those from each , after + /// calling . + /// + [Fact] + public void ContentTypeDescriptor_ResetAttributeDescriptors_ReturnsUpdated() { + + var page = new ContentTypeDescriptor("Page", "ContentTypeDescriptor"); + var pageAttributes = new ContentTypeDescriptor("Attributes", "List", page); + var titleAttribute = new AttributeDescriptor("Title", "AttributeDescriptor", pageAttributes); + + var video = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", page); + var videoAttributes = new ContentTypeDescriptor("Attributes", "List", video); + var urlAttribute = new AttributeDescriptor("Url", "AttributeDescriptor", videoAttributes); + + var initialCollection = video.AttributeDescriptors.ToList(); - /*========================================================================================================================== - | TEST: IS TYPE OF: DERIVED CONTENT TYPE: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Associates a new topic with several content types, and confirms that the topic is reported as a type of those content - /// types. - /// - [Fact] - public void IsTypeOf_DerivedContentType_ReturnsTrue() { + var descriptionAttribute = new AttributeDescriptor("Description", "AttributeDescriptor", pageAttributes); - var contentType = new ContentTypeDescriptor("Root", "ContentTypeDescriptor"); - for (var i = 0; i < 5; i++) { - var childContentType = new ContentTypeDescriptor("ContentType" + i, "ContentTypeDescriptor", contentType); - contentType = childContentType; - } + pageAttributes.Children.Remove(titleAttribute); + page.ResetAttributeDescriptors(); - Assert.True(contentType.IsTypeOf("Root")); + Assert.Single(page.AttributeDescriptors); + Assert.Equal(2, video.AttributeDescriptors.Count); + Assert.Contains(descriptionAttribute, video.AttributeDescriptors); + Assert.Contains(urlAttribute, video.AttributeDescriptors); + Assert.DoesNotContain(titleAttribute, video.AttributeDescriptors); + Assert.Contains(titleAttribute, initialCollection); + Assert.DoesNotContain(descriptionAttribute, initialCollection); + } + + /*============================================================================================================================ + | TEST: IS TYPE OF: DERIVED CONTENT TYPE: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Associates a new topic with several content types, and confirms that the topic is reported as a type of those content + /// types. + /// + [Fact] + public void IsTypeOf_DerivedContentType_ReturnsTrue() { + + var contentType = new ContentTypeDescriptor("Root", "ContentTypeDescriptor"); + for (var i = 0; i < 5; i++) { + var childContentType = new ContentTypeDescriptor("ContentType" + i, "ContentTypeDescriptor", contentType); + contentType = childContentType; } - /*========================================================================================================================== - | TEST: IS TYPE OF: INVALID CONTENT TYPE: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Associates a new topic with several content types, and confirms that the topic is not reported as a type of a content - /// type that is not in that chain. - /// - [Fact] - public void IsTypeOf_InvalidContentType_ReturnsFalse() { + Assert.True(contentType.IsTypeOf("Root")); - var contentType = new ContentTypeDescriptor("Root", "ContentTypeDescriptor"); - for (var i = 0; i < 5; i++) { - var childContentType = new ContentTypeDescriptor("ContentType" + i, "ContentTypeDescriptor", contentType); - contentType = childContentType; - } + } - Assert.False(contentType.IsTypeOf("DifferentRoot")); + /*============================================================================================================================ + | TEST: IS TYPE OF: INVALID CONTENT TYPE: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Associates a new topic with several content types, and confirms that the topic is not reported as a type of a content + /// type that is not in that chain. + /// + [Fact] + public void IsTypeOf_InvalidContentType_ReturnsFalse() { + var contentType = new ContentTypeDescriptor("Root", "ContentTypeDescriptor"); + for (var i = 0; i < 5; i++) { + var childContentType = new ContentTypeDescriptor("ContentType" + i, "ContentTypeDescriptor", contentType); + contentType = childContentType; } - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR COLLECTION: CONSTRUCT WITH VALUES: RETURNS VALUES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new with a and confirms - /// that all child s within the topic graph are added. - /// - [Fact] - public void ContentTypeDescriptorCollection_ConstructWithValues_ReturnsValues() { + Assert.False(contentType.IsTypeOf("DifferentRoot")); - var rootContentType = new ContentTypeDescriptor("ContentTypes", "ContentTypeDescriptor"); - var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", rootContentType); - _ = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", pageContentType); + } - var contentTypeCollection = new ContentTypeDescriptorCollection(rootContentType); + /*============================================================================================================================ + | TEST: CONTENT TYPE DESCRIPTOR COLLECTION: CONSTRUCT WITH VALUES: RETURNS VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a new with a and confirms + /// that all child s within the topic graph are added. + /// + [Fact] + public void ContentTypeDescriptorCollection_ConstructWithValues_ReturnsValues() { - Assert.Equal(3, contentTypeCollection.Count); + var rootContentType = new ContentTypeDescriptor("ContentTypes", "ContentTypeDescriptor"); + var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", rootContentType); + _ = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", pageContentType); - } + var contentTypeCollection = new ContentTypeDescriptorCollection(rootContentType); - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR COLLECTION: REFRESH: RETURNS UPDATED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new with a and confirms - /// that all child s within the topic graph are added. - /// - [Fact] - public void ContentTypeDescriptorCollection_Refresh_ReturnsUpdated() { + Assert.Equal(3, contentTypeCollection.Count); - var rootContentType = new ContentTypeDescriptor("ContentTypes", "ContentTypeDescriptor"); - var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", rootContentType); - var videoContentType = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", pageContentType); - var slideshowContentType = new ContentTypeDescriptor("Slideshow", "ContentTypeDescriptor"); + } - var contentTypeCollection = new ContentTypeDescriptorCollection(rootContentType); + /*============================================================================================================================ + | TEST: CONTENT TYPE DESCRIPTOR COLLECTION: REFRESH: RETURNS UPDATED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a new with a and confirms + /// that all child s within the topic graph are added. + /// + [Fact] + public void ContentTypeDescriptorCollection_Refresh_ReturnsUpdated() { - pageContentType.Children.Remove(videoContentType); - pageContentType.Children.Add(slideshowContentType); + var rootContentType = new ContentTypeDescriptor("ContentTypes", "ContentTypeDescriptor"); + var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", rootContentType); + var videoContentType = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", pageContentType); + var slideshowContentType = new ContentTypeDescriptor("Slideshow", "ContentTypeDescriptor"); - contentTypeCollection.Refresh(rootContentType); + var contentTypeCollection = new ContentTypeDescriptorCollection(rootContentType); - Assert.Equal(3, contentTypeCollection.Count); - Assert.Contains(slideshowContentType, contentTypeCollection); - Assert.DoesNotContain(videoContentType, contentTypeCollection); + pageContentType.Children.Remove(videoContentType); + pageContentType.Children.Add(slideshowContentType); - } + contentTypeCollection.Refresh(rootContentType); - /*========================================================================================================================== - | TEST: CONTENT TYPE DESCRIPTOR COLLECTION: CONSTRUCT WITH VALUES: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new with a and confirms - /// that an exception is thrown if the is not set to the expected value of ContentTypes, - /// which represents the root content type. - /// - [Fact] - public void ContentTypeDescriptorCollection_ConstructWithValues_ThrowsException() { - - var rootContentType = new ContentTypeDescriptor("ContentType", "ContentTypeDescriptor"); - var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", rootContentType); - _ = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", pageContentType); - - Assert.Throws(() => - new ContentTypeDescriptorCollection(pageContentType) - ); + Assert.Equal(3, contentTypeCollection.Count); + Assert.Contains(slideshowContentType, contentTypeCollection); + Assert.DoesNotContain(videoContentType, contentTypeCollection); - } + } + + /*============================================================================================================================ + | TEST: CONTENT TYPE DESCRIPTOR COLLECTION: CONSTRUCT WITH VALUES: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a new with a and confirms + /// that an exception is thrown if the is not set to the expected value of ContentTypes, + /// which represents the root content type. + /// + [Fact] + public void ContentTypeDescriptorCollection_ConstructWithValues_ThrowsException() { + + var rootContentType = new ContentTypeDescriptor("ContentType", "ContentTypeDescriptor"); + var pageContentType = new ContentTypeDescriptor("Page", "ContentTypeDescriptor", rootContentType); + _ = new ContentTypeDescriptor("Video", "ContentTypeDescriptor", pageContentType); + + Assert.Throws(() => + new ContentTypeDescriptorCollection(pageContentType) + ); + + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ContractTest.cs b/OnTopic.Tests/ContractTest.cs index e397ff0c..40e13ed4 100644 --- a/OnTopic.Tests/ContractTest.cs +++ b/OnTopic.Tests/ContractTest.cs @@ -6,161 +6,163 @@ using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: CONTRACT TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ContractTest { /*============================================================================================================================ - | CLASS: CONTRACT TEST + | TEST: REQUIRES: CONDITION IS TRUE: THROW NO EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Tests a true condition using the class, and validates that it correctly does nothing. /// - [ExcludeFromCodeCoverage] - public class ContractTest { - - /*========================================================================================================================== - | TEST: REQUIRES: CONDITION IS TRUE: THROW NO EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a true condition using the class, and validates that it correctly does nothing. - /// - [Fact] - public void Requires_ConditionIsTrue_ThrowNoException() - => Contract.Requires(true, "The argument cannot be null"); - - /*========================================================================================================================== - | TEST: REQUIRES: CONDITION IS FALSE: THROW ARGUMENT NULL EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a false condition using the class, and validates that it correctly returns an . - /// - [Fact] - public void Requires_ConditionIsFalse_ThrowArgumentNullException() => - Assert.Throws(() => - Contract.Requires(false, "The argument cannot be null") - ); - - /*========================================================================================================================== - | TEST: REQUIRES: OBJECT EXISTS: THROW NO EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a non-null argument using the class, and validates that it correctly does nothing. - /// - [Fact] - public void Requires_ObjectExists_ThrowNoException() => - Contract.Requires(new object(), "The argument cannot be null"); - - /*========================================================================================================================== - | TEST: REQUIRES: OBJECT IS NULL: THROW ARGUMENT NULL EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a null argument using the class, and validates that it correctly returns an . - /// - [Fact] - public void Requires_ObjectIsNull_ThrowArgumentNullException() => - Assert.Throws(() => - Contract.Requires(null, "The argument cannot be null") - ); - - /*========================================================================================================================== - | TEST: REQUIRES: MESSAGE EXISTS: THROW EXCEPTION WITH MESSAGE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a null argument using the class, and validates that it correctly returns an with the expected . - /// - [Fact] - public void Requires_MessageExists_ThrowExceptionWithMessage() { - - var errorMessage = "The argument cannot be null"; - - try { - Contract.Requires(false, errorMessage); - } - catch (ArgumentException ex) { - Assert.Equal(errorMessage, ex.Message); - } + [Fact] + public void Requires_ConditionIsTrue_ThrowNoException() + => Contract.Requires(true, "The argument cannot be null"); - } + /*============================================================================================================================ + | TEST: REQUIRES: CONDITION IS FALSE: THROW ARGUMENT NULL EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a false condition using the class, and validates that it correctly returns an . + /// + [Fact] + public void Requires_ConditionIsFalse_ThrowArgumentNullException() => + Assert.Throws(() => + Contract.Requires(false, "The argument cannot be null") + ); + + /*============================================================================================================================ + | TEST: REQUIRES: OBJECT EXISTS: THROW NO EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a non-null argument using the class, and validates that it correctly does nothing. + /// + [Fact] + public void Requires_ObjectExists_ThrowNoException() => + Contract.Requires(new object(), "The argument cannot be null"); - /*========================================================================================================================== - | TEST: REQUIRES: INVALID CONSTRUCTOR: THROW ARGUMENT EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a null argument using the class, and attempts to throw a custom with the expected , but fails due to no overload with - /// a single message parameter. In this case, it should throw a . - /// - [Fact] - public void Requires_InvalidConstructor_ThrowArgumentException() { - var errorMessage = "The argument cannot be null"; - Assert.Throws(() => - Contract.Requires(false, errorMessage) - ); + /*============================================================================================================================ + | TEST: REQUIRES: OBJECT IS NULL: THROW ARGUMENT NULL EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a null argument using the class, and validates that it correctly returns an . + /// + [Fact] + public void Requires_ObjectIsNull_ThrowArgumentNullException() => + Assert.Throws(() => + Contract.Requires((object?)null, "The argument cannot be null") + ); + + /*============================================================================================================================ + | TEST: REQUIRES: MESSAGE EXISTS: THROW EXCEPTION WITH MESSAGE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a null argument using the class, and validates that it correctly returns an with the expected . + /// + [Fact] + public void Requires_MessageExists_ThrowExceptionWithMessage() { + + var errorMessage = "The argument cannot be null"; + + try { + Contract.Requires(false, errorMessage); + } + catch (ArgumentException ex) { + Assert.Equal(errorMessage, ex.Message); } - /*========================================================================================================================== - | TEST: ASSUME: CONDITION IS TRUE: THROW NO EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a true condition using the class, and validates that it correctly does nothing. - /// - [Fact] - public void Assume_ConditionIsTrue_ThrowNoException() - => Contract.Assume(true, "The argument cannot be null"); - - /*========================================================================================================================== - | TEST: ASSUME: CONDITION IS FALSE: THROW ARGUMENT NULL EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a false condition using the class, and validates that it correctly returns an . - /// - [Fact] - public void Assume_ConditionIsFalse_ThrowArgumentNullException() => - Assert.Throws(() => - Contract.Assume(false, "The argument cannot be null") - ); - - /*========================================================================================================================== - | TEST: ASSUME: CONDITION IS FALSE: THROW CUSTOM EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a false condition using the class, and validates that it correctly throws the specified - /// . - /// - [Fact] - public void Assume_ConditionIsFalse_ThrowCustomExpection() => - Assert.Throws(() => - Contract.Assume(false, "The argument is out of range") - ); - - /*========================================================================================================================== - | TEST: ASSUME: CONDITION IS FALSE: THROW CUSTOM EXCEPTION WITHOUT MESSAGE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a false condition using the class, and validates that it correctly throws the specified - /// using the empty constructor, since no errorMessage is included. - /// - [Fact] - public void Assume_ConditionIsFalse_ThrowCustomExpectionWithoutMessage() => - Assert.Throws(() => - Contract.Assume(false) - ); - - /*========================================================================================================================== - | TEST: ASSUME: OBJECT IS NULL: THROW INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests a null assignment using the class, and validates that it correctly returns an . - /// - [Fact] - public void Assume_ObjectIsNull_ThrowInvalidOperationException() => - Assert.Throws(() => - Contract.Assume(null, "The local runtime state is invalid.") - ); - - } //Class -} //Namespace \ No newline at end of file + } + + /*============================================================================================================================ + | TEST: REQUIRES: INVALID CONSTRUCTOR: THROW ARGUMENT EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a null argument using the class, and attempts to throw a custom with the expected , but fails due to no overload with + /// a single message parameter. In this case, it should throw a . + /// + [Fact] + public void Requires_InvalidConstructor_ThrowArgumentException() { + var errorMessage = "The argument cannot be null"; + Assert.Throws(() => + Contract.Requires(false, errorMessage) + ); + } + + /*============================================================================================================================ + | TEST: ASSUME: CONDITION IS TRUE: THROW NO EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a true condition using the class, and validates that it correctly does nothing. + /// + [Fact] + public void Assume_ConditionIsTrue_ThrowNoException() + => Contract.Assume(true, "The argument cannot be null"); + + /*============================================================================================================================ + | TEST: ASSUME: CONDITION IS FALSE: THROW ARGUMENT NULL EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a false condition using the class, and validates that it correctly returns an . + /// + [Fact] + public void Assume_ConditionIsFalse_ThrowArgumentNullException() => + Assert.Throws(() => + Contract.Assume(false, "The argument cannot be null") + ); + + /*============================================================================================================================ + | TEST: ASSUME: CONDITION IS FALSE: THROW CUSTOM EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a false condition using the class, and validates that it correctly throws the specified + /// . + /// + [Fact] + public void Assume_ConditionIsFalse_ThrowCustomExpection() => + Assert.Throws(() => + Contract.Assume(false, "The argument is out of range") + ); + + /*============================================================================================================================ + | TEST: ASSUME: CONDITION IS FALSE: THROW CUSTOM EXCEPTION WITHOUT MESSAGE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a false condition using the class, and validates that it correctly throws the specified + /// , falling back to the [CallerArgumentExpression]-captured source text of + /// the condition as the message, since no errorMessage is included. + /// + [Fact] + public void Assume_ConditionIsFalse_ThrowCustomExpectionWithoutMessage() { + var exception = Assert.Throws(() => + Contract.Assume(false) + ); + Assert.Equal("false", exception.Message); + } + + /*============================================================================================================================ + | TEST: ASSUME: OBJECT IS NULL: THROW INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests a null assignment using the class, and validates that it correctly returns an . + /// + [Fact] + public void Assume_ObjectIsNull_ThrowInvalidOperationException() => + Assert.Throws(() => + Contract.Assume(null, "The local runtime state is invalid.") + ); + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Entities/CustomTopic.cs b/OnTopic.Tests/Entities/CustomTopic.cs index 82e3a0c3..81482d73 100644 --- a/OnTopic.Tests/Entities/CustomTopic.cs +++ b/OnTopic.Tests/Entities/CustomTopic.cs @@ -6,130 +6,129 @@ using System.Globalization; using OnTopic.Associations; -namespace OnTopic.Tests.Entities { +namespace OnTopic.Tests.Entities; + +/*============================================================================================================================== +| TOPIC ENTITY: CUSTOM +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a derived version of with additional properties for evaluating the enforcement of business +/// logic. +/// +[ExcludeFromCodeCoverage] +public class CustomTopic: Topic { /*============================================================================================================================ - | TOPIC ENTITY: CUSTOM + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public CustomTopic(string key, string contentType, Topic? parent = null, int id = -1): base(key, contentType, parent, id) { + } + + /*============================================================================================================================ + | TEXT ATTRIBUTE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a derived version of with additional properties for evaluating the enforcement of business - /// logic. + /// Provides a text property which is intended to be mapped to a text attribute. /// - [ExcludeFromCodeCoverage] - public class CustomTopic: Topic { + [AttributeSetter] + public string? TextAttribute { + get => Attributes.GetValue("TextAttribute"); + set => SetAttributeValue("TextAttribute", value); + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public CustomTopic(string key, string contentType, Topic? parent = null, int id = -1): base(key, contentType, parent, id) { - } - - /*========================================================================================================================== - | TEXT ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a text property which is intended to be mapped to a text attribute. - /// - [AttributeSetter] - public string? TextAttribute { - get => Attributes.GetValue("TextAttribute"); - set => SetAttributeValue("TextAttribute", value); - } - - /*========================================================================================================================== - | BOOLEAN ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a Boolean property which is intended to be mapped to a Boolean attribute. - /// - [AttributeSetter] - public bool BooleanAttribute { - get => Attributes.GetBoolean("BooleanAttribute"); - set => SetAttributeValue("BooleanAttribute", value? "1" : "0"); - } + /*============================================================================================================================ + | BOOLEAN ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a Boolean property which is intended to be mapped to a Boolean attribute. + /// + [AttributeSetter] + public bool BooleanAttribute { + get => Attributes.GetBoolean("BooleanAttribute"); + set => SetAttributeValue("BooleanAttribute", value? "1" : "0"); + } - /*========================================================================================================================== - | BOOLEAN AS STRING ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a string property which is intended to be mapped to a Boolean attribute. - /// - [AttributeSetter] - public string BooleanAsStringAttribute { - get => Attributes.GetValue("BooleanAttribute", "0"); - set => SetAttributeValue("BooleanAttribute", value); - } + /*============================================================================================================================ + | BOOLEAN AS STRING ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a string property which is intended to be mapped to a Boolean attribute. + /// + [AttributeSetter] + public string BooleanAsStringAttribute { + get => Attributes.GetValue("BooleanAttribute", "0"); + set => SetAttributeValue("BooleanAttribute", value); + } - /*========================================================================================================================== - | NUMERIC ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a numeric property which is intended to be mapped to a numeric attribute. - /// - [AttributeSetter] - public int NumericAttribute { - get => Attributes.GetInteger("NumericAttribute"); - set { - Contract.Requires( - value >= 0, - $"{nameof(NumericAttribute)} expects a positive value." - ); - SetAttributeValue("NumericAttribute", value.ToString(CultureInfo.InvariantCulture)); - } + /*============================================================================================================================ + | NUMERIC ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a numeric property which is intended to be mapped to a numeric attribute. + /// + [AttributeSetter] + public int NumericAttribute { + get => Attributes.GetInteger("NumericAttribute"); + set { + Contract.Requires( + value >= 0, + $"{nameof(NumericAttribute)} expects a positive value." + ); + SetAttributeValue("NumericAttribute", value.ToString(CultureInfo.InvariantCulture)); } + } - /*========================================================================================================================== - | NON-NULLABLE ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a property which does not permit null values as a means of ensuring the business logic is enforced when - /// removing values. - /// - [AttributeSetter] - public string NonNullableAttribute { - get => Attributes.GetValue("NonNullableAttribute")?? ""; - set { - Contract.Requires(value, nameof(value)); - SetAttributeValue("NonNullableAttribute", value.ToString(CultureInfo.InvariantCulture)); - } + /*============================================================================================================================ + | NON-NULLABLE ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a property which does not permit null values as a means of ensuring the business logic is enforced when + /// removing values. + /// + [AttributeSetter] + public string NonNullableAttribute { + get => Attributes.GetValue("NonNullableAttribute")?? ""; + set { + Contract.Requires(value, nameof(value)); + SetAttributeValue("NonNullableAttribute", value.ToString(CultureInfo.InvariantCulture)); } + } - /*========================================================================================================================== - | DATE/TIME ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a date/time property which is intended to be mapped to a date/time attribute. - /// - [AttributeSetter] - public DateTime DateTimeAttribute { - get => Attributes.GetDateTime("DateTimeAttribute"); - set { - Contract.Requires( - value.Year > 2000, - $"{nameof(DateTimeAttribute)} expects a date after 2000." - ); - SetAttributeValue("DateTimeAttribute", value.ToString(CultureInfo.InvariantCulture)); - } + /*============================================================================================================================ + | DATE/TIME ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a date/time property which is intended to be mapped to a date/time attribute. + /// + [AttributeSetter] + public DateTime DateTimeAttribute { + get => Attributes.GetDateTime("DateTimeAttribute"); + set { + Contract.Requires( + value.Year > 2000, + $"{nameof(DateTimeAttribute)} expects a date after 2000." + ); + SetAttributeValue("DateTimeAttribute", value.ToString(CultureInfo.InvariantCulture)); } + } - /*========================================================================================================================== - | TOPIC REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a topic reference property which is intended to be mapped to a topic reference. - /// - [ReferenceSetter] - public Topic? TopicReference { - get => References.GetValue("TopicReference"); - set { - Contract.Requires( - value?.ContentType == ContentType, - $"{nameof(TopicReference)} expects a topic with the same content type as the parent: {ContentType}." - ); - References.SetValue("TopicReference", value); - } + /*============================================================================================================================ + | TOPIC REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a topic reference property which is intended to be mapped to a topic reference. + /// + [ReferenceSetter] + public Topic? TopicReference { + get => References.GetValue("TopicReference"); + set { + Contract.Requires( + value?.ContentType == ContentType, + $"{nameof(TopicReference)} expects a topic with the same content type as the parent: {ContentType}." + ); + References.SetValue("TopicReference", value); } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Exceptions/NoMessageException.cs b/OnTopic.Tests/Exceptions/NoMessageException.cs index 386e6b2d..e25140ee 100644 --- a/OnTopic.Tests/Exceptions/NoMessageException.cs +++ b/OnTopic.Tests/Exceptions/NoMessageException.cs @@ -3,44 +3,31 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ -using System.Runtime.Serialization; +namespace OnTopic; -namespace OnTopic { +/*============================================================================================================================== +| CLASS: NO MESSAGE EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// A test exception that doesn't include an expected constructor overload accepting the message. +/// +/// +/// The will attempt to initialize an exception of the specified type +/// with a message. This assumes an expected constructor overload exists that accepts a single message parameter. If +/// not, it will fallback to a . +/// +[ExcludeFromCodeCoverage] +[SuppressMessage("Design", "CA1032:Implement standard exception constructors", Justification = "This exception intentionally omits the message constructor to test the fallback behavior in Contract.Requires{T}.")] +public class NoMessageException: ArgumentException { /*============================================================================================================================ - | CLASS: NO MESSAGE EXCEPTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// A test exception that doesn't include an expected constructor overload accepting the message. + /// Instantiates a new instance of a class with no parameters. /// - /// - /// The will attempt to initialize an exception of the specified type - /// with a message. This assumes an expected constructor overload exists that accepts a single message parameter. If - /// not, it will fallback to a . - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class NoMessageException: ArgumentException { + /// A new instance. + public NoMessageException(): base() { + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of a class with no parameters. - /// - /// A new instance. - public NoMessageException(): base() { - } - - /// - /// Instantiates a new instance of a class for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected NoMessageException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } - - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Fixtures/SharedRepositoryCollection.cs b/OnTopic.Tests/Fixtures/SharedRepositoryCollection.cs index 7608aad1..bd4f8861 100644 --- a/OnTopic.Tests/Fixtures/SharedRepositoryCollection.cs +++ b/OnTopic.Tests/Fixtures/SharedRepositoryCollection.cs @@ -6,17 +6,17 @@ using OnTopic.TestDoubles; using Xunit; -namespace OnTopic.Tests.Fixtures { +namespace OnTopic.Tests.Fixtures; - /*============================================================================================================================ - | CLASS: SHARED REPOSITORY COLLECTION - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Defines a common context used to share an implementation of the between - /// tests using a common . - /// - [CollectionDefinition("Shared Repository")] - public class SharedRepositoryCollection: ICollectionFixture> { +/*============================================================================================================================== +| CLASS: SHARED REPOSITORY COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a common context used to share an implementation of the between +/// tests using a common . +/// +[CollectionDefinition("Shared Repository")] +[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Follows xUnit's naming convention for collection fixture definitions, not a .NET collection type.")] +public class SharedRepositoryCollection: ICollectionFixture> { - } } \ No newline at end of file diff --git a/OnTopic.Tests/Fixtures/TopicInfrastructureFixture.cs b/OnTopic.Tests/Fixtures/TopicInfrastructureFixture.cs index 3a9a4a79..1bdb80c8 100644 --- a/OnTopic.Tests/Fixtures/TopicInfrastructureFixture.cs +++ b/OnTopic.Tests/Fixtures/TopicInfrastructureFixture.cs @@ -10,77 +10,76 @@ using OnTopic.TestDoubles; using OnTopic.Tests.TestDoubles; -namespace OnTopic.Tests.Fixtures -{ +namespace OnTopic.Tests.Fixtures; + + +/*============================================================================================================================== +| CLASS: TOPIC INFRASTRUCTURE FIXTURE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Introduces a shared context to use for unit tests depending on an , , and, optionally, an . +/// +/// +/// This basic fixture uses the , , , , and . +/// +public class TopicInfrastructureFixture where T: ITopicRepository, new() { /*============================================================================================================================ - | CLASS: TOPIC INFRASTRUCTURE FIXTURE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Introduces a shared context to use for unit tests depending on an , , and, optionally, an . - /// - /// - /// This basic fixture uses the , , , , and . - /// - public class TopicInfrastructureFixture where T: ITopicRepository, new() { + public TopicInfrastructureFixture() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Create composite topic lookup service \-------------------------------------------------------------------------------------------------------------------------*/ - public TopicInfrastructureFixture() { + TypeLookupService = new CompositeTypeLookupService( + new TopicViewModelLookupService(), + new FakeViewModelLookupService() + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Create composite topic lookup service - \-----------------------------------------------------------------------------------------------------------------------*/ - TypeLookupService = new CompositeTypeLookupService( - new TopicViewModelLookupService(), - new FakeViewModelLookupService() - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Assemble dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicRepository = new T(); - CachedTopicRepository = new CachedTopicRepository(TopicRepository); - MappingService = new TopicMappingService(CachedTopicRepository, TypeLookupService); + /*-------------------------------------------------------------------------------------------------------------------------- + | Assemble dependencies + \-------------------------------------------------------------------------------------------------------------------------*/ + TopicRepository = new T(); + CachedTopicRepository = new CachedTopicRepository(TopicRepository); + MappingService = new TopicMappingService(CachedTopicRepository, TypeLookupService); - } + } - /*========================================================================================================================== - | TYPE LOOKUP SERVICE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A for accessing view models from the and the . - /// - public ITypeLookupService TypeLookupService { get; private set; } + /*============================================================================================================================ + | TYPE LOOKUP SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A for accessing view models from the and the . + /// + public ITypeLookupService TypeLookupService { get; private set; } - /*========================================================================================================================== - | TOPIC REPOSITORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A without a caching layer. - /// - public ITopicRepository TopicRepository { get; private set; } + /*============================================================================================================================ + | TOPIC REPOSITORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A without a caching layer. + /// + public ITopicRepository TopicRepository { get; private set; } - /*========================================================================================================================== - | CACHED TOPIC REPOSITORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A wrapped in a . - /// - public ITopicRepository CachedTopicRepository { get; private set; } + /*============================================================================================================================ + | CACHED TOPIC REPOSITORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A wrapped in a . + /// + public ITopicRepository CachedTopicRepository { get; private set; } - /*========================================================================================================================== - | MAPPING SERVICE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A based on a , looking up view models from the and the . - /// - public ITopicMappingService MappingService { get; private set; } + /*============================================================================================================================ + | MAPPING SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A based on a , looking up view models from the and the . + /// + public ITopicMappingService MappingService { get; private set; } - } } diff --git a/OnTopic.Tests/Fixtures/TypeAccessorFixture.cs b/OnTopic.Tests/Fixtures/TypeAccessorFixture.cs index 3ccea59e..fa290a71 100644 --- a/OnTopic.Tests/Fixtures/TypeAccessorFixture.cs +++ b/OnTopic.Tests/Fixtures/TypeAccessorFixture.cs @@ -5,36 +5,35 @@ \=============================================================================================================================*/ using OnTopic.Internal.Reflection; -namespace OnTopic.Tests.Fixtures -{ +namespace OnTopic.Tests.Fixtures; + + +/*============================================================================================================================== +| CLASS: TYPE ACCESSOR FIXTURE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Introduces a shared context to use for unit tests depending on an . +/// +public class TypeAccessorFixture { /*============================================================================================================================ - | CLASS: TYPE ACCESSOR FIXTURE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Introduces a shared context to use for unit tests depending on an . - /// - public class TypeAccessorFixture { + public TypeAccessorFixture() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Create type accessor \-------------------------------------------------------------------------------------------------------------------------*/ - public TypeAccessorFixture() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Create type accessor - \-----------------------------------------------------------------------------------------------------------------------*/ - TypeAccessor = new TypeAccessor(typeof(T)); + TypeAccessor = new TypeAccessor(typeof(T)); - } + } - /*========================================================================================================================== - | TYPE ACCESSOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A for accessing instances. - /// - internal TypeAccessor TypeAccessor { get; private set; } + /*============================================================================================================================ + | TYPE ACCESSOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A for accessing instances. + /// + internal TypeAccessor TypeAccessor { get; private set; } - } } diff --git a/OnTopic.Tests/HierarchicalTopicMappingServiceTest.cs b/OnTopic.Tests/HierarchicalTopicMappingServiceTest.cs index ef20f949..129fd6ee 100644 --- a/OnTopic.Tests/HierarchicalTopicMappingServiceTest.cs +++ b/OnTopic.Tests/HierarchicalTopicMappingServiceTest.cs @@ -10,195 +10,193 @@ using OnTopic.Tests.Fixtures; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: HIERARCHICAL TOPIC MAPPING SERVICE TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the . +/// +[ExcludeFromCodeCoverage] +[Xunit.Collection("Shared Repository")] +public class HierarchicalTopicMappingServiceTest: IClassFixture> { /*============================================================================================================================ - | CLASS: HIERARCHICAL TOPIC MAPPING SERVICE TEST + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly Topic _topic; + + /*============================================================================================================================ + | HIERARCHICAL TOPIC MAPPING SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the . + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - [Xunit.Collection("Shared Repository")] - public class HierarchicalTopicMappingServiceTest: IClassFixture> { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. In addition, it initializes a shared reference to use for the various + /// tests. + /// + public HierarchicalTopicMappingServiceTest(TopicInfrastructureFixture fixture) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly Topic _topic; + Contract.Requires(fixture, nameof(fixture)); - /*========================================================================================================================== - | HIERARCHICAL TOPIC MAPPING SERVICE + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly IHierarchicalTopicMappingService _hierarchicalMappingService; + _topicRepository = fixture.CachedTopicRepository; + _topic = _topicRepository.Load("Root:Web:Web_3:Web_3_0")!; - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish hierarchical topic mapping service \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. In addition, it initializes a shared reference to use for the various - /// tests. - /// - public HierarchicalTopicMappingServiceTest(TopicInfrastructureFixture fixture) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(fixture, nameof(fixture)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = fixture.CachedTopicRepository; - _topic = _topicRepository.Load("Root:Web:Web_3:Web_3_0")!; - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish hierarchical topic mapping service - \-----------------------------------------------------------------------------------------------------------------------*/ - _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( - new HierarchicalTopicMappingService( - fixture.TopicRepository, - fixture.MappingService - ) - ); - - } - - /*========================================================================================================================== - | TEST: GET HIERARCHICAL ROOT: WITH NULL TOPIC: RETURNS DEFAULT ROOT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method with no - /// currentTopic and ensures it falls back to the defaultRoot. - /// - [Fact] - public void GetHierarchicalRoot_WithNullTopic_ReturnsDefaultRoot() { + _hierarchicalMappingService = new CachedHierarchicalTopicMappingService( + new HierarchicalTopicMappingService( + fixture.TopicRepository, + fixture.MappingService + ) + ); - var rootTopic = _hierarchicalMappingService.GetHierarchicalRoot(null, 2, "Configuration"); + } - Assert.NotNull(rootTopic); - Assert.Equal("Configuration", rootTopic?.Key); + /*============================================================================================================================ + | TEST: GET HIERARCHICAL ROOT: WITH NULL TOPIC: RETURNS DEFAULT ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method with no + /// currentTopic and ensures it falls back to the defaultRoot. + /// + [Fact] + public void GetHierarchicalRoot_WithNullTopic_ReturnsDefaultRoot() { - } + var rootTopic = _hierarchicalMappingService.GetHierarchicalRoot(null, 2, "Configuration"); - /*========================================================================================================================== - | TEST: GET HIERARCHICAL ROOT: WITH NULL TOPIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method with no - /// currentTopic or defaultRoot and ensures it throws an . - /// - [Fact] - public void GetHierarchicalRoot_WithNullTopic_ThrowsException() => - Assert.Throws(() => - _hierarchicalMappingService.GetHierarchicalRoot(null, 2, "") - ); - - /*========================================================================================================================== - | TEST: GET HIERARCHICAL ROOT: WITH INVALID DEFAULT ROOT: TRHOWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method with no - /// currentTopic and throws an when it cannot identify the defaultRoot. - /// - [Fact] - public void GetHierarchicalRoot_WithInvalidDefaultRoot_ThrowsException() => - Assert.Throws(() => - _hierarchicalMappingService.GetHierarchicalRoot(null, 2, "InvalidDefaultRoot") - ); - - /*========================================================================================================================== - | TEST: GET HIERARCHICAL ROOT: WITH DEEP TOPIC: RETURNS ROOT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method with a deeply - /// nested topic and ensures that it returns the expected root. - /// - [Fact] - public void GetHierarchicalRoot_WithDeepTopic_ReturnsRoot() { + Assert.NotNull(rootTopic); + Assert.Equal("Configuration", rootTopic?.Key); - var rootTopic = _hierarchicalMappingService.GetHierarchicalRoot(_topic, 2, "Configuration"); + } - Assert.NotNull(rootTopic); - Assert.Equal("Web", rootTopic?.Key); + /*============================================================================================================================ + | TEST: GET HIERARCHICAL ROOT: WITH NULL TOPIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method with no + /// currentTopic or defaultRoot and ensures it throws an . + /// + [Fact] + public void GetHierarchicalRoot_WithNullTopic_ThrowsException() => + Assert.Throws(() => + _hierarchicalMappingService.GetHierarchicalRoot(null, 2, "") + ); - } + /*============================================================================================================================ + | TEST: GET HIERARCHICAL ROOT: WITH INVALID DEFAULT ROOT: TRHOWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method with no + /// currentTopic and throws an when it cannot identify the defaultRoot. + /// + [Fact] + public void GetHierarchicalRoot_WithInvalidDefaultRoot_ThrowsException() => + Assert.Throws(() => + _hierarchicalMappingService.GetHierarchicalRoot(null, 2, "InvalidDefaultRoot") + ); - /*========================================================================================================================== - | TEST: GET VIEW MODEL: WITH TWO LEVELS: RETURNS GRAPH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method - /// and ensures that the expected data is returned. - /// - [Fact] - public async Task GetViewModel_WithTwoLevels_ReturnsGraph() { + /*============================================================================================================================ + | TEST: GET HIERARCHICAL ROOT: WITH DEEP TOPIC: RETURNS ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method with a deeply + /// nested topic and ensures that it returns the expected root. + /// + [Fact] + public void GetHierarchicalRoot_WithDeepTopic_ReturnsRoot() { - var rootTopic = _topicRepository.Load("Root:Web"); - var viewModel = await _hierarchicalMappingService.GetViewModelAsync(rootTopic, 1).ConfigureAwait(false); + var rootTopic = _hierarchicalMappingService.GetHierarchicalRoot(_topic, 2, "Configuration"); - Assert.NotNull(viewModel); - Assert.Equal(3, viewModel?.Children.Count); - Assert.Empty(viewModel?.Children[0].Children); + Assert.NotNull(rootTopic); + Assert.Equal("Web", rootTopic?.Key); - } + } - /*========================================================================================================================== - | TEST: GET VIEW MODEL: WITH VALIDATION DELEGATE: EXCLUDES TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method - /// with a validationDelegate and ensures that it correctly trims the topic graph. - /// - [Fact] - public async Task GetViewModel_WithValidationDelegate_ExcludesTopics() { - - var rootTopic = _topicRepository.Load("Root:Web"); - var viewModel = await _hierarchicalMappingService - .GetViewModelAsync(rootTopic, 2, (t) => t.Key.EndsWith("1", StringComparison.Ordinal)) - .ConfigureAwait(false); - - Assert.NotNull(viewModel); - Assert.Single(viewModel?.Children); - Assert.Single(viewModel?.Children[0].Children); - - } - - /*========================================================================================================================== - | TEST: GET VIEW MODEL: WITH DISABLED: EXCLUDES DISABLED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls method - /// with a topic in the graph, and ensures it is not returned. - /// - [Fact] - public async Task GetViewModel_WithDisabled_ExcludesDisabled() { + /*============================================================================================================================ + | TEST: GET VIEW MODEL: WITH TWO LEVELS: RETURNS GRAPH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method + /// and ensures that the expected data is returned. + /// + [Fact] + public async Task GetViewModel_WithTwoLevels_ReturnsGraph() { + + var rootTopic = _topicRepository.Load("Root:Web"); + var viewModel = await _hierarchicalMappingService.GetViewModelAsync(rootTopic, 1); + + Assert.NotNull(viewModel); + Assert.Equal(3, viewModel.Children.Count); + Assert.Empty(viewModel.Children[0].Children); + + } + + /*============================================================================================================================ + | TEST: GET VIEW MODEL: WITH VALIDATION DELEGATE: EXCLUDES TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method + /// with a validationDelegate and ensures that it correctly trims the topic graph. + /// + [Fact] + public async Task GetViewModel_WithValidationDelegate_ExcludesTopics() { + + var rootTopic = _topicRepository.Load("Root:Web"); + var viewModel = await _hierarchicalMappingService + .GetViewModelAsync(rootTopic, 2, (t) => t.Key.EndsWith('1')); + + Assert.NotNull(viewModel); + Assert.Single(viewModel.Children); + Assert.Single(viewModel.Children[0].Children); + + } + + /*============================================================================================================================ + | TEST: GET VIEW MODEL: WITH DISABLED: EXCLUDES DISABLED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls method + /// with a topic in the graph, and ensures it is not returned. + /// + [Fact] + public async Task GetViewModel_WithDisabled_ExcludesDisabled() { - var rootTopic = _topicRepository.Load("Root:Web:Web_3")!; - var disabledTopic = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); + var rootTopic = _topicRepository.Load("Root:Web:Web_3")!; + var disabledTopic = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); - Contract.Assume(disabledTopic); + Contract.Assume(disabledTopic); - rootTopic.IsDisabled = true; - disabledTopic.IsDisabled = true; + rootTopic.IsDisabled = true; + disabledTopic.IsDisabled = true; - var viewModel = await _hierarchicalMappingService.GetViewModelAsync(rootTopic, 1).ConfigureAwait(false); + var viewModel = await _hierarchicalMappingService.GetViewModelAsync(rootTopic, 1); - Assert.NotNull(viewModel); - Assert.Single(viewModel?.Children); + Assert.NotNull(viewModel); + Assert.Single(viewModel.Children); - //Revert state - rootTopic.IsDisabled = false; - disabledTopic.IsDisabled = false; + //Revert state + rootTopic.IsDisabled = false; + disabledTopic.IsDisabled = false; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ITopicRepositoryTest.cs b/OnTopic.Tests/ITopicRepositoryTest.cs index 13ef2e05..680bc0c2 100644 --- a/OnTopic.Tests/ITopicRepositoryTest.cs +++ b/OnTopic.Tests/ITopicRepositoryTest.cs @@ -9,225 +9,224 @@ using OnTopic.Tests.Fixtures; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC REPOSITORY TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +/// +/// These tests not only validate that the is functioning as expected, but also that the +/// underlying functions are also operating correctly. +/// +[ExcludeFromCodeCoverage] +[Xunit.Collection("Shared Repository")] +public class ITopicRepositoryTest { /*============================================================================================================================ - | CLASS: TOPIC REPOSITORY TEST + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Initializes a new instance of the with shared resources. /// /// - /// These tests not only validate that the is functioning as expected, but also that the - /// underlying functions are also operating correctly. + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. /// - [ExcludeFromCodeCoverage] - [Xunit.Collection("Shared Repository")] - public class ITopicRepositoryTest { + public ITopicRepositoryTest(TopicInfrastructureFixture fixture) { - /*========================================================================================================================== - | PRIVATE VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; + Contract.Requires(fixture, nameof(fixture)); - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. - /// - public ITopicRepositoryTest(TopicInfrastructureFixture fixture) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(fixture, nameof(fixture)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = fixture.CachedTopicRepository; - - } - - /*========================================================================================================================== - | TEST: LOAD: DEFAULT: RETURNS ROOT TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads the default topic and ensures there are the expected number of children. - /// - [Fact] - public void Load_Default_ReturnsTopicTopic() { + _topicRepository = fixture.CachedTopicRepository; - var rootTopic = _topicRepository.Load(); + } - Assert.Equal(2, rootTopic?.Children.Count); - Assert.Equal("Configuration", rootTopic?.Children.First().Key); - Assert.Equal("Web", rootTopic?.Children.Last().Key); + /*============================================================================================================================ + | TEST: LOAD: DEFAULT: RETURNS ROOT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads the default topic and ensures there are the expected number of children. + /// + [Fact] + public void Load_Default_ReturnsTopicTopic() { - } + var rootTopic = _topicRepository.Load(); - /*========================================================================================================================== - | TEST: LOAD: VALID UNIQUE KEY: RETURNS CORRECT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads topics and ensures there are the expected number of children. - /// - [Fact] - public void Load_ValidUniqueKey_ReturnsCorrectTopic() => - Assert.Equal("Page", _topicRepository.Load("Root:Configuration:ContentTypes:Page")?.Key); - - /*========================================================================================================================== - | TEST: LOAD: INVALID UNIQUE KEY: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads invalid topic key and ensures a null is returned. - /// - [Fact] - public void Load_InvalidUniqueKey_ReturnsTopic() => - Assert.Null(_topicRepository.Load("Root:Configuration:ContentTypes:InvalidContentType")); - - /*========================================================================================================================== - | TEST: LOAD: VALID TOPIC ID: RETURNS CORRECT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads topic by ID and ensures it is found. - /// - [Fact] - public void Load_ValidTopicId_ReturnsCorrectTopic() { + Assert.Equal(2, rootTopic?.Children.Count); + Assert.Equal("Configuration", rootTopic?.Children.First().Key); + Assert.Equal("Web", rootTopic?.Children.Last().Key); - var topic = _topicRepository.Load(11111); + } - Assert.NotNull(topic); - Assert.Equal("Web_1_1_1_1", topic?.Key); + /*============================================================================================================================ + | TEST: LOAD: VALID UNIQUE KEY: RETURNS CORRECT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads topics and ensures there are the expected number of children. + /// + [Fact] + public void Load_ValidUniqueKey_ReturnsCorrectTopic() => + Assert.Equal("Page", _topicRepository.Load("Root:Configuration:ContentTypes:Page")?.Key); - } + /*============================================================================================================================ + | TEST: LOAD: INVALID UNIQUE KEY: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads invalid topic key and ensures a null is returned. + /// + [Fact] + public void Load_InvalidUniqueKey_ReturnsTopic() => + Assert.Null(_topicRepository.Load("Root:Configuration:ContentTypes:InvalidContentType")); - /*========================================================================================================================== - | TEST: LOAD: INVALID TOPIC ID: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads topic by an incorrect ID and ensures it a null is returned. - /// - [Fact] - public void Load_InvalidTopicId_ReturnsNull() => - Assert.Null(_topicRepository.Load(9999999)); - - /*========================================================================================================================== - | TEST: SAVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves topics and ensures their identifiers are properly set. - /// - [Fact] - public void Save() { + /*============================================================================================================================ + | TEST: LOAD: VALID TOPIC ID: RETURNS CORRECT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads topic by ID and ensures it is found. + /// + [Fact] + public void Load_ValidTopicId_ReturnsCorrectTopic() { + + var topic = _topicRepository.Load(11111); + + Assert.NotNull(topic); + Assert.Equal("Web_1_1_1_1", topic?.Key); + + } + + /*============================================================================================================================ + | TEST: LOAD: INVALID TOPIC ID: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads topic by an incorrect ID and ensures it a null is returned. + /// + [Fact] + public void Load_InvalidTopicId_ReturnsNull() => + Assert.Null(_topicRepository.Load(9999999)); - var topic = new Topic("Test", "Page"); - var child = new Topic("Child", "Page", topic); + /*============================================================================================================================ + | TEST: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves topics and ensures their identifiers are properly set. + /// + [Fact] + public void Save() { - _topicRepository.Save(topic); + var topic = new Topic("Test", "Page"); + var child = new Topic("Child", "Page", topic); - Assert.NotEqual(-1, topic.Id); - Assert.Equal(-1, child.Id); + _topicRepository.Save(topic); - _topicRepository.Save(topic, true); + Assert.NotEqual(-1, topic.Id); + Assert.Equal(-1, child.Id); - Assert.NotEqual(-1, child.Id); + _topicRepository.Save(topic, true); - } + Assert.NotEqual(-1, child.Id); - /*========================================================================================================================== - | TEST: MOVE: TO NEW PARENT: CONFIRMED MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Moves topics and ensures their parents are correctly set. - /// - [Fact] - public void Move_ToNewParent_ConfirmedMove() { + } - var source = new Topic("OriginalParent", "Page"); - var destination = new Topic("NewParent", "Page"); - var topic = new Topic("Topic", "Page", source); - _ = new Topic("Sibling", "Page", source); + /*============================================================================================================================ + | TEST: MOVE: TO NEW PARENT: CONFIRMED MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Moves topics and ensures their parents are correctly set. + /// + [Fact] + public void Move_ToNewParent_ConfirmedMove() { - _topicRepository.Move(topic, destination); + var source = new Topic("OriginalParent", "Page"); + var destination = new Topic("NewParent", "Page"); + var topic = new Topic("Topic", "Page", source); + _ = new Topic("Sibling", "Page", source); - Assert.Equal(topic.Parent, destination); - Assert.Single(source.Children); - Assert.Single(destination.Children); + _topicRepository.Move(topic, destination); - } + Assert.Equal(topic.Parent, destination); + Assert.Single(source.Children); + Assert.Single(destination.Children); - /*========================================================================================================================== - | TEST: MOVE: TO NEW SIBLING: CONFIRMED MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Moves topic next to a different sibling and ensures it ends up in the correct location. - /// - [Fact] - public void Move_ToNewSibling_ConfirmedMove() { + } - var parent = new Topic("OriginalParent", "Page"); - var topic = new Topic("Topic", "Page", parent); - var sibling = new Topic("Sibling", "Page", parent); + /*============================================================================================================================ + | TEST: MOVE: TO NEW SIBLING: CONFIRMED MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Moves topic next to a different sibling and ensures it ends up in the correct location. + /// + [Fact] + public void Move_ToNewSibling_ConfirmedMove() { - _topicRepository.Move(topic, parent, sibling); + var parent = new Topic("OriginalParent", "Page"); + var topic = new Topic("Topic", "Page", parent); + var sibling = new Topic("Sibling", "Page", parent); - Assert.Equal(topic.Parent, parent); - Assert.Equal(2, parent.Children.Count); - Assert.Equal("Sibling", parent.Children.First().Key); - Assert.Equal("Topic", parent.Children[1].Key); + _topicRepository.Move(topic, parent, sibling); - } + Assert.Equal(topic.Parent, parent); + Assert.Equal(2, parent.Children.Count); + Assert.Equal("Sibling", parent.Children.First().Key); + Assert.Equal("Topic", parent.Children[1].Key); - /*========================================================================================================================== - | TEST: DELETE: TOPIC: REMOVED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic to ensure it is properly removed. - /// - [Fact] - public void Delete_Topic_Removed() { + } + + /*============================================================================================================================ + | TEST: DELETE: TOPIC: REMOVED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic to ensure it is properly removed. + /// + [Fact] + public void Delete_Topic_Removed() { - var parent = new Topic("OriginalParent", "Page"); - var topic = new Topic("Topic", "Page", parent); - _ = new Topic("child", "Page", topic); + var parent = new Topic("OriginalParent", "Page"); + var topic = new Topic("Topic", "Page", parent); + _ = new Topic("child", "Page", topic); - _topicRepository.Delete(topic, true); + _topicRepository.Delete(topic, true); - Assert.Empty(parent.Children); + Assert.Empty(parent.Children); - } + } - /*========================================================================================================================== - | TEST: DELETE: DELETE EVENT: IS FIRED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a and then immediately deletes it. Ensures that the is fired, even though the original event is fired from the underlying - /// and not the immediate . - /// - [Fact] - public void Delete_DeleteEvent_IsFired() { + /*============================================================================================================================ + | TEST: DELETE: DELETE EVENT: IS FIRED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a and then immediately deletes it. Ensures that the is fired, even though the original event is fired from the underlying + /// and not the immediate . + /// + [Fact] + public void Delete_DeleteEvent_IsFired() { - var topic = new Topic("Test", "Page"); - var hasFired = false; + var topic = new Topic("Test", "Page"); + var hasFired = false; - _topicRepository.Save(topic); - _topicRepository.TopicDeleted += eventHandler; - _topicRepository.Delete(topic); + _topicRepository.Save(topic); + _topicRepository.TopicDeleted += eventHandler; + _topicRepository.Delete(topic); - Assert.True(hasFired); + Assert.True(hasFired); - void eventHandler(object? sender, TopicEventArgs eventArgs) => hasFired = true; + void eventHandler(object? sender, TopicEventArgs eventArgs) => hasFired = true; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ITypeLookupServiceTest.cs b/OnTopic.Tests/ITypeLookupServiceTest.cs index 50d8a007..b2760ad2 100644 --- a/OnTopic.Tests/ITypeLookupServiceTest.cs +++ b/OnTopic.Tests/ITypeLookupServiceTest.cs @@ -8,72 +8,71 @@ using OnTopic.Tests.ViewModels; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TYPE LOOKUP SERVICE TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the interface and its implementations, including the +/// and . +/// +[ExcludeFromCodeCoverage] +public class ITypeLookupServiceTest { /*============================================================================================================================ - | CLASS: TYPE LOOKUP SERVICE TEST + | TEST: COMPOSITE: LOOKUP VALID TYPE: RETURNS TYPE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the interface and its implementations, including the - /// and . + /// Assembles a new with two instances of a and + /// confirms that it returns the expected for a + /// query. /// - [ExcludeFromCodeCoverage] - public class ITypeLookupServiceTest { - - /*========================================================================================================================== - | TEST: COMPOSITE: LOOKUP VALID TYPE: RETURNS TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new with two instances of a and - /// confirms that it returns the expected for a - /// query. - /// - [Fact] - public void Composite_LookupValidType_ReturnsType() { + [Fact] + public void Composite_LookupValidType_ReturnsType() { - var lookupServiceA = new FakeViewModelLookupService(); - var lookupServiceB = new TopicViewModelLookupService(); - var compositeLookup = new CompositeTypeLookupService(lookupServiceA, lookupServiceB); + var lookupServiceA = new FakeViewModelLookupService(); + var lookupServiceB = new TopicViewModelLookupService(); + var compositeLookup = new CompositeTypeLookupService(lookupServiceA, lookupServiceB); - Assert.Equal(typeof(SlideshowTopicViewModel), compositeLookup.Lookup(nameof(SlideshowTopicViewModel))); - Assert.Equal(typeof(MapToParentTopicViewModel), compositeLookup.Lookup(nameof(MapToParentTopicViewModel))); - Assert.Null(compositeLookup.Lookup(nameof(Topic))); + Assert.Equal(typeof(SlideshowTopicViewModel), compositeLookup.Lookup(nameof(SlideshowTopicViewModel))); + Assert.Equal(typeof(MapToParentTopicViewModel), compositeLookup.Lookup(nameof(MapToParentTopicViewModel))); + Assert.Null(compositeLookup.Lookup(nameof(Topic))); - } + } - /*========================================================================================================================== - | TEST: DYNAMIC TOPIC VIEW MODEL LOOKUP SERVICE: LOOKUP TOPIC VIEW MODEL: RETURNS FALLBACK VIEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new and requests a type with the TopicViewModel - /// suffix; confirms it correctly falls back to a type with the ViewModel suffix. - /// - [Fact] - public void DynamicTopicViewModelLookupService_LookupTopicViewModel_ReturnsFallbackViewModel() { + /*============================================================================================================================ + | TEST: DYNAMIC TOPIC VIEW MODEL LOOKUP SERVICE: LOOKUP TOPIC VIEW MODEL: RETURNS FALLBACK VIEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new and requests a type with the TopicViewModel + /// suffix; confirms it correctly falls back to a type with the ViewModel suffix. + /// + [Fact] + public void DynamicTopicViewModelLookupService_LookupTopicViewModel_ReturnsFallbackViewModel() { - var lookupService = new DynamicTopicViewModelLookupService(); - var topicViewModel = lookupService.Lookup("FallbackTopicViewModel", "FallbackViewModel"); + var lookupService = new DynamicTopicViewModelLookupService(); + var topicViewModel = lookupService.Lookup("FallbackTopicViewModel", "FallbackViewModel"); - Assert.Equal(typeof(FallbackViewModel), topicViewModel); + Assert.Equal(typeof(FallbackViewModel), topicViewModel); - } + } - /*========================================================================================================================== - | TEST: DEFAULT TOPIC VIEW MODEL LOOKUP SERVICE: LOOKUP TOPIC VIEW MODEL: RETURNS FALLBACK VIEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new and requests a type with the TopicViewModel - /// suffix; confirms it correctly falls back to a type with the ViewModel suffix. - /// - [Fact] - public void TopicViewModelLookupService_LookupTopicViewModel_ReturnsFallbackViewModel() { + /*============================================================================================================================ + | TEST: DEFAULT TOPIC VIEW MODEL LOOKUP SERVICE: LOOKUP TOPIC VIEW MODEL: RETURNS FALLBACK VIEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new and requests a type with the TopicViewModel + /// suffix; confirms it correctly falls back to a type with the ViewModel suffix. + /// + [Fact] + public void TopicViewModelLookupService_LookupTopicViewModel_ReturnsFallbackViewModel() { - var lookupService = new FakeViewModelLookupService(); - var topicViewModel = lookupService.Lookup("FallbackTopicViewModel", "FallbackViewModel"); + var lookupService = new FakeViewModelLookupService(); + var topicViewModel = lookupService.Lookup("FallbackTopicViewModel", "FallbackViewModel"); - Assert.Equal(typeof(FallbackViewModel), topicViewModel); + Assert.Equal(typeof(FallbackViewModel), topicViewModel); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Internal/IsExternalInit.cs b/OnTopic.Tests/Internal/IsExternalInit.cs index 2bd828ad..adbc401b 100644 --- a/OnTopic.Tests/Internal/IsExternalInit.cs +++ b/OnTopic.Tests/Internal/IsExternalInit.cs @@ -4,16 +4,15 @@ | Project Topics Library \=============================================================================================================================*/ -namespace System.Runtime.CompilerServices { +namespace System.Runtime.CompilerServices; - /*============================================================================================================================ - | CLASS: IS EXTERNAL INIT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The class is made available as part of the .NET 5.0 CLR in order to enable init accessors. - /// As this is not available in .NET Standard, however, we must maintain this separate copy until we migrate to .NET 5.0. - /// - internal static class IsExternalInit { +/*============================================================================================================================== +| CLASS: IS EXTERNAL INIT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The class is made available as part of the .NET 5.0 CLR in order to enable init accessors. +/// As this is not available in .NET Standard, however, we must maintain this separate copy until we migrate to .NET 5.0. +/// +internal static class IsExternalInit { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/KeyedTopicCollectionTest.cs b/OnTopic.Tests/KeyedTopicCollectionTest.cs index 82c33fc1..72c88e53 100644 --- a/OnTopic.Tests/KeyedTopicCollectionTest.cs +++ b/OnTopic.Tests/KeyedTopicCollectionTest.cs @@ -6,187 +6,186 @@ using OnTopic.Collections; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: KEYED TOPIC COLLECTION TESTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class KeyedTopicCollectionTest { /*============================================================================================================================ - | CLASS: KEYED TOPIC COLLECTION TESTS + | TEST: SET TOPIC: INDEXER: RETURNS TOPIC \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Establishes a number of topics, then accesses them by key. /// - [ExcludeFromCodeCoverage] - public class KeyedTopicCollectionTest { - - /*========================================================================================================================== - | TEST: SET TOPIC: INDEXER: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a number of topics, then accesses them by key. - /// - [Fact] - public void SetTopic_Indexer_ReturnsTopic() { - - var topics = new KeyedTopicCollection(); - - for (var i = 0; i < 10; i++) { - topics.Add(new("Topic" + i, "Page")); - } + [Fact] + public void SetTopic_Indexer_ReturnsTopic() { - Assert.Equal("Topic3", topics["Topic3"].Key); + var topics = new KeyedTopicCollection(); + for (var i = 0; i < 10; i++) { + topics.Add(new("Topic" + i, "Page")); } - /*========================================================================================================================== - | TEST: CONSTRUCTOR: IENUMERABLE: SEEDS TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a number of topics, then seeds a new with them. - /// - [Fact] - public void Constructor_IEnumerable_SeedsTopics() { + Assert.Equal("Topic3", topics["Topic3"].Key); - var topics = new List(); - - for (var i = 0; i < 10; i++) { - topics.Add(new("Topic" + i, "Page")); - } + } - var topicsCollection = new KeyedTopicCollection(topics); + /*============================================================================================================================ + | TEST: CONSTRUCTOR: IENUMERABLE: SEEDS TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a number of topics, then seeds a new with them. + /// + [Fact] + public void Constructor_IEnumerable_SeedsTopics() { - Assert.Equal(10, topicsCollection.Count); + var topics = new List(); + for (var i = 0; i < 10; i++) { + topics.Add(new("Topic" + i, "Page")); } - /*========================================================================================================================== - | TEST: INSERT ITEM: DUPLICATE KEY: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to add two instances with the same to a and confirms that a is correctly thrown. - /// - [Fact] - public void InsertItem_DuplicateKey_ThrowsException() => - Assert.Throws(() => - new KeyedTopicCollection { - new Topic("Key", "Page"), - new Topic("Key", "Page") - } - ); - - /*========================================================================================================================== - | TEST: READ ONLY KEYED TOPIC COLLECTION: EMPTY COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a without a backing - /// and confirms that it successfully initialized with zero items. - /// - [Fact] - public void ReadOnlyKeyedTopicCollection_EmptyCollection() { - - var readOnlyCollection = new ReadOnlyKeyedTopicCollection(); - - Assert.Empty(readOnlyCollection); + var topicsCollection = new KeyedTopicCollection(topics); - } + Assert.Equal(10, topicsCollection.Count); - /*========================================================================================================================== - | TEST: READ ONLY KEYED TOPIC COLLECTION: GET VALUE: RETURNS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a backing and - /// confirms that it successfully returns a by using . - /// - [Fact] - public void ReadOnlyKeyedTopicCollection_GetValue_ReturnsValue() { + } - var collection = new KeyedTopicCollection(); - var readOnlyCollection = new ReadOnlyKeyedTopicCollection(collection); - var topic = new Topic("Topic", "Page"); + /*============================================================================================================================ + | TEST: INSERT ITEM: DUPLICATE KEY: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to add two instances with the same to a and confirms that a is correctly thrown. + /// + [Fact] + public void InsertItem_DuplicateKey_ThrowsException() => + Assert.Throws(() => + new KeyedTopicCollection { + new Topic("Key", "Page"), + new Topic("Key", "Page") + } + ); - collection.Add(topic); + /*============================================================================================================================ + | TEST: READ ONLY KEYED TOPIC COLLECTION: EMPTY COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a without a backing + /// and confirms that it successfully initialized with zero items. + /// + [Fact] + public void ReadOnlyKeyedTopicCollection_EmptyCollection() { - Assert.Equal(topic, readOnlyCollection.GetValue(topic.Key)); + var readOnlyCollection = new ReadOnlyKeyedTopicCollection(); - } + Assert.Empty(readOnlyCollection); - /*========================================================================================================================== - | TEST: READ ONLY KEYED TOPIC COLLECTION: INDEXER: RETURNS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a backing and - /// confirms that it successfully returns a by using the indexer on . - /// - [Fact] - public void ReadOnlyKeyedTopicCollection_Indexer_ReturnsValue() { + } - var collection = new KeyedTopicCollection(); - var readOnlyCollection = new ReadOnlyKeyedTopicCollection(collection); - var topic = new Topic("Topic", "Page"); + /*============================================================================================================================ + | TEST: READ ONLY KEYED TOPIC COLLECTION: GET VALUE: RETURNS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a backing and + /// confirms that it successfully returns a by using . + /// + [Fact] + public void ReadOnlyKeyedTopicCollection_GetValue_ReturnsValue() { - collection.Add(topic); + var collection = new KeyedTopicCollection(); + var readOnlyCollection = new ReadOnlyKeyedTopicCollection(collection); + var topic = new Topic("Topic", "Page"); - Assert.Equal(topic, readOnlyCollection[topic.Key]); + collection.Add(topic); - } + Assert.Equal(topic, readOnlyCollection.GetValue(topic.Key)); + } - /*========================================================================================================================== - | TEST: READ ONLY KEYED TOPIC COLLECTION: GET VALUE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a backing and - /// confirms that it returns null if when calling with an - /// invalid . - /// - [Fact] - public void ReadOnlyKeyedTopicCollection_GetValue_ReturnsNull() => - Assert.Null(new ReadOnlyKeyedTopicCollection().GetValue("InvalidKey")); - - /*========================================================================================================================== - | TEST: AS READ ONLY: RETURNS READ ONLY KEYED TOPIC COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a number of topics, converts the collection to read only, and ensures they are still present. - /// - [Fact] - public void AsReadOnly_ReturnsReadOnlyKeyedTopicCollection() { - - var topics = new KeyedTopicCollection(); - - for (var i = 0; i < 10; i++) { - topics.Add(new("Topic" + i, "Page")); - } + /*============================================================================================================================ + | TEST: READ ONLY KEYED TOPIC COLLECTION: INDEXER: RETURNS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a backing and + /// confirms that it successfully returns a by using the indexer on . + /// + [Fact] + public void ReadOnlyKeyedTopicCollection_Indexer_ReturnsValue() { + + var collection = new KeyedTopicCollection(); + var readOnlyCollection = new ReadOnlyKeyedTopicCollection(collection); + var topic = new Topic("Topic", "Page"); - var readOnlyCollection = topics.AsReadOnly(); + collection.Add(topic); - Assert.Equal(10, readOnlyCollection.Count); - Assert.Equal("Topic0", readOnlyCollection.First().Key); + Assert.Equal(topic, readOnlyCollection[topic.Key]); + } + + + /*============================================================================================================================ + | TEST: READ ONLY KEYED TOPIC COLLECTION: GET VALUE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a backing and + /// confirms that it returns null if when calling with an + /// invalid . + /// + [Fact] + public void ReadOnlyKeyedTopicCollection_GetValue_ReturnsNull() => + Assert.Null(new ReadOnlyKeyedTopicCollection().GetValue("InvalidKey")); + + /*============================================================================================================================ + | TEST: AS READ ONLY: RETURNS READ ONLY KEYED TOPIC COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a number of topics, converts the collection to read only, and ensures they are still present. + /// + [Fact] + public void AsReadOnly_ReturnsReadOnlyKeyedTopicCollection() { + + var topics = new KeyedTopicCollection(); + + for (var i = 0; i < 10; i++) { + topics.Add(new("Topic" + i, "Page")); } - /*========================================================================================================================== - | TEST: AS READ ONLY: RETURNS READ ONLY TOPIC COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a number of topics, converts the collection to read only, and ensures they are still present. - /// - [Fact] - public void AsReadOnly_ReturnsReadOnlyTopicCollection() { + var readOnlyCollection = topics.AsReadOnly(); - var topics = new TopicCollection(); + Assert.Equal(10, readOnlyCollection.Count); + Assert.Equal("Topic0", readOnlyCollection.First().Key); - for (var i = 0; i < 10; i++) { - topics.Add(new("Topic" + i, "Page")); - } + } - var readOnlyCollection = topics.AsReadOnly(); + /*============================================================================================================================ + | TEST: AS READ ONLY: RETURNS READ ONLY TOPIC COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a number of topics, converts the collection to read only, and ensures they are still present. + /// + [Fact] + public void AsReadOnly_ReturnsReadOnlyTopicCollection() { - Assert.Equal(10, readOnlyCollection.Count); - Assert.Equal("Topic0", readOnlyCollection.First().Key); + var topics = new TopicCollection(); + for (var i = 0; i < 10; i++) { + topics.Add(new("Topic" + i, "Page")); } - } //Class -} //Namespace \ No newline at end of file + var readOnlyCollection = topics.AsReadOnly(); + + Assert.Equal(10, readOnlyCollection.Count); + Assert.Equal("Topic0", readOnlyCollection.First().Key); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/MemberAccessorTest.cs b/OnTopic.Tests/MemberAccessorTest.cs index 1b61c67c..f69738b4 100644 --- a/OnTopic.Tests/MemberAccessorTest.cs +++ b/OnTopic.Tests/MemberAccessorTest.cs @@ -8,400 +8,399 @@ using OnTopic.Tests.ViewModels; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: MEMBER ACCESSOR TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides basic unit tests for the class. +/// +/// +/// Most access to the class will be through higher-level classes which provide type validation +/// and conversion. As a result, the unit tests for the will focus on the more fundamental +/// behavior of validating and translating a object into a . +/// +[ExcludeFromCodeCoverage] +public class MemberAccessorTest { /*============================================================================================================================ - | CLASS: MEMBER ACCESSOR TEST + | TEST: IS NULLABLE: NULLABLE PROPERTY: RETURNS TRUE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides basic unit tests for the class. + /// Assembles a new from a that is nullable, and confirms that the + /// property is set to true. + /// + [Fact] + public void IsNullable_NullableProperty_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NullableProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.True(memberAccessor.IsNullable); + + } + + /*============================================================================================================================ + | TEST: IS NULLABLE: NON-NULLABLE PROPERTY: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that is not nullable, and confirms that + /// the property is set to false. + /// + [Fact] + public void IsNullable_NonNullableProperty_ReturnsFalse() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.False(memberAccessor.IsNullable); + + } + + /*============================================================================================================================ + | TEST: IS NULLABLE: NON-NULLABLE REFERENCE PROPERTY: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that is a non-nullable reference type, + /// and confirms that the property is set to true. /// /// - /// Most access to the class will be through higher-level classes which provide type validation - /// and conversion. As a result, the unit tests for the will focus on the more fundamental - /// behavior of validating and translating a object into a . + /// Unfortunately, the .NET reflection libraries don't (yet) have the ability to determine if a nullable reference types + /// are nullable or not, and thus this should always return true. /// - [ExcludeFromCodeCoverage] - public class MemberAccessorTest { - - /*========================================================================================================================== - | TEST: IS NULLABLE: NULLABLE PROPERTY: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is nullable, and confirms that the - /// property is set to true. - /// - [Fact] - public void IsNullable_NullableProperty_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NullableProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.True(memberAccessor.IsNullable); - - } - - /*========================================================================================================================== - | TEST: IS NULLABLE: NON-NULLABLE PROPERTY: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is not nullable, and confirms that - /// the property is set to false. - /// - [Fact] - public void IsNullable_NonNullableProperty_ReturnsFalse() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.False(memberAccessor.IsNullable); - - } - - /*========================================================================================================================== - | TEST: IS NULLABLE: NON-NULLABLE REFERENCE PROPERTY: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is a non-nullable reference type, - /// and confirms that the property is set to true. - /// - /// - /// Unfortunately, the .NET reflection libraries don't (yet) have the ability to determine if a nullable reference types - /// are nullable or not, and thus this should always return true. - /// - [Fact] - public void IsNullable_NonNullableReferenceProperty_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableReferenceGetter)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.True(memberAccessor.IsNullable); - - } - - /*========================================================================================================================== - | TEST: IS GETTABLE: READ-ONLY PROPERTY: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is read-only, and confirms that the - /// property is set to true. - /// - [Fact] - public void IsGettable_ReadOnlyProperty_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.ReadOnlyProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.True(memberAccessor.CanRead); - - } - - /*========================================================================================================================== - | TEST: IS GETTABLE: WRITE-ONLY PROPERTY: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is write-only, and confirms that the - /// property is set to false. - /// - [Fact] - public void IsGettable_WriteOnlyProperty_ReturnsFalse() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.WriteOnlyProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.False(memberAccessor.CanRead); - - } - - /*========================================================================================================================== - | TEST: IS SETTABLE: WRITE-ONLY PROPERTY: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is write-only, and confirms that the - /// property is set to false. - /// - [Fact] - public void IsSettable_WriteOnlyProperty_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.WriteOnlyProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.True(memberAccessor.CanWrite); - - } - - /*========================================================================================================================== - | TEST: IS SETTABLE: READ-ONLY PROPERTY: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that is read-only, and confirms that the - /// property is set to false. - /// - [Fact] - public void IsSettable_ReadOnlyProperty_ReturnsFalse() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.ReadOnlyProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.False(memberAccessor.CanWrite); - - } - - /*========================================================================================================================== - | TEST: GET VALUE: VALID PROPERTY: RETURNS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be returned. - /// - [Fact] - public void GetValue_ValidProperty_ReturnsValue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - var sourceObject = new MemberAccessorViewModel() { NonNullableProperty = 15 }; - var returnObject = memberAccessor.GetValue(sourceObject); - - Assert.Equal(sourceObject.NonNullableProperty, returnObject); - - } - - /*========================================================================================================================== - | TEST: GET VALUE: VALID METHOD: RETURNS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be returned. - /// - [Theory] - [InlineData(15)] - [InlineData(null)] - public void GetValue_ValidMethod_ReturnsValue(int? value) { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.GetMethod)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - var sourceObject = new MemberAccessorViewModel(); - - sourceObject.SetMethod(value); - - var returnObject = memberAccessor.GetValue(sourceObject); - - Assert.Equal(value, returnObject); - - } - - /*========================================================================================================================== - | TEST: GET VALUE: TYPE MISMATCH: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a , and attempts to call with an object that doesn't contain the , expecting that an - /// will be thrown. - /// - [Fact] - public void GetValue_TypeMismatch_ThrowsException() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.ReadOnlyProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.Throws(() => - memberAccessor.GetValue(new object()) - ); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: VALID PROPERTY: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be - /// set. - /// - [Theory] - [InlineData(15)] - [InlineData(null)] - public void SetValue_ValidProperty_SetsValue(int? value) { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NullableProperty)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - var sourceObject = new MemberAccessorViewModel { - NullableProperty = 5 - }; - memberAccessor.SetValue(sourceObject, value); - - Assert.Equal(value, sourceObject.NullableProperty); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: VALID METHOD: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be - /// set. - /// - [Theory] - [InlineData(15)] - [InlineData(null)] - public void SetValue_ValidMethod_SetsValue(int? value) { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.SetMethod)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - var sourceObject = new MemberAccessorViewModel(); - - sourceObject.SetMethod(5); - memberAccessor.SetValue(sourceObject, value); - - Assert.Equal(value, sourceObject.GetMethod()); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: MEMBER TYPE MISMATCH: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a , and attempts to call with an object that isn't compatible with the , expecting that an will be thrown. - /// - [Fact] - public void SetValue_MemberTypeMismatch_ThrowsException() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableReferenceGetter)).FirstOrDefault()!; - var memberAccessor = new MemberAccessor(memberInfo); - - Assert.Throws(() => - memberAccessor.SetValue(new MemberAccessorViewModel(), new object()) - ); - - } - - /*========================================================================================================================== - | TEST: IS VALID: PROPERTY: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates a that is a and confirms that it is accepted. - /// - [Fact] - public void IsValid_Property_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetProperty(nameof(MemberAccessorViewModel.NonNullableProperty))!; - - Assert.True(MemberAccessor.IsValid(memberInfo)); - - } - - /*========================================================================================================================== - | TEST: IS VALID: GETTER METHOD: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates a that is a with a return type and no parameters and - /// confirms that it is accepted. - /// - [Fact] - public void IsValid_GetterMethod_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.GetMethod))!; - - Assert.NotNull(memberInfo); - Assert.True(MemberAccessor.IsValid(memberInfo)); - - } - - /*========================================================================================================================== - | TEST: IS VALID: INVALID GETTER METHOD: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates a that is a with a parameter and confirms that it is - /// rejected. - /// - /// - /// The is only designed to be able to get methods that have a return type and no parameters. - /// - [Fact] - public void IsValid_InvalidGetterMethod_ReturnsFalse() - { - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.InvalidGetMethod))!; - - Assert.NotNull(memberInfo); - Assert.False(MemberAccessor.IsValid(memberInfo)); - - } - - /*========================================================================================================================== - | TEST: IS VALID: SETTER METHOD: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates a that is a with no return type and one parameter and - /// confirms that it is accepted. - /// - [Fact] - public void IsValid_SetterMethod_ReturnsTrue() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.SetMethod))!; - - Assert.True(MemberAccessor.IsValid(memberInfo)); - - } - - /*========================================================================================================================== - | TEST: IS VALID: INVALID SETTER METHOD: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates a that is a with no return type and two parameters and - /// confirms that it is rejected. - /// - /// - /// The is only designed to be able to set methods that are void and accept a single - /// parameter. - /// - [Fact] - public void IsValid_InvalidSetterMethod_ReturnsFalse() - { - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.InvalidSetMethod))!; - - Assert.NotNull(memberInfo); - Assert.False(MemberAccessor.IsValid(memberInfo)); - - } - - /*========================================================================================================================== - | TEST: IS VALID: CONSTRUCTOR: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates a that is not a or a and - /// confirms that it is rejected. - /// - [Fact] - public void IsValid_Constructor_ReturnsFalse() { - - var type = typeof(MemberAccessorViewModel); - var memberInfo = type.GetConstructor(Array.Empty())!; - - Assert.NotNull(memberInfo); - Assert.False(MemberAccessor.IsValid(memberInfo)); - - } - - } //Class -} //Namespace \ No newline at end of file + [Fact] + public void IsNullable_NonNullableReferenceProperty_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableReferenceGetter)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.True(memberAccessor.IsNullable); + + } + + /*============================================================================================================================ + | TEST: IS GETTABLE: READ-ONLY PROPERTY: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that is read-only, and confirms that the + /// property is set to true. + /// + [Fact] + public void IsGettable_ReadOnlyProperty_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.ReadOnlyProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.True(memberAccessor.CanRead); + + } + + /*============================================================================================================================ + | TEST: IS GETTABLE: WRITE-ONLY PROPERTY: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that is write-only, and confirms that the + /// property is set to false. + /// + [Fact] + public void IsGettable_WriteOnlyProperty_ReturnsFalse() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.WriteOnlyProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.False(memberAccessor.CanRead); + + } + + /*============================================================================================================================ + | TEST: IS SETTABLE: WRITE-ONLY PROPERTY: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that is write-only, and confirms that the + /// property is set to false. + /// + [Fact] + public void IsSettable_WriteOnlyProperty_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.WriteOnlyProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.True(memberAccessor.CanWrite); + + } + + /*============================================================================================================================ + | TEST: IS SETTABLE: READ-ONLY PROPERTY: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that is read-only, and confirms that the + /// property is set to false. + /// + [Fact] + public void IsSettable_ReadOnlyProperty_ReturnsFalse() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.ReadOnlyProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.False(memberAccessor.CanWrite); + + } + + /*============================================================================================================================ + | TEST: GET VALUE: VALID PROPERTY: RETURNS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be returned. + /// + [Fact] + public void GetValue_ValidProperty_ReturnsValue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + var sourceObject = new MemberAccessorViewModel() { NonNullableProperty = 15 }; + var returnObject = memberAccessor.GetValue(sourceObject); + + Assert.Equal(sourceObject.NonNullableProperty, returnObject); + + } + + /*============================================================================================================================ + | TEST: GET VALUE: VALID METHOD: RETURNS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be returned. + /// + [Theory] + [InlineData(15)] + [InlineData(null)] + public void GetValue_ValidMethod_ReturnsValue(int? value) { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.GetMethod)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + var sourceObject = new MemberAccessorViewModel(); + + sourceObject.SetMethod(value); + + var returnObject = memberAccessor.GetValue(sourceObject); + + Assert.Equal(value, returnObject); + + } + + /*============================================================================================================================ + | TEST: GET VALUE: TYPE MISMATCH: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a , and attempts to call with an object that doesn't contain the , expecting that an + /// will be thrown. + /// + [Fact] + public void GetValue_TypeMismatch_ThrowsException() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.ReadOnlyProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.Throws(() => + memberAccessor.GetValue(new object()) + ); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: VALID PROPERTY: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be + /// set. + /// + [Theory] + [InlineData(15)] + [InlineData(null)] + public void SetValue_ValidProperty_SetsValue(int? value) { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NullableProperty)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + var sourceObject = new MemberAccessorViewModel { + NullableProperty = 5 + }; + memberAccessor.SetValue(sourceObject, value); + + Assert.Equal(value, sourceObject.NullableProperty); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: VALID METHOD: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a , and attempts to call with a compliant object, expecting that the correct value will be + /// set. + /// + [Theory] + [InlineData(15)] + [InlineData(null)] + public void SetValue_ValidMethod_SetsValue(int? value) { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.SetMethod)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + var sourceObject = new MemberAccessorViewModel(); + + sourceObject.SetMethod(5); + memberAccessor.SetValue(sourceObject, value); + + Assert.Equal(value, sourceObject.GetMethod()); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: MEMBER TYPE MISMATCH: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a , and attempts to call with an object that isn't compatible with the , expecting that an will be thrown. + /// + [Fact] + public void SetValue_MemberTypeMismatch_ThrowsException() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMember(nameof(MemberAccessorViewModel.NonNullableReferenceGetter)).FirstOrDefault()!; + var memberAccessor = new MemberAccessor(memberInfo); + + Assert.Throws(() => + memberAccessor.SetValue(new MemberAccessorViewModel(), new object()) + ); + + } + + /*============================================================================================================================ + | TEST: IS VALID: PROPERTY: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates a that is a and confirms that it is accepted. + /// + [Fact] + public void IsValid_Property_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetProperty(nameof(MemberAccessorViewModel.NonNullableProperty))!; + + Assert.True(MemberAccessor.IsValid(memberInfo)); + + } + + /*============================================================================================================================ + | TEST: IS VALID: GETTER METHOD: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates a that is a with a return type and no parameters and + /// confirms that it is accepted. + /// + [Fact] + public void IsValid_GetterMethod_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.GetMethod))!; + + Assert.NotNull(memberInfo); + Assert.True(MemberAccessor.IsValid(memberInfo)); + + } + + /*============================================================================================================================ + | TEST: IS VALID: INVALID GETTER METHOD: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates a that is a with a parameter and confirms that it is + /// rejected. + /// + /// + /// The is only designed to be able to get methods that have a return type and no parameters. + /// + [Fact] + public void IsValid_InvalidGetterMethod_ReturnsFalse() + { + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.InvalidGetMethod))!; + + Assert.NotNull(memberInfo); + Assert.False(MemberAccessor.IsValid(memberInfo)); + + } + + /*============================================================================================================================ + | TEST: IS VALID: SETTER METHOD: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates a that is a with no return type and one parameter and + /// confirms that it is accepted. + /// + [Fact] + public void IsValid_SetterMethod_ReturnsTrue() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.SetMethod))!; + + Assert.True(MemberAccessor.IsValid(memberInfo)); + + } + + /*============================================================================================================================ + | TEST: IS VALID: INVALID SETTER METHOD: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates a that is a with no return type and two parameters and + /// confirms that it is rejected. + /// + /// + /// The is only designed to be able to set methods that are void and accept a single + /// parameter. + /// + [Fact] + public void IsValid_InvalidSetterMethod_ReturnsFalse() + { + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetMethod(nameof(MemberAccessorViewModel.InvalidSetMethod))!; + + Assert.NotNull(memberInfo); + Assert.False(MemberAccessor.IsValid(memberInfo)); + + } + + /*============================================================================================================================ + | TEST: IS VALID: CONSTRUCTOR: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates a that is not a or a and + /// confirms that it is rejected. + /// + [Fact] + public void IsValid_Constructor_ReturnsFalse() { + + var type = typeof(MemberAccessorViewModel); + var memberInfo = type.GetConstructor(Array.Empty())!; + + Assert.NotNull(memberInfo); + Assert.False(MemberAccessor.IsValid(memberInfo)); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/OnTopic.Tests.csproj b/OnTopic.Tests/OnTopic.Tests.csproj index f9ad9ded..5a5ec64d 100644 --- a/OnTopic.Tests/OnTopic.Tests.csproj +++ b/OnTopic.Tests/OnTopic.Tests.csproj @@ -4,7 +4,7 @@ net8.0 Exe false - CS1591 + CS1591;CA1515;CA1024 diff --git a/OnTopic.Tests/ReverseTopicMappingServiceTest.cs b/OnTopic.Tests/ReverseTopicMappingServiceTest.cs index c3ceeaa2..629b7e89 100644 --- a/OnTopic.Tests/ReverseTopicMappingServiceTest.cs +++ b/OnTopic.Tests/ReverseTopicMappingServiceTest.cs @@ -17,660 +17,659 @@ using OnTopic.Tests.Fixtures; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: REVERSE TOPIC MAPPING SERVICE TESTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the using local DTOs. +/// +[ExcludeFromCodeCoverage] +[Xunit.Collection("Shared Repository")] +public class ReverseTopicMappingServiceTest { /*============================================================================================================================ - | CLASS: REVERSE TOPIC MAPPING SERVICE TESTS + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly IReverseTopicMappingService _mappingService; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the using local DTOs. + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - [Xunit.Collection("Shared Repository")] - public class ReverseTopicMappingServiceTest { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. + /// + public ReverseTopicMappingServiceTest(TopicInfrastructureFixture fixture) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly IReverseTopicMappingService _mappingService; + Contract.Requires(fixture, nameof(fixture)); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. - /// - public ReverseTopicMappingServiceTest(TopicInfrastructureFixture fixture) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(fixture, nameof(fixture)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = fixture.CachedTopicRepository; - _mappingService = new ReverseTopicMappingService(_topicRepository); + _topicRepository = fixture.CachedTopicRepository; + _mappingService = new ReverseTopicMappingService(_topicRepository); - } + } - /*========================================================================================================================== - | TEST: MAP: GENERIC: RETURNS NEW TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting basic scalar values by specifying an explicit - /// type. - /// - [Fact] - public async Task Map_Generic_ReturnsNewTopic() { - - var bindingModel = new TextAttributeTopicBindingModel("Test") { - ContentType = "TextAttributeDescriptor", - Title = "Test Attribute", - DefaultValue = "Hello", - IsRequired = true - }; - - var target = await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); - - Assert.Equal("Test", target?.Key); - Assert.Equal("TextAttributeDescriptor", target?.ContentType); - Assert.Equal("Test Attribute", target?.Title); - Assert.Equal("Hello", target?.DefaultValue); - Assert.Equal(true, target?.IsRequired); + /*============================================================================================================================ + | TEST: MAP: GENERIC: RETURNS NEW TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting basic scalar values by specifying an explicit + /// type. + /// + [Fact] + public async Task Map_Generic_ReturnsNewTopic() { - } + var bindingModel = new TextAttributeTopicBindingModel("Test") { + ContentType = "TextAttributeDescriptor", + Title = "Test Attribute", + DefaultValue = "Hello", + IsRequired = true + }; - /*========================================================================================================================== - | TEST: MAP: DYNAMIC: RETURNS NEW TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting basic scalar values by allowing it to - /// dynamically determine the instance type. - /// - [Fact] - public async Task Map_Dynamic_ReturnsNewTopic() { - - var bindingModel = new TextAttributeTopicBindingModel("Test") { - ContentType = "TextAttributeDescriptor", - Title = "Test Attribute", - DefaultValue = "Hello", - IsRequired = true - }; - - var target = (TextAttributeDescriptor?)await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); - - Assert.NotNull(target); - Assert.Equal("Test", target?.Key); - Assert.Equal("TextAttributeDescriptor", target?.ContentType); - Assert.Equal("Test Attribute", target?.Title); - Assert.Equal("Hello", target?.DefaultValue); - Assert.Equal(true, target?.IsRequired); + var target = await _mappingService.MapAsync(bindingModel); - } + Assert.Equal("Test", target?.Key); + Assert.Equal("TextAttributeDescriptor", target?.ContentType); + Assert.Equal("Test Attribute", target?.Title); + Assert.Equal("Hello", target?.DefaultValue); + Assert.Equal(true, target?.IsRequired); - /*========================================================================================================================== - | TEST: MAP: EXISTING: RETURNS UPDATED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting basic scalar values on an existing object, - /// ensuring that all mapped values are overwritten, and unmapped valued are not. - /// - [Fact] - public async Task Map_Existing_ReturnsUpdatedTopic() { + } - var bindingModel = new TextAttributeTopicBindingModel("Test") { - ContentType = "TextAttributeDescriptor", - Title = null, - DefaultValue = "World", - IsRequired = false - }; + /*============================================================================================================================ + | TEST: MAP: DYNAMIC: RETURNS NEW TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting basic scalar values by allowing it to + /// dynamically determine the instance type. + /// + [Fact] + public async Task Map_Dynamic_ReturnsNewTopic() { - var target = new TextAttributeDescriptor("Test", "TextAttributeDescriptor"); + var bindingModel = new TextAttributeTopicBindingModel("Test") { + ContentType = "TextAttributeDescriptor", + Title = "Test Attribute", + DefaultValue = "Hello", + IsRequired = true + }; - Contract.Assume(target); + var target = (TextAttributeDescriptor?)await _mappingService.MapAsync(bindingModel); - target.Title = "Original Attribute"; - target.DefaultValue = "Hello"; - target.IsRequired = true; - target.IsExtendedAttribute= false; + Assert.NotNull(target); + Assert.Equal("Test", target?.Key); + Assert.Equal("TextAttributeDescriptor", target?.ContentType); + Assert.Equal("Test Attribute", target?.Title); + Assert.Equal("Hello", target?.DefaultValue); + Assert.Equal(true, target?.IsRequired); - target.Attributes.SetValue("Description", "Original Description"); + } - target = (TextAttributeDescriptor?)await _mappingService.MapAsync(bindingModel, target).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: EXISTING: RETURNS UPDATED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting basic scalar values on an existing object, + /// ensuring that all mapped values are overwritten, and unmapped valued are not. + /// + [Fact] + public async Task Map_Existing_ReturnsUpdatedTopic() { - Assert.Equal("Test", target?.Key); - Assert.Equal("TextAttributeDescriptor", target?.ContentType); - Assert.Equal("Test", target?.Title); //Should inherit from "Key" since it will be null - Assert.Equal("World", target?.DefaultValue); - Assert.Equal(false, target?.IsRequired); - Assert.Equal(false, target?.IsExtendedAttribute); - Assert.Equal("Original Description", target?.Attributes.GetValue("Description")); + var bindingModel = new TextAttributeTopicBindingModel("Test") { + ContentType = "TextAttributeDescriptor", + Title = null, + DefaultValue = "World", + IsRequired = false + }; - } + var target = new TextAttributeDescriptor("Test", "TextAttributeDescriptor"); - /*========================================================================================================================== - | TEST: MAP: RECORD: RETURNS NEW TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests mapping a binding model that's based on a C# 9.0 - /// record type. - /// - [Fact] - public async Task Map_Record_ReturnsNewTopic() { + Contract.Assume(target); - var bindingModel = new RecordTopicBindingModel() { - Key = "Test", - ContentType = "TextAttributeDescriptor" - }; + target.Title = "Original Attribute"; + target.DefaultValue = "Hello"; + target.IsRequired = true; + target.IsExtendedAttribute= false; - var target = await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); + target.Attributes.SetValue("Description", "Original Description"); - Assert.NotNull(target); - Assert.Equal("Test", target?.Key); - Assert.Equal("TextAttributeDescriptor", target?.ContentType); + target = (TextAttributeDescriptor?)await _mappingService.MapAsync(bindingModel, target); - } + Assert.Equal("Test", target?.Key); + Assert.Equal("TextAttributeDescriptor", target?.ContentType); + Assert.Equal("Test", target?.Title); //Should inherit from "Key" since it will be null + Assert.Equal("World", target?.DefaultValue); + Assert.Equal(false, target?.IsRequired); + Assert.Equal(false, target?.IsExtendedAttribute); + Assert.Equal("Original Description", target?.Attributes.GetValue("Description")); - /*========================================================================================================================== - | TEST: MAP: COMPLEX OBJECT: RETURNS FLATTENED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting values from complex objects. - /// - [Fact] - public async Task Map_ComplexObject_ReturnsFlattenedTopic() { + } - var bindingModel = new MapToParentTopicBindingModel { - Key = "Test", - ContentType = "Contact" - }; + /*============================================================================================================================ + | TEST: MAP: RECORD: RETURNS NEW TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests mapping a binding model that's based on a C# 9.0 + /// record type. + /// + [Fact] + public async Task Map_Record_ReturnsNewTopic() { - bindingModel.PrimaryContact.Name = "Jeremy"; - bindingModel.AlternateContact.Email = "AlternateContact@Ignia.com"; - bindingModel.BillingContact.Email = "BillingContact@Ignia.com"; + var bindingModel = new RecordTopicBindingModel() { + Key = "Test", + ContentType = "TextAttributeDescriptor" + }; - var target = await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); + var target = await _mappingService.MapAsync(bindingModel); - Assert.NotNull(target); - Assert.Equal("Jeremy", target?.Attributes.GetValue("Name")); - Assert.Equal("AlternateContact@Ignia.com", target?.Attributes.GetValue("AlternateEmail")); - Assert.Equal("BillingContact@Ignia.com", target?.Attributes.GetValue("BillingContactEmail")); + Assert.NotNull(target); + Assert.Equal("Test", target?.Key); + Assert.Equal("TextAttributeDescriptor", target?.ContentType); - } + } - /*========================================================================================================================== - | TEST: MAP: ALTERNATE ATTRIBUTE KEY: RETURNS MAPPED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully derives values from the key - /// specified by . - /// - [Fact] - public async Task Map_AlternateAttributeKey_ReturnsMappedTopic() { + /*============================================================================================================================ + | TEST: MAP: COMPLEX OBJECT: RETURNS FLATTENED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting values from complex objects. + /// + [Fact] + public async Task Map_ComplexObject_ReturnsFlattenedTopic() { - var bindingModel = new PageTopicBindingModel("Test") { - ContentType = "Page", - Title = "Test Page", - BrowserTitle = "Browser Title" - }; + var bindingModel = new MapToParentTopicBindingModel { + Key = "Test", + ContentType = "Contact" + }; - var target = await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); + bindingModel.PrimaryContact.Name = "Jeremy"; + bindingModel.AlternateContact.Email = "AlternateContact@Ignia.com"; + bindingModel.BillingContact.Email = "BillingContact@Ignia.com"; - Assert.Equal("Browser Title", target?.Attributes.GetValue("MetaTitle")); + var target = await _mappingService.MapAsync(bindingModel); - } + Assert.NotNull(target); + Assert.Equal("Jeremy", target?.Attributes.GetValue("Name")); + Assert.Equal("AlternateContact@Ignia.com", target?.Attributes.GetValue("AlternateEmail")); + Assert.Equal("BillingContact@Ignia.com", target?.Attributes.GetValue("BillingContactEmail")); - /*========================================================================================================================== - | TEST: MAP: RELATIONSHIPS: RETURNS MAPPED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls the relationships. - /// - [Fact] - public async Task Map_Relationships_ReturnsMappedTopic() { - - var bindingModel = new ContentTypeDescriptorTopicBindingModel("Test"); - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor"); - - topic.Relationships.SetValue("ContentTypes", contentTypes[4]); - - for (var i = 0; i < 3; i++) { - bindingModel.ContentTypes.Add( - new() { - UniqueKey = contentTypes[i].GetUniqueKey() - } - ); - } + } - var target = (ContentTypeDescriptor?)await _mappingService.MapAsync(bindingModel, topic).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: ALTERNATE ATTRIBUTE KEY: RETURNS MAPPED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully derives values from the key + /// specified by . + /// + [Fact] + public async Task Map_AlternateAttributeKey_ReturnsMappedTopic() { - Assert.Equal(3, target?.PermittedContentTypes.Count); - Assert.True(target?.PermittedContentTypes.Contains(contentTypes[0])); - Assert.True(target?.PermittedContentTypes.Contains(contentTypes[1])); - Assert.True(target?.PermittedContentTypes.Contains(contentTypes[2])); - Assert.False(target?.PermittedContentTypes.Contains(contentTypes[3])); + var bindingModel = new PageTopicBindingModel("Test") { + ContentType = "Page", + Title = "Test Page", + BrowserTitle = "Browser Title" + }; - //Revert state - _topicRepository.Delete(topic); + var target = await _mappingService.MapAsync(bindingModel); - } + Assert.Equal("Browser Title", target?.Attributes.GetValue("MetaTitle")); - /*========================================================================================================================== - | TEST: MAP: RELATIONSHIPS: THROW EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it correctly throws an exception if the - /// cannot be located in the repository. - /// - [Fact] - public async Task Map_Relationships_ThrowException() { + } - var bindingModel = new ContentTypeDescriptorTopicBindingModel("Test"); - var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor"); + /*============================================================================================================================ + | TEST: MAP: RELATIONSHIPS: RETURNS MAPPED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls the relationships. + /// + [Fact] + public async Task Map_Relationships_ReturnsMappedTopic() { + var bindingModel = new ContentTypeDescriptorTopicBindingModel("Test"); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor"); + + topic.Relationships.SetValue("ContentTypes", contentTypes[4]); + + for (var i = 0; i < 3; i++) { bindingModel.ContentTypes.Add( new() { - UniqueKey = "Root:Configuration:InvalidKey" + UniqueKey = contentTypes[i].GetUniqueKey() } ); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel, topic).ConfigureAwait(false) - ).ConfigureAwait(false); + var target = (ContentTypeDescriptor?)await _mappingService.MapAsync(bindingModel, topic); - } + Assert.Equal(3, target?.PermittedContentTypes.Count); + Assert.True(target?.PermittedContentTypes.Contains(contentTypes[0])); + Assert.True(target?.PermittedContentTypes.Contains(contentTypes[1])); + Assert.True(target?.PermittedContentTypes.Contains(contentTypes[2])); + Assert.False(target?.PermittedContentTypes.Contains(contentTypes[3])); + //Revert state + _topicRepository.Delete(topic); - /*========================================================================================================================== - | TEST: MAP: NESTED TOPICS: RETURNS MAPPED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls the nested topics. - /// - [Fact] - public async Task Map_NestedTopics_ReturnsMappedTopic() { + } - var bindingModel = new ContentTypeDescriptorTopicBindingModel("Test"); + /*============================================================================================================================ + | TEST: MAP: RELATIONSHIPS: THROW EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it correctly throws an exception if the + /// cannot be located in the repository. + /// + [Fact] + public async Task Map_Relationships_ThrowException() { - bindingModel.Attributes.Add(new TextAttributeTopicBindingModel("Attribute1")); - bindingModel.Attributes.Add(new TextAttributeTopicBindingModel("Attribute2")); - bindingModel.Attributes.Add(new TextAttributeTopicBindingModel("Attribute3") { DefaultValue = "New Value" }); + var bindingModel = new ContentTypeDescriptorTopicBindingModel("Test"); + var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor"); - var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor"); - var attributes = new Topic("Attributes", "List", topic); + bindingModel.ContentTypes.Add( + new() { + UniqueKey = "Root:Configuration:InvalidKey" + } + ); - var attribute3 = new TextAttributeDescriptor("Attribute3", "TextAttributeDescriptor", attributes); - _ = new TextAttributeDescriptor("Attribute4", "TextAttributeDescriptor", attributes); + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel, topic).ConfigureAwait(false) + ); - attribute3.DefaultValue = "Original Value"; + } - var target = (ContentTypeDescriptor?)await _mappingService.MapAsync(bindingModel, topic).ConfigureAwait(false); - Assert.Equal(3, target?.AttributeDescriptors.Count); - Assert.NotNull(target?.AttributeDescriptors.GetValue("Attribute1")); - Assert.NotNull(target?.AttributeDescriptors.GetValue("Attribute2")); - Assert.NotNull(target?.AttributeDescriptors.GetValue("Attribute3")); - Assert.Equal("New Value", target?.AttributeDescriptors.GetValue("Attribute3")?.DefaultValue); - Assert.Null(target?.AttributeDescriptors.GetValue("Attribute4")); + /*============================================================================================================================ + | TEST: MAP: NESTED TOPICS: RETURNS MAPPED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls the nested topics. + /// + [Fact] + public async Task Map_NestedTopics_ReturnsMappedTopic() { - } + var bindingModel = new ContentTypeDescriptorTopicBindingModel("Test"); - /*========================================================================================================================== - | TEST: MAP: TOPIC REFERENCES: RETURNS MAPPED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully maps referenced topics. - /// - [Fact] - public async Task Map_TopicReferences_ReturnsMappedTopic() { + bindingModel.Attributes.Add(new TextAttributeTopicBindingModel("Attribute1")); + bindingModel.Attributes.Add(new TextAttributeTopicBindingModel("Attribute2")); + bindingModel.Attributes.Add(new TextAttributeTopicBindingModel("Attribute3") { DefaultValue = "New Value" }); - var topic = _topicRepository.Load("Root:Configuration:ContentTypes:Attributes:Title"); + var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor"); + var attributes = new Topic("Attributes", "List", topic); - Contract.Assume(topic); + var attribute3 = new TextAttributeDescriptor("Attribute3", "TextAttributeDescriptor", attributes); + _ = new TextAttributeDescriptor("Attribute4", "TextAttributeDescriptor", attributes); - var bindingModel = new ReferenceTopicBindingModel("Test") { - BaseTopic = new() { - UniqueKey = topic.GetUniqueKey() - } - }; + attribute3.DefaultValue = "Original Value"; - var target = (TextAttributeDescriptor?)await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); + var target = (ContentTypeDescriptor?)await _mappingService.MapAsync(bindingModel, topic); - Assert.NotNull(target?.BaseTopic); - Assert.Equal("Title", target?.BaseTopic?.Key); - Assert.Equal("Text", target?.EditorType); + Assert.Equal(3, target?.AttributeDescriptors.Count); + Assert.NotNull(target?.AttributeDescriptors.GetValue("Attribute1")); + Assert.NotNull(target?.AttributeDescriptors.GetValue("Attribute2")); + Assert.NotNull(target?.AttributeDescriptors.GetValue("Attribute3")); + Assert.Equal("New Value", target?.AttributeDescriptors.GetValue("Attribute3")?.DefaultValue); + Assert.Null(target?.AttributeDescriptors.GetValue("Attribute4")); - } + } - /*========================================================================================================================== - | TEST: MAP: NULL TOPIC REFERENCE: DELETE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it correctly ovewrite any topic references if - /// the has a set to null. - /// - [Fact] - public async Task Map_NullTopicReference_Delete() { + /*============================================================================================================================ + | TEST: MAP: TOPIC REFERENCES: RETURNS MAPPED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully maps referenced topics. + /// + [Fact] + public async Task Map_TopicReferences_ReturnsMappedTopic() { - var topic = _topicRepository.Load("Root:Configuration:ContentTypes:Attributes:Title"); - var baseTopic = _topicRepository.Load("Root:Configuration:ContentTypes:Attributes:Key"); + var topic = _topicRepository.Load("Root:Configuration:ContentTypes:Attributes:Title"); - Contract.Assume(topic); + Contract.Assume(topic); - topic.BaseTopic = baseTopic; + var bindingModel = new ReferenceTopicBindingModel("Test") { + BaseTopic = new() { + UniqueKey = topic.GetUniqueKey() + } + }; - var bindingModel = new ReferenceTopicBindingModel(topic.Key) { - ContentType = topic.ContentType, - BaseTopic = new() { - UniqueKey = "" - } - }; + var target = (TextAttributeDescriptor?)await _mappingService.MapAsync(bindingModel); - await _mappingService.MapAsync(bindingModel, topic).ConfigureAwait(false); + Assert.NotNull(target?.BaseTopic); + Assert.Equal("Title", target?.BaseTopic?.Key); + Assert.Equal("Text", target?.EditorType); - Assert.Null(topic.BaseTopic); + } - } + /*============================================================================================================================ + | TEST: MAP: NULL TOPIC REFERENCE: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it correctly ovewrite any topic references if + /// the has a set to null. + /// + [Fact] + public async Task Map_NullTopicReference_Delete() { - /*========================================================================================================================== - | TEST: MAP: NULL TOPIC REFERENCE: THROW EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it correctly throws an exception if the is set to null. - /// - [Fact] - public async Task Map_NullTopicReference_ThrowException() { + var topic = _topicRepository.Load("Root:Configuration:ContentTypes:Attributes:Title"); + var baseTopic = _topicRepository.Load("Root:Configuration:ContentTypes:Attributes:Key"); - var bindingModel = new ReferenceTopicBindingModel("AttributeDescriptor") { - ContentType = "AttributeDescriptor" - }; + Contract.Assume(topic); - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + topic.BaseTopic = baseTopic; - } + var bindingModel = new ReferenceTopicBindingModel(topic.Key) { + ContentType = topic.ContentType, + BaseTopic = new() { + UniqueKey = "" + } + }; - /*========================================================================================================================== - | TEST: MAP: NULL TOPIC REFERENCE KEY: THROW EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it correctly throws an exception if the is set to null. - /// - [Fact] - public async Task Map_NullTopicReferenceKey_ThrowException() { - - var bindingModel = new ReferenceTopicBindingModel("AttributeDescriptor") { - ContentType = "AttributeDescriptor", - BaseTopic = new() - }; - - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + await _mappingService.MapAsync(bindingModel, topic); - } + Assert.Null(topic.BaseTopic); - /*========================================================================================================================== - | TEST: MAP: TOPIC REFERENCES: THOWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it correctly throws an exception if the - /// cannot be resolved in the supplied . - /// - [Fact] - public async Task Map_TopicReferences_ThrowException() { - - var bindingModel = new ReferenceTopicBindingModel("Test") { - BaseTopic = new() { - UniqueKey = "Root:InvalidKey" - } - }; + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: NULL TOPIC REFERENCE: THROW EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it correctly throws an exception if the is set to null. + /// + [Fact] + public async Task Map_NullTopicReference_ThrowException() { - } + var bindingModel = new ReferenceTopicBindingModel("AttributeDescriptor") { + ContentType = "AttributeDescriptor" + }; - /*========================================================================================================================== - | TEST: MAP: VALID REQUIRED PROPERTY: IS MAPPED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a required property. Ensures that an error is thrown if it is not set. - /// - [Fact] - public async Task Map_ValidRequiredProperty_IsMapped() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new PageTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: NULL TOPIC REFERENCE KEY: THROW EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it correctly throws an exception if the is set to null. + /// + [Fact] + public async Task Map_NullTopicReferenceKey_ThrowException() { - } + var bindingModel = new ReferenceTopicBindingModel("AttributeDescriptor") { + ContentType = "AttributeDescriptor", + BaseTopic = new() + }; - /*========================================================================================================================== - | TEST: MAP: NULL PROPERTY: MAPS DEFAULT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has default properties. Ensures that each is set appropriately. - /// - [Fact] - public async Task Map_NullProperty_MapsDefaultValue() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new PageTopicBindingModel("Test") { - Title = "Required Title" - }; + } - var target = await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: TOPIC REFERENCES: THOWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it correctly throws an exception if the + /// cannot be resolved in the supplied . + /// + [Fact] + public async Task Map_TopicReferences_ThrowException() { - Assert.Equal("Default page description", target?.Attributes.GetValue("MetaDescription")); + var bindingModel = new ReferenceTopicBindingModel("Test") { + BaseTopic = new() { + UniqueKey = "Root:InvalidKey" + } + }; - } + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - /*========================================================================================================================== - | TEST: MAP: EXCEEDS MINIMUM VALUE: THROWS VALIDATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has minimum value properties. Ensures that an error is thrown if the minimum is not met. - /// - [Fact] - public async Task Map_ExceedsMinimumValue_ThrowsValidationException() { + } - var bindingModel = new MinimumLengthPropertyTopicBindingModel("Test") { - Title = "Hello World" - }; + /*============================================================================================================================ + | TEST: MAP: VALID REQUIRED PROPERTY: IS MAPPED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a required property. Ensures that an error is thrown if it is not set. + /// + [Fact] + public async Task Map_ValidRequiredProperty_IsMapped() { - await Assert.ThrowsAsync (async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + var bindingModel = new PageTopicBindingModel("Test"); - } + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - /*========================================================================================================================== - | TEST: MAP: INVALID CHILDREN PROPERTY: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has children property. This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidChildrenProperty_ThrowsInvalidOperationException() { + } - var bindingModel = new InvalidChildrenTopicBindingModel("Test"); + /*============================================================================================================================ + | TEST: MAP: NULL PROPERTY: MAPS DEFAULT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has default properties. Ensures that each is set appropriately. + /// + [Fact] + public async Task Map_NullProperty_MapsDefaultValue() { - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + var bindingModel = new PageTopicBindingModel("Test") { + Title = "Required Title" + }; - } + var target = await _mappingService.MapAsync(bindingModel); - /*========================================================================================================================== - | TEST: MAP: INVALID PARENT PROPERTY: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has parent property. This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidParentProperty_ThrowsInvalidOperationException() { + Assert.Equal("Default page description", target?.Attributes.GetValue("MetaDescription")); - var bindingModel = new InvalidParentTopicBindingModel("Test") { - Parent = new("Test", "Page") - }; + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: EXCEEDS MINIMUM VALUE: THROWS VALIDATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has minimum value properties. Ensures that an error is thrown if the minimum is not met. + /// + [Fact] + public async Task Map_ExceedsMinimumValue_ThrowsValidationException() { - } + var bindingModel = new MinimumLengthPropertyTopicBindingModel("Test") { + Title = "Hello World" + }; - /*========================================================================================================================== - | TEST: MAP: INVALID ATTRIBUTE: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a property that doesn't map to any attributes. This is invalid, and expected to throw an - /// . - /// - [Fact] - public async Task Map_InvalidAttribute_ThrowsInvalidOperationException() { + await Assert.ThrowsAsync (async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new InvalidAttributeTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID CHILDREN PROPERTY: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has children property. This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidChildrenProperty_ThrowsInvalidOperationException() { - } + var bindingModel = new InvalidChildrenTopicBindingModel("Test"); - /*========================================================================================================================== - | TEST: MAP: INVALID RELATIONSHIP BASE TYPE: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a relationship whose type doesn't implement . - /// This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidRelationshipBaseType_ThrowsInvalidOperationException() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new InvalidRelationshipBaseTypeTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID PARENT PROPERTY: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has parent property. This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidParentProperty_ThrowsInvalidOperationException() { - } + var bindingModel = new InvalidParentTopicBindingModel("Test") { + Parent = new("Test", "Page") + }; - /*========================================================================================================================== - | TEST: MAP: INVALID RELATIONSHIP TYPE: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a relationship with an invalid —i.e., it refers to , even though the property is associated with a . This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidRelationshipType_ThrowsInvalidOperationException() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new InvalidRelationshipTypeTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID ATTRIBUTE: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a property that doesn't map to any attributes. This is invalid, and expected to throw an + /// . + /// + [Fact] + public async Task Map_InvalidAttribute_ThrowsInvalidOperationException() { - } + var bindingModel = new InvalidAttributeTopicBindingModel("Test"); - /*========================================================================================================================== - | TEST: MAP: INVALID RELATIONSHIP LIST TYPE: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a relationship that implements an invalid collection type—i.e., it implements a , even though relationships are expected to return a type implementing . This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidRelationshipListType_ThrowsInvalidOperationException() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new InvalidRelationshipListTypeTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID RELATIONSHIP BASE TYPE: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a relationship whose type doesn't implement . + /// This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidRelationshipBaseType_ThrowsInvalidOperationException() { - } + var bindingModel = new InvalidRelationshipBaseTypeTopicBindingModel("Test"); - /*========================================================================================================================== - | TEST: MAP: INVALID NESTED TOPIC LIST TYPE: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a nested topic that implements an invalid collection type—i.e., it implements a , even though nestd topics are expected to return a type implementing . This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidNestedTopicListType_ThrowsInvalidOperationException() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new InvalidNestedTopicListTypeTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID RELATIONSHIP TYPE: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a relationship with an invalid —i.e., it refers to , even though the property is associated with a . This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidRelationshipType_ThrowsInvalidOperationException() { - } + var bindingModel = new InvalidRelationshipTypeTopicBindingModel("Test"); - /*========================================================================================================================== - | TEST: MAP: INVALID TOPIC REFERENCE TYPE: THROWS INVALID OPERATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a reference that implements an invalid type—i.e., it implements a , even though references are expected to return a type implementing . This is invalid, and expected to throw an . - /// - [Fact] - public async Task Map_InvalidTopicReferenceType_ThrowsInvalidOperationException() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new InvalidReferenceTypeTopicBindingModel("Test"); + } - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) - ).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID RELATIONSHIP LIST TYPE: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a relationship that implements an invalid collection type—i.e., it implements a , even though relationships are expected to return a type implementing . This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidRelationshipListType_ThrowsInvalidOperationException() { - } + var bindingModel = new InvalidRelationshipListTypeTopicBindingModel("Test"); - /*========================================================================================================================== - | TEST: MAP: DISABLED PROPERTY: IS NOT MAPPED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a property that doesn't map to any attributes. This is invalid. However, the property - /// is also decorated with the , which should prevent the from validating or mapping the property. - /// - [Fact] - public async Task Map_DisabledProperty_IsNotMapped() { + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); - var bindingModel = new DisabledAttributeTopicBindingModel("Test") { - UnmappedAttribute = "Hello World" - }; + } - var target = await _mappingService.MapAsync(bindingModel).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INVALID NESTED TOPIC LIST TYPE: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a nested topic that implements an invalid collection type—i.e., it implements a , even though nestd topics are expected to return a type implementing . This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidNestedTopicListType_ThrowsInvalidOperationException() { - Assert.Null(target?.Attributes.GetValue("UnmappedAttribute", null)); + var bindingModel = new InvalidNestedTopicListTypeTopicBindingModel("Test"); - } + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); + + } + + /*============================================================================================================================ + | TEST: MAP: INVALID TOPIC REFERENCE TYPE: THROWS INVALID OPERATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a reference that implements an invalid type—i.e., it implements a , even though references are expected to return a type implementing . This is invalid, and expected to throw an . + /// + [Fact] + public async Task Map_InvalidTopicReferenceType_ThrowsInvalidOperationException() { + + var bindingModel = new InvalidReferenceTypeTopicBindingModel("Test"); + + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(bindingModel).ConfigureAwait(false) + ); + + } + + /*============================================================================================================================ + | TEST: MAP: DISABLED PROPERTY: IS NOT MAPPED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a property that doesn't map to any attributes. This is invalid. However, the property + /// is also decorated with the , which should prevent the from validating or mapping the property. + /// + [Fact] + public async Task Map_DisabledProperty_IsNotMapped() { + + var bindingModel = new DisabledAttributeTopicBindingModel("Test") { + UnmappedAttribute = "Hello World" + }; + + var target = await _mappingService.MapAsync(bindingModel); + + Assert.Null(target?.Attributes.GetValue("UnmappedAttribute", null)); + + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Schemas/AttributesDataTable.cs b/OnTopic.Tests/Schemas/AttributesDataTable.cs index 5edf1da7..b4e090d3 100644 --- a/OnTopic.Tests/Schemas/AttributesDataTable.cs +++ b/OnTopic.Tests/Schemas/AttributesDataTable.cs @@ -6,95 +6,94 @@ using System.Data; using OnTopic.Data.Sql; -namespace OnTopic.Tests.Schemas { +namespace OnTopic.Tests.Schemas; + +/*============================================================================================================================== +| CLASS: ATTRIBUTES DATA TABLE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a which maps to the expected schema of the Attributes table. +/// +/// +/// This allows testing of the via its methods. +/// +[ExcludeFromCodeCoverage] +public class AttributesDataTable: DataTable { /*============================================================================================================================ - | CLASS: ATTRIBUTES DATA TABLE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a which maps to the expected schema of the Attributes table. + /// Instantiates a new instance of the . /// - /// - /// This allows testing of the via its methods. - /// - [ExcludeFromCodeCoverage] - public class AttributesDataTable: DataTable { + /// A new instance of the . + public AttributesDataTable() : base("Attributes") { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add TopicId column \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public AttributesDataTable() : base("Attributes") { + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "TopicId", + Unique = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "TopicId", - Unique = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add AttributeKey column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(string), + ColumnName = "AttributeKey" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add AttributeKey column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(string), - ColumnName = "AttributeKey" - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add AttributeValue column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(string), + ColumnName = "AttributeValue", + AllowDBNull = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add AttributeValue column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(string), - ColumnName = "AttributeValue", - AllowDBNull = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Version column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(DateTime), + ColumnName = "Version" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add Version column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(DateTime), - ColumnName = "Version" - }); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to the . + /// + public void AddRow(int topicId, string attributeKey, string? attributeValue, DateTime? version = null) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Verify parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to the . - /// - public void AddRow(int topicId, string attributeKey, string? attributeValue, DateTime? version = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Verify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicId, nameof(topicId)); - Contract.Requires(attributeKey, nameof(attributeKey)); + Contract.Requires(topicId, nameof(topicId)); + Contract.Requires(attributeKey, nameof(attributeKey)); - /*------------------------------------------------------------------------------------------------------------------------ - | Create new row - \-----------------------------------------------------------------------------------------------------------------------*/ - var row = NewRow(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new row + \-------------------------------------------------------------------------------------------------------------------------*/ + var row = NewRow(); - row["TopicId"] = topicId; - row["AttributeKey"] = attributeKey; - row["AttributeValue"] = attributeValue is null? DBNull.Value : attributeValue; - row["Version"] = version?? DateTime.UtcNow; + row["TopicId"] = topicId; + row["AttributeKey"] = attributeKey; + row["AttributeValue"] = attributeValue is null? DBNull.Value : attributeValue; + row["Version"] = version?? DateTime.UtcNow; - /*------------------------------------------------------------------------------------------------------------------------ - | Add row to table - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(row); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add row to table + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(row); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Schemas/ExtendedAttributesDataTable.cs b/OnTopic.Tests/Schemas/ExtendedAttributesDataTable.cs index 060d60c5..136e6f9d 100644 --- a/OnTopic.Tests/Schemas/ExtendedAttributesDataTable.cs +++ b/OnTopic.Tests/Schemas/ExtendedAttributesDataTable.cs @@ -7,85 +7,84 @@ using System.Xml; using OnTopic.Data.Sql; -namespace OnTopic.Tests.Schemas { +namespace OnTopic.Tests.Schemas; + +/*============================================================================================================================== +| CLASS: EXTENDED ATTRIBUTES DATA TABLE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a which maps to the expected schema of the ExtendedAttributes table. +/// +/// +/// This allows testing of the via its methods. +/// +[ExcludeFromCodeCoverage] +public class ExtendedAttributesDataTable: DataTable { /*============================================================================================================================ - | CLASS: EXTENDED ATTRIBUTES DATA TABLE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a which maps to the expected schema of the ExtendedAttributes table. + /// Instantiates a new instance of the . /// - /// - /// This allows testing of the via its methods. - /// - [ExcludeFromCodeCoverage] - public class ExtendedAttributesDataTable: DataTable { + /// A new instance of the . + public ExtendedAttributesDataTable() : base("ExtendedAttributes") { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add TopicId column \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public ExtendedAttributesDataTable() : base("ExtendedAttributes") { + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "TopicId", + Unique = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "TopicId", - Unique = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add AttributesXml column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(XmlDocument), + ColumnName = "AttributesXml" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add AttributesXml column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(XmlDocument), - ColumnName = "AttributesXml" - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Version column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(DateTime), + ColumnName = "Version" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add Version column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(DateTime), - ColumnName = "Version" - }); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to the . + /// + public void AddRow(int topicId, XmlDocument xml, DateTime? version = null) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Verify parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to the . - /// - public void AddRow(int topicId, XmlDocument xml, DateTime? version = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Verify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicId, nameof(topicId)); - Contract.Requires(xml, nameof(xml)); + Contract.Requires(topicId, nameof(topicId)); + Contract.Requires(xml, nameof(xml)); - /*------------------------------------------------------------------------------------------------------------------------ - | Create new row - \-----------------------------------------------------------------------------------------------------------------------*/ - var row = NewRow(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new row + \-------------------------------------------------------------------------------------------------------------------------*/ + var row = NewRow(); - row["TopicId"] = topicId; - row["AttributesXml"] = xml; - row["Version"] = version?? DateTime.UtcNow; + row["TopicId"] = topicId; + row["AttributesXml"] = xml; + row["Version"] = version?? DateTime.UtcNow; - /*------------------------------------------------------------------------------------------------------------------------ - | Add row to table - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(row); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add row to table + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(row); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Schemas/RelationshipsDataTable.cs b/OnTopic.Tests/Schemas/RelationshipsDataTable.cs index 665c728f..e312e548 100644 --- a/OnTopic.Tests/Schemas/RelationshipsDataTable.cs +++ b/OnTopic.Tests/Schemas/RelationshipsDataTable.cs @@ -6,104 +6,103 @@ using System.Data; using OnTopic.Data.Sql; -namespace OnTopic.Tests.Schemas { +namespace OnTopic.Tests.Schemas; + +/*============================================================================================================================== +| CLASS: RELATIONSHIPS DATA TABLE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a which maps to the expected schema of the Relationships table. +/// +/// +/// This allows testing of the via its methods. +/// +[ExcludeFromCodeCoverage] +public class RelationshipsDataTable: DataTable { /*============================================================================================================================ - | CLASS: RELATIONSHIPS DATA TABLE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a which maps to the expected schema of the Relationships table. + /// Instantiates a new instance of the . /// - /// - /// This allows testing of the via its methods. - /// - [ExcludeFromCodeCoverage] - public class RelationshipsDataTable: DataTable { - - /*========================================================================================================================== - | CONSTRUCTOR + /// A new instance of the . + public RelationshipsDataTable() : base("Relationships") { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Source_TopicId column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "Source_TopicId", + Unique = true + }); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add RelationshipKey column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(string), + ColumnName = "RelationshipKey" + }); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Target_TopicId column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "Target_TopicId" + }); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add IsDeleted column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(bool), + ColumnName = "IsDeleted" + }); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add ParentId column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(DateTime), + ColumnName = "Version" + }); + + } + + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to the . + /// + public void AddRow(int sourceTopicId, string relationshipKey, int targetTopicId, bool isDeleted, DateTime? version = null) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Verify parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public RelationshipsDataTable() : base("Relationships") { - - /*------------------------------------------------------------------------------------------------------------------------ - | Add Source_TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "Source_TopicId", - Unique = true - }); - - /*------------------------------------------------------------------------------------------------------------------------ - | Add RelationshipKey column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(string), - ColumnName = "RelationshipKey" - }); - - /*------------------------------------------------------------------------------------------------------------------------ - | Add Target_TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "Target_TopicId" - }); - - /*------------------------------------------------------------------------------------------------------------------------ - | Add IsDeleted column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(bool), - ColumnName = "IsDeleted" - }); - - /*------------------------------------------------------------------------------------------------------------------------ - | Add ParentId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(DateTime), - ColumnName = "Version" - }); - - } - - /*========================================================================================================================== - | ADD ROW + Contract.Requires(sourceTopicId, nameof(sourceTopicId)); + Contract.Requires(relationshipKey, nameof(relationshipKey)); + Contract.Requires(targetTopicId, nameof(targetTopicId)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new row \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to the . - /// - public void AddRow(int sourceTopicId, string relationshipKey, int targetTopicId, bool isDeleted, DateTime? version = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Verify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(sourceTopicId, nameof(sourceTopicId)); - Contract.Requires(relationshipKey, nameof(relationshipKey)); - Contract.Requires(targetTopicId, nameof(targetTopicId)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Create new row - \-----------------------------------------------------------------------------------------------------------------------*/ - var row = NewRow(); - - row["Source_TopicId"] = sourceTopicId; - row["RelationshipKey"] = relationshipKey; - row["Target_TopicId"] = targetTopicId; - row["IsDeleted"] = isDeleted; - row["Version"] = version?? DateTime.UtcNow; - - /*------------------------------------------------------------------------------------------------------------------------ - | Add row to table - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(row); - - } - - } //Class -} //Namespace \ No newline at end of file + var row = NewRow(); + + row["Source_TopicId"] = sourceTopicId; + row["RelationshipKey"] = relationshipKey; + row["Target_TopicId"] = targetTopicId; + row["IsDeleted"] = isDeleted; + row["Version"] = version?? DateTime.UtcNow; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Add row to table + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(row); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Schemas/TopicReferencesDataTable.cs b/OnTopic.Tests/Schemas/TopicReferencesDataTable.cs index 8639a101..4758b5e9 100644 --- a/OnTopic.Tests/Schemas/TopicReferencesDataTable.cs +++ b/OnTopic.Tests/Schemas/TopicReferencesDataTable.cs @@ -6,95 +6,94 @@ using System.Data; using OnTopic.Data.Sql; -namespace OnTopic.Tests.Schemas { +namespace OnTopic.Tests.Schemas; + +/*============================================================================================================================== +| CLASS: TOPIC REFERENCES DATA TABLE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a which maps to the expected schema of the TopicReferences table. +/// +/// +/// This allows testing of the via its methods. +/// +[ExcludeFromCodeCoverage] +public class TopicReferencesDataTable: DataTable { /*============================================================================================================================ - | CLASS: TOPIC REFERENCES DATA TABLE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a which maps to the expected schema of the TopicReferences table. + /// Instantiates a new instance of the . /// - /// - /// This allows testing of the via its methods. - /// - [ExcludeFromCodeCoverage] - public class TopicReferencesDataTable: DataTable { + /// A new instance of the . + public TopicReferencesDataTable() : base("TopicReferences") { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Source_TopicId column \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public TopicReferencesDataTable() : base("TopicReferences") { + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "Source_TopicId", + Unique = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add Source_TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "Source_TopicId", - Unique = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add RelationshipKey column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(string), + ColumnName = "ReferenceKey" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add RelationshipKey column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(string), - ColumnName = "ReferenceKey" - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Target_TopicId column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "Target_TopicId", + AllowDBNull = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add Target_TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "Target_TopicId", - AllowDBNull = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add ParentId column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(DateTime), + ColumnName = "Version" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add ParentId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(DateTime), - ColumnName = "Version" - }); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to the . + /// + public void AddRow(int sourceTopicId, string referenceKey, int? targetTopicId, DateTime? version = null) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Verify parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to the . - /// - public void AddRow(int sourceTopicId, string referenceKey, int? targetTopicId, DateTime? version = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Verify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(sourceTopicId, nameof(sourceTopicId)); - Contract.Requires(referenceKey, nameof(referenceKey)); + Contract.Requires(sourceTopicId, nameof(sourceTopicId)); + Contract.Requires(referenceKey, nameof(referenceKey)); - /*------------------------------------------------------------------------------------------------------------------------ - | Create new row - \-----------------------------------------------------------------------------------------------------------------------*/ - var row = NewRow(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new row + \-------------------------------------------------------------------------------------------------------------------------*/ + var row = NewRow(); - row["Source_TopicId"] = sourceTopicId; - row["ReferenceKey"] = referenceKey; - row["Target_TopicId"] = targetTopicId.HasValue ? (object)targetTopicId : DBNull.Value; - row["Version"] = version?? DateTime.UtcNow; + row["Source_TopicId"] = sourceTopicId; + row["ReferenceKey"] = referenceKey; + row["Target_TopicId"] = targetTopicId.HasValue ? (object)targetTopicId : DBNull.Value; + row["Version"] = version?? DateTime.UtcNow; - /*------------------------------------------------------------------------------------------------------------------------ - | Add row to table - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(row); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add row to table + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(row); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Schemas/TopicsDataTable.cs b/OnTopic.Tests/Schemas/TopicsDataTable.cs index 0c5a99a6..85c0f443 100644 --- a/OnTopic.Tests/Schemas/TopicsDataTable.cs +++ b/OnTopic.Tests/Schemas/TopicsDataTable.cs @@ -6,96 +6,95 @@ using System.Data; using OnTopic.Data.Sql; -namespace OnTopic.Tests.Schemas { +namespace OnTopic.Tests.Schemas; + +/*============================================================================================================================== +| CLASS: TOPICS DATA TABLE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a which maps to the expected schema of the Topics table. +/// +/// +/// This allows testing of the via its methods. +/// +[ExcludeFromCodeCoverage] +public class TopicsDataTable: DataTable { /*============================================================================================================================ - | CLASS: TOPICS DATA TABLE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a which maps to the expected schema of the Topics table. + /// Instantiates a new instance of the . /// - /// - /// This allows testing of the via its methods. - /// - [ExcludeFromCodeCoverage] - public class TopicsDataTable: DataTable { + /// A new instance of the . + public TopicsDataTable() : base("Topics") { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add TopicId column \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public TopicsDataTable() : base("Topics") { + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "TopicId", + Unique = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "TopicId", - Unique = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add TopicKey column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(string), + ColumnName = "TopicKey" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add TopicKey column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(string), - ColumnName = "TopicKey" - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add ContentType column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(string), + ColumnName = "ContentType" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add ContentType column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(string), - ColumnName = "ContentType" - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add ParentId column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "ParentId", + AllowDBNull = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add ParentId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "ParentId", - AllowDBNull = true - }); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to the . + /// + public void AddRow(int topicId, string topicKey, string contentType, int? parentId = null) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Verify parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to the . - /// - public void AddRow(int topicId, string topicKey, string contentType, int? parentId = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Verify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicId, nameof(topicId)); - Contract.Requires(topicKey, nameof(topicKey)); - Contract.Requires(contentType, nameof(contentType)); + Contract.Requires(topicId, nameof(topicId)); + Contract.Requires(topicKey, nameof(topicKey)); + Contract.Requires(contentType, nameof(contentType)); - /*------------------------------------------------------------------------------------------------------------------------ - | Create new row - \-----------------------------------------------------------------------------------------------------------------------*/ - var row = NewRow(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new row + \-------------------------------------------------------------------------------------------------------------------------*/ + var row = NewRow(); - row["TopicId"] = topicId; - row["TopicKey"] = topicKey; - row["ContentType"] = contentType; - row["ParentId"] = parentId.HasValue? (object)parentId : DBNull.Value; + row["TopicId"] = topicId; + row["TopicKey"] = topicKey; + row["ContentType"] = contentType; + row["ParentId"] = parentId.HasValue? (object)parentId : DBNull.Value; - /*------------------------------------------------------------------------------------------------------------------------ - | Add row to table - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(row); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add row to table + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(row); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/Schemas/VersionHistoryDataTable.cs b/OnTopic.Tests/Schemas/VersionHistoryDataTable.cs index 9f7a712a..4973d3c4 100644 --- a/OnTopic.Tests/Schemas/VersionHistoryDataTable.cs +++ b/OnTopic.Tests/Schemas/VersionHistoryDataTable.cs @@ -6,77 +6,76 @@ using System.Data; using OnTopic.Data.Sql; -namespace OnTopic.Tests.Schemas { +namespace OnTopic.Tests.Schemas; + +/*============================================================================================================================== +| CLASS: VERSION HISTORY DATA TABLE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a which maps to the expected schema of the VersionHistory records returns from +/// the GetTopics stored procedure. +/// +/// +/// This allows testing of the via its methods. +/// +[ExcludeFromCodeCoverage] +public class VersionHistoryDataTable: DataTable { /*============================================================================================================================ - | CLASS: VERSION HISTORY DATA TABLE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a which maps to the expected schema of the VersionHistory records returns from - /// the GetTopics stored procedure. + /// Instantiates a new instance of the . /// - /// - /// This allows testing of the via its methods. - /// - [ExcludeFromCodeCoverage] - public class VersionHistoryDataTable: DataTable { + /// A new instance of the . + public VersionHistoryDataTable() : base("VersionHistory") { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add TopicId column \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public VersionHistoryDataTable() : base("VersionHistory") { + Columns.Add(new DataColumn() { + DataType = typeof(int), + ColumnName = "TopicId", + Unique = true + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add TopicId column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(int), - ColumnName = "TopicId", - Unique = true - }); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add Version column + \-------------------------------------------------------------------------------------------------------------------------*/ + Columns.Add(new DataColumn() { + DataType = typeof(DateTime), + ColumnName = "Version" + }); - /*------------------------------------------------------------------------------------------------------------------------ - | Add Version column - \-----------------------------------------------------------------------------------------------------------------------*/ - Columns.Add(new DataColumn() { - DataType = typeof(DateTime), - ColumnName = "Version" - }); + } - } + /*============================================================================================================================ + | ADD ROW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to the . + /// + public void AddRow(int topicId, DateTime version) { - /*========================================================================================================================== - | ADD ROW + /*-------------------------------------------------------------------------------------------------------------------------- + | Verify parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to the . - /// - public void AddRow(int topicId, DateTime version) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Verify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicId, nameof(topicId)); - Contract.Requires(version, nameof(version)); + Contract.Requires(topicId, nameof(topicId)); + Contract.Requires(version, nameof(version)); - /*------------------------------------------------------------------------------------------------------------------------ - | Create new row - \-----------------------------------------------------------------------------------------------------------------------*/ - var row = NewRow(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new row + \-------------------------------------------------------------------------------------------------------------------------*/ + var row = NewRow(); - row["TopicId"] = topicId; - row["Version"] = version; + row["TopicId"] = topicId; + row["Version"] = version; - /*------------------------------------------------------------------------------------------------------------------------ - | Add row to table - \-----------------------------------------------------------------------------------------------------------------------*/ - Rows.Add(row); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add row to table + \-------------------------------------------------------------------------------------------------------------------------*/ + Rows.Add(row); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/SqlTopicRepositoryTest.cs b/OnTopic.Tests/SqlTopicRepositoryTest.cs index b8c1b5d8..86cbb637 100644 --- a/OnTopic.Tests/SqlTopicRepositoryTest.cs +++ b/OnTopic.Tests/SqlTopicRepositoryTest.cs @@ -11,664 +11,663 @@ using OnTopic.Tests.Schemas; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: SQL TOPIC REPOSITORY TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SqlTopicRepositoryTest { /*============================================================================================================================ - | CLASS: SQL TOPIC REPOSITORY TEST + | TEST: LOAD TOPIC GRAPH: WITH TOPIC: RETURNS TOPIC \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Calls with a record and confirms that a topic with those values is returned. /// - [ExcludeFromCodeCoverage] - public class SqlTopicRepositoryTest { - - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH TOPIC: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record and confirms that a topic with those values is returned. - /// - [Fact] - public void LoadTopicGraph_WithTopic_ReturnsTopic() { + [Fact] + public void LoadTopicGraph_WithTopic_ReturnsTopic() { - using var topics = new TopicsDataTable(); + using var topics = new TopicsDataTable(); - topics.AddRow(1, "Root", "Container", null); + topics.AddRow(1, "Root", "Container", null); - using var tableReader = new DataTableReader(topics); + using var tableReader = new DataTableReader(topics); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); + Assert.NotNull(topic); + Assert.Equal(1, topic?.Id); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH NEW PARENT: UPDATES PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record that represents a different parent than the existing referenceTopic and confirms that - /// the topic's parent is updated. - /// - [Fact] - public void LoadTopicGraph_WithNewParent_UpdatesParent() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH NEW PARENT: UPDATES PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record that represents a different parent than the existing referenceTopic and confirms that + /// the topic's parent is updated. + /// + [Fact] + public void LoadTopicGraph_WithNewParent_UpdatesParent() { - using var topics = new TopicsDataTable(); + using var topics = new TopicsDataTable(); - var topic = new Topic("Root", "Container", null, 1); - var parent1 = new Topic("Parent1", "Container", topic, 2); - var parent2 = new Topic("Parent2", "Container", topic, 3); - var child = new Topic("Child", "Page", parent1, 4); + var topic = new Topic("Root", "Container", null, 1); + var parent1 = new Topic("Parent1", "Container", topic, 2); + var parent2 = new Topic("Parent2", "Container", topic, 3); + var child = new Topic("Child", "Page", parent1, 4); - topics.AddRow(4, "Child", "Page", parent2.Id); + topics.AddRow(4, "Child", "Page", parent2.Id); - using var tableReader = new DataTableReader(topics); + using var tableReader = new DataTableReader(topics); - tableReader.LoadTopicGraph(topic); + tableReader.LoadTopicGraph(topic); - Assert.Equal(parent2, child.Parent); + Assert.Equal(parent2, child.Parent); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH ATTRIBUTES: RETURNS ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with an record and confirms that a topic with those values is returned. - /// - [Fact] - public void LoadTopicGraph_WithAttributes_ReturnsAttributes() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH ATTRIBUTES: RETURNS ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with an record and confirms that a topic with those values is returned. + /// + [Fact] + public void LoadTopicGraph_WithAttributes_ReturnsAttributes() { - using var topics = new TopicsDataTable(); - using var attributes = new AttributesDataTable(); + using var topics = new TopicsDataTable(); + using var attributes = new AttributesDataTable(); - topics.AddRow(1, "Root", "Container", null); - attributes.AddRow(1, "Test", "Value"); + topics.AddRow(1, "Root", "Container", null); + attributes.AddRow(1, "Test", "Value"); - using var tableReader = new DataTableReader(new DataTable[] { topics, attributes }); + using var tableReader = new DataTableReader(new DataTable[] { topics, attributes }); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Equal("Value", topic?.Attributes.GetValue("Test")); + Assert.NotNull(topic); + Assert.Equal(1, topic?.Id); + Assert.Equal("Value", topic?.Attributes.GetValue("Test")); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH NULL ATTRIBUTES: REMOVES ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with an record representing a deleted attribute and confirms that an existing reference topic with that - /// attribute has the value removed. - /// - [Fact] - public void LoadTopicGraph_WithNullAttributes_RemovesAttribute() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH NULL ATTRIBUTES: REMOVES ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with an record representing a deleted attribute and confirms that an existing reference topic with that + /// attribute has the value removed. + /// + [Fact] + public void LoadTopicGraph_WithNullAttributes_RemovesAttribute() { - using var topics = new TopicsDataTable(); - using var attributes = new AttributesDataTable(); + using var topics = new TopicsDataTable(); + using var attributes = new AttributesDataTable(); - var topic = new Topic("Root", "Container", null, 1); + var topic = new Topic("Root", "Container", null, 1); - topic.Attributes.SetValue("Test", "Initial Value"); + topic.Attributes.SetValue("Test", "Initial Value"); - topics.AddRow(1, "Root", "Container"); - attributes.AddRow(1, "Test", null); + topics.AddRow(1, "Root", "Container"); + attributes.AddRow(1, "Test", null); - using var tableReader = new DataTableReader(new DataTable[] { topics, attributes }); + using var tableReader = new DataTableReader(new DataTable[] { topics, attributes }); - tableReader.LoadTopicGraph(topic); + tableReader.LoadTopicGraph(topic); - Assert.Null(topic.Attributes.GetValue("Test")); + Assert.Null(topic.Attributes.GetValue("Test")); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH RELATIONSHIP: RETURNS RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record and confirms that a topic with those values is returned. - /// - [Fact] - public void LoadTopicGraph_WithRelationship_ReturnsRelationship() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH RELATIONSHIP: RETURNS RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record and confirms that a topic with those values is returned. + /// + [Fact] + public void LoadTopicGraph_WithRelationship_ReturnsRelationship() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var relationships = new RelationshipsDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var relationships = new RelationshipsDataTable(); - topics.AddRow(1, "Root", "Container", null); - topics.AddRow(2, "Web", "Container", 1); - relationships.AddRow(1, "Test", 2, false); + topics.AddRow(1, "Root", "Container", null); + topics.AddRow(2, "Web", "Container", 1); + relationships.AddRow(1, "Test", 2, false); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, relationships }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, relationships }); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Equal(2, topic?.Relationships.GetValues("Test").FirstOrDefault()?.Id); - Assert.True(topic?.Relationships.IsFullyLoaded); + Assert.NotNull(topic); + Assert.Equal(1, topic?.Id); + Assert.Equal(2, topic?.Relationships.GetValues("Test").FirstOrDefault()?.Id); + Assert.True(topic?.Relationships.IsFullyLoaded); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH MISSING RELATIONSHIP: NOT FULLY LOADED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record that is missing and confirms that returns false. - /// - [Fact] - public void LoadTopicGraph_WithMissingRelationship_NotFullyLoaded() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH MISSING RELATIONSHIP: NOT FULLY LOADED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record that is missing and confirms that returns false. + /// + [Fact] + public void LoadTopicGraph_WithMissingRelationship_NotFullyLoaded() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var relationships = new RelationshipsDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var relationships = new RelationshipsDataTable(); - topics.AddRow(1, "Root", "Container", null); - relationships.AddRow(1, "Test", 2, false); + topics.AddRow(1, "Root", "Container", null); + relationships.AddRow(1, "Test", 2, false); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, relationships }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, relationships }); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Empty(topic?.Relationships); - Assert.False(topic?.Relationships.IsFullyLoaded); + Assert.NotNull(topic); + Assert.Equal(1, topic.Id); + Assert.Empty(topic.Relationships); + Assert.False(topic.Relationships.IsFullyLoaded); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH REFERENCE: RETURNS REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record and confirms that a topic with those values is returned. - /// - [Fact] - public void LoadTopicGraph_WithReference_ReturnsReference() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH REFERENCE: RETURNS REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record and confirms that a topic with those values is returned. + /// + [Fact] + public void LoadTopicGraph_WithReference_ReturnsReference() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var references = new TopicReferencesDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var references = new TopicReferencesDataTable(); - topics.AddRow(1, "Root", "Container", null); - topics.AddRow(2, "Web", "Container", 1); - references.AddRow(1, "Test", 2); + topics.AddRow(1, "Root", "Container", null); + topics.AddRow(2, "Web", "Container", 1); + references.AddRow(1, "Test", 2); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Equal(2, topic?.References.GetValue("Test")?.Id); - Assert.True(topic?.References.IsDirty()); + Assert.NotNull(topic); + Assert.Equal(1, topic?.Id); + Assert.Equal(2, topic?.References.GetValue("Test")?.Id); + Assert.True(topic?.References.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH EXTERNAL REFERENCE: RETURNS REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record and confirms that a topic with those values is returned. - /// - [Fact] - public void LoadTopicGraph_WithExternalReference_ReturnsReference() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH EXTERNAL REFERENCE: RETURNS REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record and confirms that a topic with those values is returned. + /// + [Fact] + public void LoadTopicGraph_WithExternalReference_ReturnsReference() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var references = new TopicReferencesDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var references = new TopicReferencesDataTable(); - var referenceTopic = new Topic("Web", "Container", null, 2); + var referenceTopic = new Topic("Web", "Container", null, 2); - topics.AddRow(1, "Root", "Container", null); - references.AddRow(1, "Test", 2); + topics.AddRow(1, "Root", "Container", null); + references.AddRow(1, "Test", 2); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); - var topic = tableReader.LoadTopicGraph(referenceTopic, false); + var topic = tableReader.LoadTopicGraph(referenceTopic, false); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Equal(2, topic?.References.GetValue("Test")?.Id); - Assert.True(topic?.References.IsFullyLoaded); - Assert.False(topic?.References.IsDirty()); + Assert.NotNull(topic); + Assert.Equal(1, topic?.Id); + Assert.Equal(2, topic?.References.GetValue("Test")?.Id); + Assert.True(topic?.References.IsFullyLoaded); + Assert.False(topic?.References.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH DELETED REFERENCE: REMOVES EXISTING REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record and confirms that existing references on a reference topic are deleted if they are - /// null in the . - /// - [Fact] - public void LoadTopicGraph_WithDeletedReference_RemovesExistingReference() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH DELETED REFERENCE: REMOVES EXISTING REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record and confirms that existing references on a reference topic are deleted if they are + /// null in the . + /// + [Fact] + public void LoadTopicGraph_WithDeletedReference_RemovesExistingReference() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var references = new TopicReferencesDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var references = new TopicReferencesDataTable(); - var referenceTopic = new Topic("Web", "Container", null, 1); + var referenceTopic = new Topic("Web", "Container", null, 1); - referenceTopic.References.SetValue("Reference", referenceTopic); + referenceTopic.References.SetValue("Reference", referenceTopic); - topics.AddRow(1, "Web", "Container", null); - references.AddRow(1, "Reference", null); + topics.AddRow(1, "Web", "Container", null); + references.AddRow(1, "Reference", null); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); - tableReader.LoadTopicGraph(referenceTopic, false); + tableReader.LoadTopicGraph(referenceTopic, false); - Assert.Null(referenceTopic.References.GetValue("Reference")); - Assert.True(referenceTopic.References.IsFullyLoaded); + Assert.Null(referenceTopic.References.GetValue("Reference")); + Assert.True(referenceTopic.References.IsFullyLoaded); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH MISSING REFERENCE: NOT FULLY LOADED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a record that is missing and confirms that returns false. - /// - [Fact] - public void LoadTopicGraph_WithMissingReference_NotFullyLoaded() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH MISSING REFERENCE: NOT FULLY LOADED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a record that is missing and confirms that returns false. + /// + [Fact] + public void LoadTopicGraph_WithMissingReference_NotFullyLoaded() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var references = new TopicReferencesDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var references = new TopicReferencesDataTable(); - topics.AddRow(1, "Root", "Container", null); - references.AddRow(1, "Test", 2); + topics.AddRow(1, "Root", "Container", null); + references.AddRow(1, "Test", 2); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, references }); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Empty(topic?.References); - Assert.False(topic?.References.IsFullyLoaded); + Assert.NotNull(topic); + Assert.Equal(1, topic.Id); + Assert.Empty(topic.References); + Assert.False(topic.References.IsFullyLoaded); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH DELETED RELATIONSHIP: REMOVES RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a deleted record and confirms that it is deleted from the referenceTopic graph. - /// - [Fact] - public void LoadTopicGraph_WithDeletedRelationship_RemovesRelationship() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH DELETED RELATIONSHIP: REMOVES RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a deleted record and confirms that it is deleted from the referenceTopic graph. + /// + [Fact] + public void LoadTopicGraph_WithDeletedRelationship_RemovesRelationship() { - var topic = new Topic("Test", "Container", null, 1); - var child = new Topic("Child", "Container", topic, 2); - var related = new Topic("Related", "Container", topic, 3); + var topic = new Topic("Test", "Container", null, 1); + var child = new Topic("Child", "Container", topic, 2); + var related = new Topic("Related", "Container", topic, 3); - child.Relationships.SetValue("Test", related); + child.Relationships.SetValue("Test", related); - using var empty = new AttributesDataTable(); - using var relationships = new RelationshipsDataTable(); + using var empty = new AttributesDataTable(); + using var relationships = new RelationshipsDataTable(); - relationships.AddRow(2, "Test", 3, true); + relationships.AddRow(2, "Test", 3, true); - using var tableReader = new DataTableReader(new DataTable[] { empty, empty, empty, relationships }); + using var tableReader = new DataTableReader(new DataTable[] { empty, empty, empty, relationships }); - tableReader.LoadTopicGraph(related); + tableReader.LoadTopicGraph(related); - Assert.Empty(topic.Relationships.GetValues("Test")); + Assert.Empty(topic.Relationships.GetValues("Test")); - } + } - /*========================================================================================================================== - | TEST: LOAD TOPIC GRAPH: WITH VERSION HISTORY: RETURNS VERSIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with an record and confirms that a topic with those values is returned. - /// - [Fact] - public void LoadTopicGraph_WithVersionHistory_ReturnsVersions() { + /*============================================================================================================================ + | TEST: LOAD TOPIC GRAPH: WITH VERSION HISTORY: RETURNS VERSIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with an record and confirms that a topic with those values is returned. + /// + [Fact] + public void LoadTopicGraph_WithVersionHistory_ReturnsVersions() { - using var topics = new TopicsDataTable(); - using var empty = new AttributesDataTable(); - using var versions = new VersionHistoryDataTable(); + using var topics = new TopicsDataTable(); + using var empty = new AttributesDataTable(); + using var versions = new VersionHistoryDataTable(); - topics.AddRow(1, "Root", "Container", null); - versions.AddRow(1, DateTime.MinValue); + topics.AddRow(1, "Root", "Container", null); + versions.AddRow(1, DateTime.MinValue); - using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, empty, versions }); + using var tableReader = new DataTableReader(new DataTable[] { topics, empty, empty, empty, empty, versions }); - var topic = tableReader.LoadTopicGraph(); + var topic = tableReader.LoadTopicGraph(); - Assert.NotNull(topic); - Assert.Equal(1, topic?.Id); - Assert.Single(topic?.VersionHistory); - Assert.True(topic?.VersionHistory.Contains(DateTime.MinValue)); + Assert.NotNull(topic); + Assert.Equal(1, topic.Id); + Assert.Single(topic.VersionHistory); + Assert.Contains(DateTime.MinValue, topic.VersionHistory); - } + } - /*========================================================================================================================== - | TEST: TOPIC LIST DATA TABLE: ADD ROW: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a and calls . Confirms that a with the expected data is returned. - /// - [Fact] - public void TopicListDataTable_AddRow_Succeeds() { + /*============================================================================================================================ + | TEST: TOPIC LIST DATA TABLE: ADD ROW: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a and calls . Confirms that a with the expected data is returned. + /// + [Fact] + public void TopicListDataTable_AddRow_Succeeds() { - var dataTable = new Data.Sql.Models.TopicListDataTable(); + var dataTable = new Data.Sql.Models.TopicListDataTable(); - dataTable.AddRow(1); - dataTable.AddRow(2); - dataTable.AddRow(2); + dataTable.AddRow(1); + dataTable.AddRow(2); + dataTable.AddRow(2); - Assert.Equal(3, dataTable.Rows.Count); - Assert.Single(dataTable.Columns); + Assert.Equal(3, dataTable.Rows.Count); + Assert.Single(dataTable.Columns); - dataTable.Dispose(); + dataTable.Dispose(); - } + } - /*========================================================================================================================== - | TEST: ATTRIBUTE VALUES DATA TABLE: ADD ROW: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a and calls . Confirms that a with the expected data is - /// returned. - /// - [Fact] - public void AttributeValuesDataTable_AddRow_Succeeds() { + /*============================================================================================================================ + | TEST: ATTRIBUTE VALUES DATA TABLE: ADD ROW: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a and calls . Confirms that a with the expected data is + /// returned. + /// + [Fact] + public void AttributeValuesDataTable_AddRow_Succeeds() { - var dataTable = new Data.Sql.Models.AttributeValuesDataTable(); + var dataTable = new Data.Sql.Models.AttributeValuesDataTable(); - dataTable.AddRow("Key", "Test"); - dataTable.AddRow("ContentType", "Page"); - dataTable.AddRow("ParentId", "4"); + dataTable.AddRow("Key", "Test"); + dataTable.AddRow("ContentType", "Page"); + dataTable.AddRow("ParentId", "4"); - Assert.Equal(3, dataTable.Rows.Count); - Assert.Equal(2, dataTable.Columns.Count); + Assert.Equal(3, dataTable.Rows.Count); + Assert.Equal(2, dataTable.Columns.Count); - dataTable.Dispose(); + dataTable.Dispose(); - } + } - /*========================================================================================================================== - | TEST: TOPIC REFERENCES DATA TABLE: ADD ROW: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a and calls . Confirms that a with the expected data is - /// returned. - /// - [Fact] - public void TopicReferencesDataTable_AddRow_Succeeds() { + /*============================================================================================================================ + | TEST: TOPIC REFERENCES DATA TABLE: ADD ROW: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a and calls . Confirms that a with the expected data is + /// returned. + /// + [Fact] + public void TopicReferencesDataTable_AddRow_Succeeds() { - var dataTable = new Data.Sql.Models.TopicReferencesDataTable(); + var dataTable = new Data.Sql.Models.TopicReferencesDataTable(); - dataTable.AddRow("BaseTopic", 1); - dataTable.AddRow("Parent", 2); - dataTable.AddRow("RootTopic", 3); + dataTable.AddRow("BaseTopic", 1); + dataTable.AddRow("Parent", 2); + dataTable.AddRow("RootTopic", 3); - Assert.Equal(3, dataTable.Rows.Count); - Assert.Equal(2, dataTable.Columns.Count); + Assert.Equal(3, dataTable.Rows.Count); + Assert.Equal(2, dataTable.Columns.Count); - dataTable.Dispose(); + dataTable.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: STRING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_String() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: STRING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_String() { - var command = new SqlCommand(); + var command = new SqlCommand(); - command.AddParameter("TopicKey", "Root"); + command.AddParameter("TopicKey", "Root"); - var sqlParameter = command.Parameters["@TopicKey"]; + var sqlParameter = command.Parameters["@TopicKey"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@TopicKey")); - Assert.Equal("Root", (string?)sqlParameter?.Value); - Assert.Equal(SqlDbType.VarChar, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@TopicKey")); + Assert.Equal("Root", (string?)sqlParameter?.Value); + Assert.Equal(SqlDbType.VarChar, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: NULL STRING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a null parameter value to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_NullString() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: NULL STRING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a null parameter value to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_NullString() { - var command = new SqlCommand(); + var command = new SqlCommand(); - command.AddParameter("TopicKey", (string?)null); + command.AddParameter("TopicKey", (string?)null); - var sqlParameter = command.Parameters["@TopicKey"]; + var sqlParameter = command.Parameters["@TopicKey"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@TopicKey")); - Assert.Null(sqlParameter?.Value); - Assert.Equal(SqlDbType.VarChar, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@TopicKey")); + Assert.Null(sqlParameter?.Value); + Assert.Equal(SqlDbType.VarChar, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: INT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_Int() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: INT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_Int() { - var command = new SqlCommand(); + var command = new SqlCommand(); - command.AddParameter("TopicId", 5); + command.AddParameter("TopicId", 5); - var sqlParameter = command.Parameters["@TopicId"]; + var sqlParameter = command.Parameters["@TopicId"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@TopicId")); - Assert.Equal(5, (int?)sqlParameter?.Value); - Assert.Equal(SqlDbType.Int, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@TopicId")); + Assert.Equal(5, (int?)sqlParameter?.Value); + Assert.Equal(SqlDbType.Int, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: BOOL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_Bool() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: BOOL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_Bool() { - var command = new SqlCommand(); + var command = new SqlCommand(); - command.AddParameter("IsHidden", true); + command.AddParameter("IsHidden", true); - var sqlParameter = command.Parameters["@IsHidden"]; + var sqlParameter = command.Parameters["@IsHidden"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@IsHidden")); - Assert.Equal(true, (bool?)sqlParameter?.Value); - Assert.Equal(SqlDbType.Bit, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@IsHidden")); + Assert.Equal(true, (bool?)sqlParameter?.Value); + Assert.Equal(SqlDbType.Bit, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: DATE/TIME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_DateTime() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: DATE/TIME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_DateTime() { - var command = new SqlCommand(); - var lastModified = DateTime.UtcNow; + var command = new SqlCommand(); + var lastModified = DateTime.UtcNow; - command.AddParameter("LastModified", lastModified); + command.AddParameter("LastModified", lastModified); - var sqlParameter = command.Parameters["@LastModified"]; + var sqlParameter = command.Parameters["@LastModified"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@LastModified")); - Assert.Equal(lastModified, (DateTime?)sqlParameter?.Value); - Assert.Equal(SqlDbType.DateTime2, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@LastModified")); + Assert.Equal(lastModified, (DateTime?)sqlParameter?.Value); + Assert.Equal(SqlDbType.DateTime2, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: DATA TABLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_DataTable() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: DATA TABLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_DataTable() { - var command = new SqlCommand(); - var dataTable = new Data.Sql.Models.TopicListDataTable(); + var command = new SqlCommand(); + var dataTable = new Data.Sql.Models.TopicListDataTable(); - command.AddParameter("Relationships", dataTable); + command.AddParameter("Relationships", dataTable); - var sqlParameter = command.Parameters["@Relationships"]; + var sqlParameter = command.Parameters["@Relationships"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@Relationships")); - Assert.Equal(dataTable, (DataTable?)sqlParameter?.Value); - Assert.Equal(SqlDbType.Structured, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@Relationships")); + Assert.Equal(dataTable, (DataTable?)sqlParameter?.Value); + Assert.Equal(SqlDbType.Structured, sqlParameter?.SqlDbType); - command.Dispose(); - dataTable.Dispose(); + command.Dispose(); + dataTable.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD PARAMETER: STRING BUILDER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddParameter_StringBuilder() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD PARAMETER: STRING BUILDER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddParameter_StringBuilder() { - var command = new SqlCommand(); - var xml = new StringBuilder(); + var command = new SqlCommand(); + var xml = new StringBuilder(); - command.AddParameter("AttributesXml", xml); + command.AddParameter("AttributesXml", xml); - var sqlParameter = command.Parameters["@AttributesXml"]; + var sqlParameter = command.Parameters["@AttributesXml"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@AttributesXml")); - Assert.Equal(xml.ToString(), (string?)sqlParameter?.Value); - Assert.Equal(SqlDbType.Xml, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@AttributesXml")); + Assert.Equal(xml.ToString(), (string?)sqlParameter?.Value); + Assert.Equal(SqlDbType.Xml, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD OUTPUT PARAMETER: RETURN CODE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. - /// - [Fact] - public void SqlCommand_AddOutputParameter_ReturnCode() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD OUTPUT PARAMETER: RETURN CODE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. + /// + [Fact] + public void SqlCommand_AddOutputParameter_ReturnCode() { - var command = new SqlCommand(); + var command = new SqlCommand(); - command.AddOutputParameter("TopicId"); + command.AddOutputParameter("TopicId"); - var sqlParameter = command.Parameters["@TopicId"]; + var sqlParameter = command.Parameters["@TopicId"]; - sqlParameter.Value = 5; + sqlParameter.Value = 5; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@TopicId")); - Assert.Equal(5, command.GetReturnCode("TopicId")); - Assert.Equal(ParameterDirection.ReturnValue, sqlParameter?.Direction); - Assert.Equal(SqlDbType.Int, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@TopicId")); + Assert.Equal(5, command.GetReturnCode("TopicId")); + Assert.Equal(ParameterDirection.ReturnValue, sqlParameter?.Direction); + Assert.Equal(SqlDbType.Int, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - /*========================================================================================================================== - | TEST: SQL COMMAND: ADD OUTPUT PARAMETER: RETURN DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a object and adds a parameter to it using the extension method. Ensures the default return code is - /// returned, if the value isn't explicitly set. - /// - [Fact] - public void SqlCommand_AddOutputParameter_ReturnsDefault() { + /*============================================================================================================================ + | TEST: SQL COMMAND: ADD OUTPUT PARAMETER: RETURN DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a object and adds a parameter to it using the extension method. Ensures the default return code is + /// returned, if the value isn't explicitly set. + /// + [Fact] + public void SqlCommand_AddOutputParameter_ReturnsDefault() { - var command = new SqlCommand(); + var command = new SqlCommand(); - command.AddOutputParameter("TopicId"); + command.AddOutputParameter("TopicId"); - var sqlParameter = command.Parameters["@TopicId"]; + var sqlParameter = command.Parameters["@TopicId"]; - Assert.Single(command.Parameters); - Assert.True(command.Parameters.Contains("@TopicId")); - Assert.Equal(-1, command.GetReturnCode("TopicId")); - Assert.Equal(ParameterDirection.ReturnValue, sqlParameter?.Direction); - Assert.Equal(SqlDbType.Int, sqlParameter?.SqlDbType); + Assert.Single(command.Parameters); + Assert.True(command.Parameters.Contains("@TopicId")); + Assert.Equal(-1, command.GetReturnCode("TopicId")); + Assert.Equal(ParameterDirection.ReturnValue, sqlParameter?.Direction); + Assert.Equal(SqlDbType.Int, sqlParameter?.SqlDbType); - command.Dispose(); + command.Dispose(); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TestDoubles/DummyStaticTypeLookupService.cs b/OnTopic.Tests/TestDoubles/DummyStaticTypeLookupService.cs index aed9d8ae..1545a1bb 100644 --- a/OnTopic.Tests/TestDoubles/DummyStaticTypeLookupService.cs +++ b/OnTopic.Tests/TestDoubles/DummyStaticTypeLookupService.cs @@ -4,70 +4,69 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: DUMMY STATIC TYPE LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The provides a wrapper around the in +/// order to relay access to protected members for the purpose of testing. The +/// doesn't implement any functionality of its own; it's just a pass-through wrapper. +/// +[ExcludeFromCodeCoverage] +public class DummyStaticTypeLookupService: StaticTypeLookupService { /*============================================================================================================================ - | CLASS: DUMMY STATIC TYPE LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The provides a wrapper around the in - /// order to relay access to protected members for the purpose of testing. The - /// doesn't implement any functionality of its own; it's just a pass-through wrapper. + /// Establishes a new instance of a . Optionally accepts a list of instances and a default value. /// - [ExcludeFromCodeCoverage] - public class DummyStaticTypeLookupService: StaticTypeLookupService { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . Optionally accepts a list of instances and a default value. - /// - /// The list of instances to expose as part of this service. - public DummyStaticTypeLookupService( - IEnumerable? types = null - ): base(types) { - } + /// The list of instances to expose as part of this service. + public DummyStaticTypeLookupService( + IEnumerable? types = null + ): base(types) { + } - /*========================================================================================================================== - | METHOD: LOOKUP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Type? Lookup(params string[] typeNames) => base.Lookup(typeNames); + /*============================================================================================================================ + | METHOD: LOOKUP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Type? Lookup(params string[] typeNames) => base.Lookup(typeNames); - /*========================================================================================================================== - | METHOD: ADD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public new void Add(Type type) => base.Add(type); + /*============================================================================================================================ + | METHOD: ADD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public new void Add(Type type) => base.Add(type); - /*========================================================================================================================== - | METHOD: TRY ADD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public new bool TryAdd(Type type) => base.TryAdd(type); + /*============================================================================================================================ + | METHOD: TRY ADD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public new bool TryAdd(Type type) => base.TryAdd(type); - /*========================================================================================================================== - | METHOD: ADD OR REPLACE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public new void AddOrReplace(Type type) => base.AddOrReplace(type); + /*============================================================================================================================ + | METHOD: ADD OR REPLACE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public new void AddOrReplace(Type type) => base.AddOrReplace(type); - /*========================================================================================================================== - | METHOD: CONTAINS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public new bool Contains(Type type) => base.Contains(type); + /*============================================================================================================================ + | METHOD: CONTAINS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public new bool Contains(Type type) => base.Contains(type); - /// - public new bool Contains(string key) => base.Contains(key); + /// + public new bool Contains(string key) => base.Contains(key); - /*========================================================================================================================== - | METHOD: REMOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public new void Remove(string key) => base.Remove(key); + /*============================================================================================================================ + | METHOD: REMOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public new void Remove(string key) => base.Remove(key); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TestDoubles/FakeViewModelLookupService.cs b/OnTopic.Tests/TestDoubles/FakeViewModelLookupService.cs index 304b6094..eee92154 100644 --- a/OnTopic.Tests/TestDoubles/FakeViewModelLookupService.cs +++ b/OnTopic.Tests/TestDoubles/FakeViewModelLookupService.cs @@ -7,69 +7,68 @@ using OnTopic.Tests.ViewModels; using OnTopic.Tests.ViewModels.Metadata; -namespace OnTopic.Tests.TestDoubles { +namespace OnTopic.Tests.TestDoubles; + +/*============================================================================================================================== +| CLASS: FAKE TOPIC LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides access to derived types of classes. +/// +/// +/// Allows testing of services that depend on without using expensive reflection. +/// +public class FakeViewModelLookupService: TopicViewModelLookupService { /*============================================================================================================================ - | CLASS: FAKE TOPIC LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides access to derived types of classes. + /// Instantiates a new instance of the . /// - /// - /// Allows testing of services that depend on without using expensive reflection. - /// - public class FakeViewModelLookupService: TopicViewModelLookupService { + /// A new instance of the . + public FakeViewModelLookupService() : base() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add test specific view models \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the . - /// - /// A new instance of the . - public FakeViewModelLookupService() : base() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Add test specific view models - \-----------------------------------------------------------------------------------------------------------------------*/ - Add(typeof(AmbiguousRelationTopicViewModel)); - Add(typeof(AscendentSpecializedTopicViewModel)); - Add(typeof(AscendentTopicViewModel)); - Add(typeof(CircularTopicViewModel)); - Add(typeof(ConstructedTopicViewModel)); - Add(typeof(DefaultValueTopicViewModel)); - Add(typeof(DescendentSpecializedTopicViewModel)); - Add(typeof(DescendentTopicViewModel)); - Add(typeof(DisableMappingTopicViewModel)); - Add(typeof(FallbackViewModel)); - Add(typeof(FilteredTopicViewModel)); - Add(typeof(FlattenChildrenTopicViewModel)); - Add(typeof(InheritedPropertyTopicViewModel)); - Add(typeof(KeyOnlyTopicViewModel)); - Add(typeof(MapAsTopicViewModel)); - Add(typeof(MapToParentTopicViewModel)); - Add(typeof(MethodBasedViewModel)); - Add(typeof(MinimumLengthPropertyTopicViewModel)); - Add(typeof(NestedTopicViewModel)); - Add(typeof(PropertyAliasTopicViewModel)); - Add(typeof(RecordTopicViewModel)); - Add(typeof(RelatedEntityTopicViewModel)); - Add(typeof(RelationTopicViewModel)); - Add(typeof(RelationWithChildrenTopicViewModel)); - Add(typeof(RequiredObjectTopicViewModel)); - Add(typeof(RequiredTopicViewModel)); - Add(typeof(TopicReferenceAttributeDescriptorTopicViewModel)); - Add(typeof(TopicReferenceTopicViewModel)); + Add(typeof(AmbiguousRelationTopicViewModel)); + Add(typeof(AscendentSpecializedTopicViewModel)); + Add(typeof(AscendentTopicViewModel)); + Add(typeof(CircularTopicViewModel)); + Add(typeof(ConstructedTopicViewModel)); + Add(typeof(DefaultValueTopicViewModel)); + Add(typeof(DescendentSpecializedTopicViewModel)); + Add(typeof(DescendentTopicViewModel)); + Add(typeof(DisableMappingTopicViewModel)); + Add(typeof(FallbackViewModel)); + Add(typeof(FilteredTopicViewModel)); + Add(typeof(FlattenChildrenTopicViewModel)); + Add(typeof(InheritedPropertyTopicViewModel)); + Add(typeof(KeyOnlyTopicViewModel)); + Add(typeof(MapAsTopicViewModel)); + Add(typeof(MapToParentTopicViewModel)); + Add(typeof(MethodBasedViewModel)); + Add(typeof(MinimumLengthPropertyTopicViewModel)); + Add(typeof(NestedTopicViewModel)); + Add(typeof(PropertyAliasTopicViewModel)); + Add(typeof(RecordTopicViewModel)); + Add(typeof(RelatedEntityTopicViewModel)); + Add(typeof(RelationTopicViewModel)); + Add(typeof(RelationWithChildrenTopicViewModel)); + Add(typeof(RequiredObjectTopicViewModel)); + Add(typeof(RequiredTopicViewModel)); + Add(typeof(TopicReferenceAttributeDescriptorTopicViewModel)); + Add(typeof(TopicReferenceTopicViewModel)); - /*------------------------------------------------------------------------------------------------------------------------ - | Add test specific metadata view models - \-----------------------------------------------------------------------------------------------------------------------*/ - Add(typeof(AttributeDescriptorTopicViewModel)); - Add(typeof(ContentTypeDescriptorTopicViewModel)); - Add(typeof(MetadataLookupTopicViewModel)); - Add(typeof(TextAttributeDescriptorTopicViewModel)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add test specific metadata view models + \-------------------------------------------------------------------------------------------------------------------------*/ + Add(typeof(AttributeDescriptorTopicViewModel)); + Add(typeof(ContentTypeDescriptorTopicViewModel)); + Add(typeof(MetadataLookupTopicViewModel)); + Add(typeof(TextAttributeDescriptorTopicViewModel)); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TopicMappingServiceTest.cs b/OnTopic.Tests/TopicMappingServiceTest.cs index d2296953..56f154ab 100644 --- a/OnTopic.Tests/TopicMappingServiceTest.cs +++ b/OnTopic.Tests/TopicMappingServiceTest.cs @@ -18,1637 +18,1654 @@ using OnTopic.Tests.ViewModels.Metadata; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC MAPPING SERVICE TESTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the using local DTOs. +/// +[ExcludeFromCodeCoverage] +[Xunit.Collection("Shared Repository")] +public class TopicMappingServiceTest { /*============================================================================================================================ - | CLASS: TOPIC MAPPING SERVICE TESTS + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly ITopicMappingService _mappingService; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the using local DTOs. + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - [Xunit.Collection("Shared Repository")] - public class TopicMappingServiceTest { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. + /// + public TopicMappingServiceTest(TopicInfrastructureFixture fixture) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ITopicMappingService _mappingService; + Contract.Requires(fixture, nameof(fixture)); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Set services \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. - /// - public TopicMappingServiceTest(TopicInfrastructureFixture fixture) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(fixture, nameof(fixture)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set services - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = fixture.CachedTopicRepository; - _mappingService = fixture.MappingService; + _topicRepository = fixture.CachedTopicRepository; + _mappingService = fixture.MappingService; - } + } - /*========================================================================================================================== - | TEST: MAP: LOAD TESTING: EVALUATE THRESHOLD + /*============================================================================================================================ + | TEST: MAP: LOAD TESTING: EVALUATE THRESHOLD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests creating and mapping instances in bulk, + /// as a quick-and-easy way of assessing performance. + /// + /// + /// + /// The includes functionality to map properties to attributes via a constructor that + /// accepts a . This introduces some overhead which is not cost effective if there are + /// not any attributes that map to properties. For larger numbers of mapped attributes, however, the can reduce the mapping time considerably, while also giving more control over the model + /// construction to the model developer. This test is intended to help identify and optimize that threshold based on + /// improvements to the underlying , , and convenience method. + /// + /// + /// This is only intended to be enabled when needed for specialized performance testing. + /// + /// + [Fact] + public async Task Map_LoadTesting_EvaluateThreshold() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests creating and mapping instances in bulk, - /// as a quick-and-easy way of assessing performance. - /// - /// - /// - /// The includes functionality to map properties to attributes via a constructor that - /// accepts a . This introduces some overhead which is not cost effective if there are - /// not any attributes that map to properties. For larger numbers of mapped attributes, however, the can reduce the mapping time considerably, while also giving more control over the model - /// construction to the model developer. This test is intended to help identify and optimize that threshold based on - /// improvements to the underlying , , and convenience method. - /// - /// - /// This is only intended to be enabled when needed for specialized performance testing. - /// - /// - [Fact] - public async Task Map_LoadTesting_EvaluateThreshold() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var runs = 0; // The number of mapping operations to perform - var propertyCount = 10; // The number of property values to set on the LoadTestingModel - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish data model - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = new Topic("Test", "ContentList", null); - - for (var i = 0; i <= propertyCount; i++) { - topic.Attributes.SetInteger("Property"+i, i); - } + var runs = 0; // The number of mapping operations to perform + var propertyCount = 10; // The number of property values to set on the LoadTestingModel - /*------------------------------------------------------------------------------------------------------------------------ - | Run load testing - \-----------------------------------------------------------------------------------------------------------------------*/ - for (var i = 0; i < runs; i++) { - await _mappingService.MapAsync(topic).ConfigureAwait(false); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish data model + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = new Topic("Test", "ContentList", null); - /*------------------------------------------------------------------------------------------------------------------------ - | Always assume the test passed - \-----------------------------------------------------------------------------------------------------------------------*/ - Assert.True(true); + for (var i = 0; i <= propertyCount; i++) { + topic.Attributes.SetInteger("Property"+i, i); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Run load testing + \-------------------------------------------------------------------------------------------------------------------------*/ + for (var i = 0; i < runs; i++) { + await _mappingService.MapAsync(topic); } - /*========================================================================================================================== - | TEST: MAP: LOAD TESTING: EVALUATE TIME + /*-------------------------------------------------------------------------------------------------------------------------- + | Always assume the test passed \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests creating and mapping instances in bulk, - /// as a quick-and-easy way of assessing performance. - /// - [Fact] - public async Task Map_LoadTesting_EvaluateTime() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var runs = 0; // The number of mapping operations to perform - var useFullAttributeSet = false; // Include a larget set of attribute values - var includeNestedTopics = false; // Only include a minimal set of properties - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish object model - \-----------------------------------------------------------------------------------------------------------------------*/ - var currentId = 1; - var baseTopic = new Topic("Base", "Page", null, currentId++); - var grandparent = new Topic("Grandparent", "Page", null, currentId++); - var parent = new Topic("Parent", "Page", grandparent, currentId++); - var topic = new Topic("Test", "ContentList", parent, currentId++); - var contentItems = new Topic("ContentItems", "List", topic, currentId++); - - if (includeNestedTopics) { - _ = new Topic("Item1", "ContentItem", contentItems, currentId++); - _ = new Topic("Item2", "ContentItem", contentItems, currentId++); - _ = new Topic("Item3", "ContentItem", contentItems, currentId++); - _ = new Topic("Item4", "ContentItem", contentItems, currentId++); - _ = new Topic("Item5", "ContentItem", contentItems, currentId++); - _ = new Topic("Item6", "ContentItem", contentItems, currentId++); - } + Assert.True(true); - grandparent.BaseTopic = baseTopic; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Populate attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var contentItem in contentItems.Children) { - contentItem.Attributes.SetDateTime("LastModified", DateTime.Now); - contentItem.Attributes.SetValue("Description", "Value1"); - if (useFullAttributeSet) { - contentItem.Attributes.SetValue("LearnMoreUrl", "/Topic/23/"); - contentItem.Attributes.SetValue("ThumbnailImage", "/Image.jpg"); - contentItem.Attributes.SetValue("Description", "Value1"); - contentItem.Attributes.SetValue("Category", "Gumby"); - } - } + /*============================================================================================================================ + | TEST: MAP: LOAD TESTING: EVALUATE TIME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests creating and mapping instances in bulk, + /// as a quick-and-easy way of assessing performance. + /// + [Fact] + public async Task Map_LoadTesting_EvaluateTime() { - topic.Attributes.SetValue("Title", "Friendly Title"); - topic.Attributes.SetValue("IsHidden", "0"); - if (useFullAttributeSet) { - topic.Attributes.SetValue("View", "Test"); - topic.Attributes.SetValue("ShortTitle", "Short Title"); - topic.Attributes.SetValue("Subtitle", "Subtitle"); - topic.Attributes.SetValue("MetaTitle", "Meta Title"); - topic.Attributes.SetValue("MetaDescription", "Meta Description"); - topic.Attributes.SetValue("MetaKeywords", "Load;Test;Keywords"); - topic.Attributes.SetValue("NoIndex", "0"); - topic.Attributes.SetValue("Body", "Body of test topic"); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var runs = 0; // The number of mapping operations to perform + var useFullAttributeSet = false; // Include a larget set of attribute values + var includeNestedTopics = false; // Only include a minimal set of properties + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish object model + \-------------------------------------------------------------------------------------------------------------------------*/ + var currentId = 1; + var baseTopic = new Topic("Base", "Page", null, currentId++); + var grandparent = new Topic("Grandparent", "Page", null, currentId++); + var parent = new Topic("Parent", "Page", grandparent, currentId++); + var topic = new Topic("Test", "ContentList", parent, currentId++); + var contentItems = new Topic("ContentItems", "List", topic, currentId++); + + if (includeNestedTopics) { + _ = new Topic("Item1", "ContentItem", contentItems, currentId++); + _ = new Topic("Item2", "ContentItem", contentItems, currentId++); + _ = new Topic("Item3", "ContentItem", contentItems, currentId++); + _ = new Topic("Item4", "ContentItem", contentItems, currentId++); + _ = new Topic("Item5", "ContentItem", contentItems, currentId++); + _ = new Topic("Item6", "ContentItem", contentItems, currentId++); + } - baseTopic.Attributes.SetValue("Title", "Inherited Title"); + grandparent.BaseTopic = baseTopic; - /*------------------------------------------------------------------------------------------------------------------------ - | Run load testing - \-----------------------------------------------------------------------------------------------------------------------*/ - for (var i = 0; i <= runs; i++) { - await _mappingService.MapAsync(topic).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Populate attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var contentItem in contentItems.Children) { + contentItem.Attributes.SetDateTime("LastModified", DateTime.Now); + contentItem.Attributes.SetValue("Description", "Value1"); + if (useFullAttributeSet) { + contentItem.Attributes.SetValue("LearnMoreUrl", "/Topic/23/"); + contentItem.Attributes.SetValue("ThumbnailImage", "/Image.jpg"); + contentItem.Attributes.SetValue("Description", "Value1"); + contentItem.Attributes.SetValue("Category", "Gumby"); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Always assume the test passed - \-----------------------------------------------------------------------------------------------------------------------*/ - Assert.True(true); + topic.Attributes.SetValue("Title", "Friendly Title"); + topic.Attributes.SetValue("IsHidden", "0"); + if (useFullAttributeSet) { + topic.Attributes.SetValue("View", "Test"); + topic.Attributes.SetValue("ShortTitle", "Short Title"); + topic.Attributes.SetValue("Subtitle", "Subtitle"); + topic.Attributes.SetValue("MetaTitle", "Meta Title"); + topic.Attributes.SetValue("MetaDescription", "Meta Description"); + topic.Attributes.SetValue("MetaKeywords", "Load;Test;Keywords"); + topic.Attributes.SetValue("NoIndex", "0"); + topic.Attributes.SetValue("Body", "Body of test topic"); + } + + baseTopic.Attributes.SetValue("Title", "Inherited Title"); + /*-------------------------------------------------------------------------------------------------------------------------- + | Run load testing + \-------------------------------------------------------------------------------------------------------------------------*/ + for (var i = 0; i <= runs; i++) { + await _mappingService.MapAsync(topic); } - /*========================================================================================================================== - | TEST: MAP: GENERIC: RETURNS NEW MODEL + /*-------------------------------------------------------------------------------------------------------------------------- + | Always assume the test passed \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting basic scalar values by specifying an explicit type. - /// - [Fact] - public async Task Map_Generic_ReturnsNewModel() { + Assert.True(true); - var topic = new Topic("Test", "Page"); + } - topic.Attributes.SetValue("MetaTitle", "ValueA"); - topic.Attributes.SetValue("Title", "Value1"); + /*============================================================================================================================ + | TEST: MAP: GENERIC: RETURNS NEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting basic scalar values by specifying an explicit type. + /// + [Fact] + public async Task Map_Generic_ReturnsNewModel() { - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var topic = new Topic("Test", "Page"); - Assert.Equal("ValueA", target?.MetaTitle); - Assert.Equal("Value1", target?.Title); + topic.Attributes.SetValue("MetaTitle", "ValueA"); + topic.Attributes.SetValue("Title", "Value1"); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: GENERIC: RETURNS NEW RECORD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a basic record type can be mapped by - /// explicitly setting defining the target type. - /// - [Fact] - public async Task Map_Generic_ReturnsNewRecord() { + Assert.Equal("ValueA", target?.MetaTitle); + Assert.Equal("Value1", target?.Title); - var topic = new Topic("Test", "Page"); + } - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: GENERIC: RETURNS NEW RECORD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a basic record type can be mapped by + /// explicitly setting defining the target type. + /// + [Fact] + public async Task Map_Generic_ReturnsNewRecord() { - Assert.Equal(topic.Key, target?.Key); + var topic = new Topic("Test", "Page"); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: DYNAMIC: RETURNS NEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting basic scalar values by allowing it to dynamically - /// determine the instance type. - /// - [Fact] - public async Task Map_Dynamic_ReturnsNewModel() { + Assert.Equal(topic.Key, target?.Key); - var topic = new Topic("Test", "Page"); + } - topic.Attributes.SetValue("MetaTitle", "ValueA"); - topic.Attributes.SetValue("Title", "Value1"); + /*============================================================================================================================ + | TEST: MAP: DYNAMIC: RETURNS NEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting basic scalar values by allowing it to dynamically + /// determine the instance type. + /// + [Fact] + public async Task Map_Dynamic_ReturnsNewModel() { - var target = (PageTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + var topic = new Topic("Test", "Page"); - Assert.Equal("ValueA", target?.MetaTitle); - Assert.Equal("Value1", target?.Title); + topic.Attributes.SetValue("MetaTitle", "ValueA"); + topic.Attributes.SetValue("Title", "Value1"); - } + var target = (PageTopicViewModel?)await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: GENERIC: RETURNS CONVERTED PROPERTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a basic source property of type string—e.g., —can successfully be converted to a target type of an integer—e.g., . - /// - [Fact] - public async Task Map_Generic_ReturnsConvertedProperty() { + Assert.Equal("ValueA", target?.MetaTitle); + Assert.Equal("Value1", target?.Title); - var topic = new CustomTopic("Test", "CustomTopic") { - NumericAttribute = 1, - BooleanAsStringAttribute = "1" - }; + } - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: GENERIC: RETURNS CONVERTED PROPERTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a basic source property of type string—e.g., —can successfully be converted to a target type of an integer—e.g., . + /// + [Fact] + public async Task Map_Generic_ReturnsConvertedProperty() { - Assert.True(target?.BooleanAttribute); - Assert.Equal(topic.NumericAttribute.ToString(CultureInfo.InvariantCulture), target?.NumericAsStringAttribute); + var topic = new CustomTopic("Test", "CustomTopic") { + NumericAttribute = 1, + BooleanAsStringAttribute = "1" + }; - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: ATTRIBUTE DICTIONARY: RETURNS NEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and attempts to map a view model with a constructor containing a . Confirms that the expected model is returned. - /// - [Fact] - public async Task Map_AttributeDictionary_ReturnsNewModel() { + Assert.True(target?.BooleanAttribute); + Assert.Equal(topic.NumericAttribute.ToString(CultureInfo.InvariantCulture), target?.NumericAsStringAttribute); - var topic = new Topic("Test", "Page"); - var lastModified = new DateTime(2021, 12, 22); + } - topic.Attributes.SetValue("Title", "Value"); - topic.Attributes.SetValue("ShortTitle", "Short Title"); - topic.Attributes.SetValue("Subtitle", "Subtitle"); - topic.Attributes.SetValue("MetaTitle", "Meta Title"); - topic.Attributes.SetValue("MetaDescription", "Meta Description"); - topic.Attributes.SetValue("MetaKeywords", "Load;Test;Keywords"); - topic.Attributes.SetValue("NoIndex", "0"); - topic.Attributes.SetValue("Body", "Body of test topic"); - topic.Attributes.SetValue("MappedProperty", "Mapped Value"); - topic.Attributes.SetValue("UnmappedProperty", "Unmapped Value"); - topic.VersionHistory.Add(lastModified); - - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - - Assert.Equal("Value", target?.Title); - Assert.Equal("Short Title", target?.ShortTitle); - Assert.Equal("Subtitle", target?.Subtitle); - Assert.Equal("Meta Title", target?.MetaTitle); - Assert.Equal("Meta Description", target?.MetaDescription); - Assert.Equal(false, target?.NoIndex); - Assert.Equal("Load;Test;Keywords", target?.MetaKeywords); - Assert.Equal("Mapped Value", target?.MappedProperty); - Assert.Null(target?.UnmappedProperty); - Assert.Equal(lastModified, target?.LastModified); + /*============================================================================================================================ + | TEST: MAP: ATTRIBUTE DICTIONARY: RETURNS NEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and attempts to map a view model with a constructor containing a . Confirms that the expected model is returned. + /// + [Fact] + public async Task Map_AttributeDictionary_ReturnsNewModel() { + + var topic = new Topic("Test", "Page"); + var lastModified = new DateTime(2021, 12, 22); + + topic.Attributes.SetValue("Title", "Value"); + topic.Attributes.SetValue("ShortTitle", "Short Title"); + topic.Attributes.SetValue("Subtitle", "Subtitle"); + topic.Attributes.SetValue("MetaTitle", "Meta Title"); + topic.Attributes.SetValue("MetaDescription", "Meta Description"); + topic.Attributes.SetValue("MetaKeywords", "Load;Test;Keywords"); + topic.Attributes.SetValue("NoIndex", "0"); + topic.Attributes.SetValue("Body", "Body of test topic"); + topic.Attributes.SetValue("MappedProperty", "Mapped Value"); + topic.Attributes.SetValue("UnmappedProperty", "Unmapped Value"); + topic.VersionHistory.Add(lastModified); + + var target = await _mappingService.MapAsync(topic); + + Assert.Equal("Value", target?.Title); + Assert.Equal("Short Title", target?.ShortTitle); + Assert.Equal("Subtitle", target?.Subtitle); + Assert.Equal("Meta Title", target?.MetaTitle); + Assert.Equal("Meta Description", target?.MetaDescription); + Assert.Equal(false, target?.NoIndex); + Assert.Equal("Load;Test;Keywords", target?.MetaKeywords); + Assert.Equal("Mapped Value", target?.MappedProperty); + Assert.Null(target?.UnmappedProperty); + Assert.Equal(lastModified, target?.LastModified); + + } - } + /*============================================================================================================================ + | TEST: MAP: CONSTRUCTOR: RETURNS NEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and attempts to map a view model with a constructor containing a + /// scalar value, topic reference, relationship, and an optional parameter. Confirms that the expected model is returned. + /// + [Fact] + public async Task Map_Constructor_ReturnsNewModel() { - /*========================================================================================================================== - | TEST: MAP: CONSTRUCTOR: RETURNS NEW MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and attempts to map a view model with a constructor containing a - /// scalar value, topic reference, relationship, and an optional parameter. Confirms that the expected model is returned. - /// - [Fact] - public async Task Map_Constructor_ReturnsNewModel() { + var topic = new Topic("Topic", "Constructed", null, 1); + var related1 = new Topic("Related1", "Constructed", null, 2); + var related2 = new Topic("Related2", "Constructed", null, 3); + var related3 = new Topic("Related3", "Constructed", null, 4); - var topic = new Topic("Topic", "Constructed", null, 1); - var related1 = new Topic("Related1", "Constructed", null, 2); - var related2 = new Topic("Related2", "Constructed", null, 3); - var related3 = new Topic("Related3", "Constructed", null, 4); + topic.Attributes.SetValue("Value", "Foo"); + topic.Attributes.SetValue("ScalarValue", "Invalid"); + topic.Attributes.SetValue("OptionalValue", "3"); + topic.References.SetValue("TopicReference", related1); + topic.Relationships.SetValue("Related", related2); + topic.Relationships.SetValue("Relationships", related2); //Should not be mapped + topic.Relationships.SetValue("Relationships", related3); //Should not be mapped - topic.Attributes.SetValue("Value", "Foo"); - topic.Attributes.SetValue("ScalarValue", "Invalid"); - topic.Attributes.SetValue("OptionalValue", "3"); - topic.References.SetValue("TopicReference", related1); - topic.Relationships.SetValue("Related", related2); - topic.Relationships.SetValue("Relationships", related2); //Should not be mapped - topic.Relationships.SetValue("Relationships", related3); //Should not be mapped + related1.Attributes.SetValue("Value", "Bar"); + related1.References.SetValue("TopicReference", related3); - related1.Attributes.SetValue("Value", "Bar"); - related1.References.SetValue("TopicReference", related3); + related3.Attributes.SetValue("Value", "Baz"); - related3.Attributes.SetValue("Value", "Baz"); + var target = await _mappingService.MapAsync(topic); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + Assert.NotNull(target); + Assert.Equal("Foo", target.ScalarValue); + Assert.NotNull(target.TopicReference); + Assert.NotNull(target.Relationships); + Assert.Equal(5, target.OptionalValue); + Assert.Single(target.Relationships); - Assert.Equal("Foo", target?.ScalarValue); - Assert.NotNull(target?.TopicReference); - Assert.NotNull(target?.Relationships); - Assert.Equal(5, target?.OptionalValue); - Assert.Single(target?.Relationships); + Assert.Equal("Bar", target.TopicReference.ScalarValue); - Assert.Equal("Bar", target?.TopicReference?.ScalarValue); + Assert.NotNull(target.TopicReference.TopicReference); + Assert.Equal("Baz", target.TopicReference.TopicReference.ScalarValue); - Assert.NotNull(target?.TopicReference?.TopicReference); - Assert.Equal("Baz", target?.TopicReference!.TopicReference!.ScalarValue); + Assert.Null(target.TopicReference.TopicReference.TopicReference); - Assert.Null(target?.TopicReference!.TopicReference!.TopicReference); + } - } + /*============================================================================================================================ + | TEST: MAP: GENERIC: INITIALIZES COLLECTIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and attempts to map a view model whose collections are not initialized + /// in order to confirm that it can successfully initialize them. + /// + [Fact] + public async Task Map_Generic_InitializesCollections() { - /*========================================================================================================================== - | TEST: MAP: GENERIC: INITIALIZES COLLECTIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and attempts to map a view model whose collections are not initialized - /// in order to confirm that it can successfully initialize them. - /// - [Fact] - public async Task Map_Generic_InitializesCollections() { + var topic = new Topic("Topic", "NullCollection", null, 1); + var reference = new Topic("Reference", "KeyOnly", null, 2); - var topic = new Topic("Topic", "NullCollection", null, 1); - var reference = new Topic("Reference", "KeyOnly", null, 2); + topic.Relationships.SetValue("Collection", reference); - topic.Relationships.SetValue("Collection", reference); + var result = await _mappingService.MapAsync(topic); - var result = await _mappingService.MapAsync(topic).ConfigureAwait(false); + Assert.NotNull(result); + Assert.NotNull(result.NullCollection); + Assert.NotNull(result.NullICollection); + Assert.NotNull(result.NullIList); + Assert.NotNull(result.NullIEnumerable); + Assert.NotNull(result.NullTypedCollection); - Assert.NotNull(result?.NullCollection); - Assert.NotNull(result?.NullICollection); - Assert.NotNull(result?.NullIList); - Assert.NotNull(result?.NullIEnumerable); - Assert.NotNull(result?.NullTypedCollection); + Assert.NotEmpty(result.NullCollection); + Assert.NotEmpty(result.NullICollection); + Assert.NotEmpty(result.NullIList); + Assert.NotEmpty(result.NullIEnumerable); + Assert.NotEmpty(result.NullTypedCollection); - Assert.NotEmpty(result?.NullCollection); - Assert.NotEmpty(result?.NullICollection); - Assert.NotEmpty(result?.NullIList); - Assert.NotEmpty(result?.NullIEnumerable); - Assert.NotEmpty(result?.NullTypedCollection); + } - } + /*============================================================================================================================ + | TEST: MAP: CONSTRUCTOR: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and attempts to map a view model with a constructor containing a + /// circular reference, and confirms that a is correctly thrown. + /// + [Fact] + public async Task Map_Constructor_ThrowsException() { - /*========================================================================================================================== - | TEST: MAP: CONSTRUCTOR: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and attempts to map a view model with a constructor containing a - /// circular reference, and confirms that a is correctly thrown. - /// - [Fact] - public async Task Map_Constructor_ThrowsException() { + var topic = new Topic("Topic", "Constructed", null, 1); + var related = new Topic("Related", "Constructed", null, 2); - var topic = new Topic("Topic", "Constructed", null, 1); - var related = new Topic("Related", "Constructed", null, 2); + topic.References.SetValue("TopicReference", related); + related.References.SetValue("TopicReference", topic); - topic.References.SetValue("TopicReference", related); - related.References.SetValue("TopicReference", topic); + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(topic).ConfigureAwait(false) + ); - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(topic).ConfigureAwait(false) - ).ConfigureAwait(false); + } - } + /*============================================================================================================================ + | TEST: MAP: DISABLED PROPERTY: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it maps a property decorated with the . + /// + [Fact] + public async Task Map_DisabledProperty_ReturnsNull() { - /*========================================================================================================================== - | TEST: MAP: DISABLED PROPERTY: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it maps a property decorated with the . - /// - [Fact] - public async Task Map_DisabledProperty_ReturnsNull() { + var topic = new Topic("Test", "DisableMapping"); - var topic = new Topic("Test", "DisableMapping"); + var viewModel = await _mappingService.MapAsync(topic); - var viewModel = await _mappingService.MapAsync(topic).ConfigureAwait(false); + Assert.NotNull(viewModel); + Assert.Null(viewModel?.Key); - Assert.NotNull(viewModel); - Assert.Null(viewModel?.Key); + } - } + /*============================================================================================================================ + | TEST: MAP: PARENTS: RETURNS ASCENDENTS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls the parent tree. + /// + [Fact] + public async Task Map_Parents_ReturnsAscendents() { - /*========================================================================================================================== - | TEST: MAP: PARENTS: RETURNS ASCENDENTS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls the parent tree. - /// - [Fact] - public async Task Map_Parents_ReturnsAscendents() { - - var grandParent = new Topic("Grandparent", "AscendentSpecialized"); - var parent = new Topic("Parent", "Ascendent", grandParent); - var topic = new Topic("Test", "Ascendent", parent); - - grandParent.Attributes.SetValue("IsRoot", "1"); - - var viewModel = await _mappingService.MapAsync(topic).ConfigureAwait(false); - var parentViewModel = viewModel?.Parent; - var grandParentViewModel = parentViewModel?.Parent as AscendentSpecializedTopicViewModel; - - Assert.NotNull(viewModel); - Assert.NotNull(parentViewModel); - Assert.NotNull(grandParentViewModel); - Assert.Equal("Test", viewModel?.Key); - Assert.Equal("Parent", parentViewModel?.Key); - Assert.Equal("Grandparent", grandParentViewModel?.Key); - Assert.True(grandParentViewModel?.IsRoot); - Assert.Null(grandParentViewModel?.Parent); + var grandParent = new Topic("Grandparent", "AscendentSpecialized"); + var parent = new Topic("Parent", "Ascendent", grandParent); + var topic = new Topic("Test", "Ascendent", parent); - } + grandParent.Attributes.SetValue("IsRoot", "1"); - /*========================================================================================================================== - | TEST: MAP: INHERIT ATTRIBUTE: INHERITS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully inherits values as specified by - /// . - /// - [Fact] - public async Task Map_InheritAttribute_InheritsValue() { + var viewModel = await _mappingService.MapAsync(topic); + var parentViewModel = viewModel?.Parent; + var grandParentViewModel = parentViewModel?.Parent as AscendentSpecializedTopicViewModel; - var grandParent = new Topic("Grandparent", "Page"); - var parent = new Topic("Parent", "Page", grandParent); - var topic = new Topic("Test", "InheritedProperty", parent); + Assert.NotNull(viewModel); + Assert.NotNull(parentViewModel); + Assert.NotNull(grandParentViewModel); + Assert.Equal("Test", viewModel?.Key); + Assert.Equal("Parent", parentViewModel?.Key); + Assert.Equal("Grandparent", grandParentViewModel?.Key); + Assert.True(grandParentViewModel?.IsRoot); + Assert.Null(grandParentViewModel?.Parent); - grandParent.Attributes.SetValue("Property", "ValueA"); - grandParent.Attributes.SetValue("InheritedProperty", "ValueB"); + } - var viewModel = await _mappingService.MapAsync(topic).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: INHERIT ATTRIBUTE: INHERITS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully inherits values as specified by + /// . + /// + [Fact] + public async Task Map_InheritAttribute_InheritsValue() { - Assert.Null(viewModel?.Property); - Assert.Equal("ValueB", viewModel?.InheritedProperty); + var grandParent = new Topic("Grandparent", "Page"); + var parent = new Topic("Parent", "Page", grandParent); + var topic = new Topic("Test", "InheritedProperty", parent); - } + grandParent.Attributes.SetValue("Property", "ValueA"); + grandParent.Attributes.SetValue("InheritedProperty", "ValueB"); - /*========================================================================================================================== - | TEST: MAP: NULLABLE PROPERTIES WITH INVALID VALUES: RETURNS NULL OR DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting nullable scalar values with invalid values with the - /// expectation that they will be returned as null. - /// - [Fact] - public async Task Map_NullablePropertiesWithInvalidValues_ReturnsNullOrDefault() { + var viewModel = await _mappingService.MapAsync(topic); - var topic = new Topic("Test", "Page"); + Assert.Null(viewModel?.Property); + Assert.Equal("ValueB", viewModel?.InheritedProperty); - topic.Attributes.SetValue("NullableInteger", "A"); - topic.Attributes.SetValue("NullableBoolean", "43"); - topic.Attributes.SetValue("NullableDateTime", "Hello World"); - topic.Attributes.SetValue("NullableUrl", "invalid://Web\\Path\\File!?@Query=String?"); + } - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: NULLABLE PROPERTIES WITH INVALID VALUES: RETURNS NULL OR DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting nullable scalar values with invalid values with the + /// expectation that they will be returned as null. + /// + [Fact] + public async Task Map_NullablePropertiesWithInvalidValues_ReturnsNullOrDefault() { - Assert.Null(target?.NullableInteger); - Assert.Null(target?.NullableBoolean); - Assert.Null(target?.NullableDateTime); - Assert.Null(target?.NullableUrl); + var topic = new Topic("Test", "Page"); - //The following should not be null since they map to non-nullable properties which will have default values - Assert.Equal(topic.Title, target?.Title); - Assert.Equal(topic.IsHidden, target?.IsHidden); - Assert.Equal(topic.LastModified, target?.LastModified); + topic.Attributes.SetValue("NullableInteger", "A"); + topic.Attributes.SetValue("NullableBoolean", "43"); + topic.Attributes.SetValue("NullableDateTime", "Hello World"); + topic.Attributes.SetValue("NullableUrl", "invalid://Web\\Path\\File!?@Query=String?"); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: NULLABLE PROPERTIES WITH VALID VALUES: RETURNS VALUES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests setting nullable scalar values with valid values with the - /// expectation that they will be mapped correctly. - /// - [Fact] - public async Task Map_NullablePropertiesWithInvalidValues_ReturnsValues() { - - var topic = new Topic("Test", "Page"); - - topic.Attributes.SetValue("NullableString", "Hello World."); - topic.Attributes.SetValue("NullableInteger", "43"); - topic.Attributes.SetValue("NullableDouble", "3.14159265359"); - topic.Attributes.SetValue("NullableBoolean", "tRuE"); - topic.Attributes.SetValue("NullableDateTime", "10/15/1976"); - topic.Attributes.SetValue("NullableUrl", "/Web/Path/File?Query=String"); - - topic.Attributes.SetValue("Title", "Hello World."); - topic.Attributes.SetValue("IsHidden", "true"); - topic.Attributes.SetValue("LastModified", "10/15/1976"); - - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - - Assert.Equal("Hello World.", target?.NullableString); - Assert.Equal(43, target?.NullableInteger); - Assert.Equal(3.14159265359, target?.NullableDouble); - Assert.Equal(true, target?.NullableBoolean); - Assert.Equal(new(1976, 10, 15), target?.NullableDateTime); - Assert.Equal(new("/Web/Path/File?Query=String", UriKind.RelativeOrAbsolute), target?.NullableUrl); - - Assert.Equal(topic.Title, target?.Title); - Assert.Equal(topic.IsHidden, target?.IsHidden); - Assert.Equal(topic.LastModified, target?.LastModified); + Assert.Null(target?.NullableInteger); + Assert.Null(target?.NullableBoolean); + Assert.Null(target?.NullableDateTime); + Assert.Null(target?.NullableUrl); - } + //The following should not be null since they map to non-nullable properties which will have default values + Assert.Equal(topic.Title, target?.Title); + Assert.Equal(topic.IsHidden, target?.IsHidden); + Assert.Equal(topic.LastModified, target?.LastModified); - /*========================================================================================================================== - | TEST: MAP: ALTERNATE ATTRIBUTE KEY: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully derives values from the key - /// specified by . - /// - [Fact] - public async Task Map_AlternateAttributeKey_ReturnsMappedModel() { + } - var topic = new Topic("Test", "PropertyAlias"); + /*============================================================================================================================ + | TEST: MAP: NULLABLE PROPERTIES WITH VALID VALUES: RETURNS VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests setting nullable scalar values with valid values with the + /// expectation that they will be mapped correctly. + /// + [Fact] + public async Task Map_NullablePropertiesWithInvalidValues_ReturnsValues() { - topic.Attributes.SetValue("Property", "ValueA"); - topic.Attributes.SetValue("PropertyAlias", "ValueB"); + var topic = new Topic("Test", "Page"); - var viewModel = await _mappingService.MapAsync(topic).ConfigureAwait(false); + topic.Attributes.SetValue("NullableString", "Hello World."); + topic.Attributes.SetValue("NullableInteger", "43"); + topic.Attributes.SetValue("NullableDouble", "3.14159265359"); + topic.Attributes.SetValue("NullableBoolean", "tRuE"); + topic.Attributes.SetValue("NullableDateTime", "10/15/1976"); + topic.Attributes.SetValue("NullableUrl", "/Web/Path/File?Query=String"); - Assert.Equal("ValueA", viewModel?.PropertyAlias); + topic.Attributes.SetValue("Title", "Hello World."); + topic.Attributes.SetValue("IsHidden", "true"); + topic.Attributes.SetValue("LastModified", "10/15/1976"); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE: TRY GET VALUE: RETURNS ENTRY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and then confirms that it is returned via . - /// - [Fact] - public void MappedTopicCache_TryGetValue_ReturnsEntry() { + Assert.Equal("Hello World.", target?.NullableString); + Assert.Equal(43, target?.NullableInteger); + Assert.Equal(3.14159265359, target?.NullableDouble); + Assert.Equal(true, target?.NullableBoolean); + Assert.Equal(new(1976, 10, 15), target?.NullableDateTime); + Assert.Equal(new("/Web/Path/File?Query=String", UriKind.RelativeOrAbsolute), target?.NullableUrl); - var cache = new MappedTopicCache(); - var topicId = 1; - var viewModel = new EmptyViewModel(); + Assert.Equal(topic.Title, target?.Title); + Assert.Equal(topic.IsHidden, target?.IsHidden); + Assert.Equal(topic.LastModified, target?.LastModified); - cache.Register(topicId, AssociationTypes.None, viewModel); + } - var isSuccess = cache.TryGetValue(topicId, viewModel.GetType(), out var result); + /*============================================================================================================================ + | TEST: MAP: ALTERNATE ATTRIBUTE KEY: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully derives values from the key + /// specified by . + /// + [Fact] + public async Task Map_AlternateAttributeKey_ReturnsMappedModel() { - Assert.True(isSuccess); - Assert.Equal(viewModel, result?.MappedTopic); + var topic = new Topic("Test", "PropertyAlias"); - } + topic.Attributes.SetValue("Property", "ValueA"); + topic.Attributes.SetValue("PropertyAlias", "ValueB"); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE: TRY GET VALUE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and then confirms that it is not returned via if the doesn't match. - /// - [Fact] - public void MappedTopicCache_TryGetValue_ReturnsNull() { + var viewModel = await _mappingService.MapAsync(topic); - var cache = new MappedTopicCache(); - var topicId = 1; + Assert.Equal("ValueA", viewModel?.PropertyAlias); - cache.Register(topicId, AssociationTypes.None, new EmptyViewModel()); + } - var isSuccess = cache.TryGetValue(topicId, typeof(TopicViewModel), out var result); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE: TRY GET VALUE: RETURNS ENTRY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and then confirms that it is returned via . + /// + [Fact] + public void MappedTopicCache_TryGetValue_ReturnsEntry() { - Assert.False(isSuccess); - Assert.Null(result); + var cache = new MappedTopicCache(); + var topicId = 1; + var viewModel = new EmptyViewModel(); - } + cache.Register(topicId, AssociationTypes.None, viewModel); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE: GET OR ADD: RETURNS EXISTING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and then confirms that the existing entry is returned when calling with duplicate parameters. - /// - [Fact] - public void MappedTopicCache_GetOrAdd_ReturnsExisting() { + var isSuccess = cache.TryGetValue(topicId, viewModel.GetType(), out var result); - var cache = new MappedTopicCache(); - var initialViewModel = new EmptyViewModel(); - var newViewModel = new EmptyViewModel(); + Assert.True(isSuccess); + Assert.Equal(viewModel, result?.MappedTopic); - cache.Register(1, AssociationTypes.None, initialViewModel); - cache.Register(1, AssociationTypes.None, newViewModel); + } - var isSuccess = cache.TryGetValue(1, newViewModel.GetType(), out var result); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE: TRY GET VALUE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and then confirms that it is not returned via if the doesn't match. + /// + [Fact] + public void MappedTopicCache_TryGetValue_ReturnsNull() { - Assert.True(isSuccess); - Assert.Equal(initialViewModel, result?.MappedTopic); + var cache = new MappedTopicCache(); + var topicId = 1; - } + cache.Register(topicId, AssociationTypes.None, new EmptyViewModel()); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE: GET OR ADD: NEW TOPIC: IS NOT CACHED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and then confirms that entries are not added when using doesn't add entries with . - /// - [Fact] - public void MappedTopicCache_GetOrAdd_NewTopic_IsNotCached() { + var isSuccess = cache.TryGetValue(topicId, typeof(TopicViewModel), out var result); - var cache = new MappedTopicCache(); + Assert.False(isSuccess); + Assert.Null(result); - cache.Register(-1, AssociationTypes.None, new EmptyViewModel()); + } - var isSuccess = cache.TryGetValue(-1, typeof(EmptyViewModel), out var result); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE: GET OR ADD: RETURNS EXISTING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and then confirms that the existing entry is returned when calling with duplicate parameters. + /// + [Fact] + public void MappedTopicCache_GetOrAdd_ReturnsExisting() { - Assert.False(isSuccess); - Assert.Null(result); + var cache = new MappedTopicCache(); + var initialViewModel = new EmptyViewModel(); + var newViewModel = new EmptyViewModel(); - } + cache.Register(1, AssociationTypes.None, initialViewModel); + cache.Register(1, AssociationTypes.None, newViewModel); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE: GET OR ADD: OBJECT: IS NOT CACHED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and then confirms that entries are not added when using doesn't add entries with view models of type . - /// - [Fact] - public void MappedTopicCache_GetOrAdd_IsNotCached() { + var isSuccess = cache.TryGetValue(1, newViewModel.GetType(), out var result); - var cache = new MappedTopicCache(); + Assert.True(isSuccess); + Assert.Equal(initialViewModel, result?.MappedTopic); - cache.Register(1, AssociationTypes.None, new object()); + } - var isSuccess = cache.TryGetValue(-1, typeof(object), out var result); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE: GET OR ADD: NEW TOPIC: IS NOT CACHED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and then confirms that entries are not added when using doesn't add entries with . + /// + [Fact] + public void MappedTopicCache_GetOrAdd_NewTopic_IsNotCached() { - Assert.False(isSuccess); - Assert.Null(result); - Assert.Null(result); + var cache = new MappedTopicCache(); - } + cache.Register(-1, AssociationTypes.None, new EmptyViewModel()); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE ENTRY: GET MISSING ASSOCIATIONS: RETURNS DIFFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a set of , and then confirms that - /// its correctly returns the missing - /// associations. - /// - [Fact] - public void MappedTopicCacheEntry_GetMissingAssociations_ReturnsDifference() { + var isSuccess = cache.TryGetValue(-1, typeof(EmptyViewModel), out var result); - var cacheEntry = new MappedTopicCacheEntry() { - Associations = AssociationTypes.Children | AssociationTypes.Parents - }; - var associations = AssociationTypes.Children | AssociationTypes.References; + Assert.False(isSuccess); + Assert.Null(result); - var difference = cacheEntry.GetMissingAssociations(associations); + } - cacheEntry.AddMissingAssociations(difference); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE: GET OR ADD: OBJECT: IS NOT CACHED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and then confirms that entries are not added when using doesn't add entries with view models of type . + /// + [Fact] + public void MappedTopicCache_GetOrAdd_IsNotCached() { - Assert.True(difference.HasFlag(AssociationTypes.References)); - Assert.False(difference.HasFlag(AssociationTypes.Children)); - Assert.False(difference.HasFlag(AssociationTypes.Parents)); + var cache = new MappedTopicCache(); - } + cache.Register(1, AssociationTypes.None, new object()); - /*========================================================================================================================== - | TEST: MAPPED TOPIC CACHE ENTRY: ADD MISSING ASSOCIATIONS: SETS UNION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a set of , and then confirms that - /// its correctly extends the missing - /// associations. - /// - [Fact] - public void MappedTopicCacheEntry_AddMissingAssociations_SetsUnion() { + var isSuccess = cache.TryGetValue(-1, typeof(object), out var result); - var cacheEntry = new MappedTopicCacheEntry() { - Associations = AssociationTypes.Children - }; - var associations = AssociationTypes.Children | AssociationTypes.Parents; + Assert.False(isSuccess); + Assert.Null(result); + Assert.Null(result); - cacheEntry.AddMissingAssociations(associations); + } - Assert.Equal(AssociationTypes.Children | AssociationTypes.Parents, cacheEntry.Associations); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE ENTRY: GET MISSING ASSOCIATIONS: RETURNS DIFFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a set of , and then confirms that + /// its correctly returns the missing + /// associations. + /// + [Fact] + public void MappedTopicCacheEntry_GetMissingAssociations_ReturnsDifference() { - } + var cacheEntry = new MappedTopicCacheEntry() { + Associations = AssociationTypes.Children | AssociationTypes.Parents + }; + var associations = AssociationTypes.Children | AssociationTypes.References; - /*========================================================================================================================== - | TEST: MAP: RELATIONSHIPS: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls the relationships. - /// - [Fact] - public async Task Map_Relationships_ReturnsMappedModel() { + var difference = cacheEntry.GetMissingAssociations(associations); - var relatedTopic1 = new Topic("Cousin1", "Relation"); - var relatedTopic2 = new Topic("Cousin2", "Relation"); - var relatedTopic3 = new Topic("Sibling", "Relation"); - var topic = new Topic("Test", "Relation"); + cacheEntry.AddMissingAssociations(difference); - topic.Relationships.SetValue("Cousins", relatedTopic1); - topic.Relationships.SetValue("Cousins", relatedTopic2); - topic.Relationships.SetValue("Siblings", relatedTopic3); + Assert.True(difference.HasFlag(AssociationTypes.References)); + Assert.False(difference.HasFlag(AssociationTypes.Children)); + Assert.False(difference.HasFlag(AssociationTypes.Parents)); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + } - Assert.Equal(2, target?.Cousins.Count); - Assert.NotNull(GetChildTopic(target?.Cousins, "Cousin1")); - Assert.NotNull(GetChildTopic(target?.Cousins, "Cousin2")); - Assert.Null(GetChildTopic(target?.Cousins, "Sibling")); + /*============================================================================================================================ + | TEST: MAPPED TOPIC CACHE ENTRY: ADD MISSING ASSOCIATIONS: SETS UNION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a set of , and then confirms that + /// its correctly extends the missing + /// associations. + /// + [Fact] + public void MappedTopicCacheEntry_AddMissingAssociations_SetsUnion() { - } + var cacheEntry = new MappedTopicCacheEntry() { + Associations = AssociationTypes.Children + }; + var associations = AssociationTypes.Children | AssociationTypes.Parents; - /*========================================================================================================================== - | TEST: MAP: RELATIONSHIPS: SKIPS DISABLED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully skips disabled. - /// - [Fact] - public async Task Map_Relationships_SkipsDisabled() { + cacheEntry.AddMissingAssociations(associations); - var relatedTopic1 = new Topic("Cousin1", "Relation"); - var relatedTopic2 = new Topic("Cousin2", "Relation"); - var topic = new Topic("Test", "Relation"); + Assert.Equal(AssociationTypes.Children | AssociationTypes.Parents, cacheEntry.Associations); - topic.Relationships.SetValue("Cousins", relatedTopic1); - topic.Relationships.SetValue("Cousins", relatedTopic2); + } - topic.IsDisabled = true; - relatedTopic2.IsDisabled = true; + /*============================================================================================================================ + | TEST: MAP: RELATIONSHIPS: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls the relationships. + /// + [Fact] + public async Task Map_Relationships_ReturnsMappedModel() { - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var relatedTopic1 = new Topic("Cousin1", "Relation"); + var relatedTopic2 = new Topic("Cousin2", "Relation"); + var relatedTopic3 = new Topic("Sibling", "Relation"); + var topic = new Topic("Test", "Relation"); - Assert.Single(target?.Cousins); - Assert.NotNull(GetChildTopic(target?.Cousins, "Cousin1")); - Assert.Null(GetChildTopic(target?.Cousins, "Cousin2")); + topic.Relationships.SetValue("Cousins", relatedTopic1); + topic.Relationships.SetValue("Cousins", relatedTopic2); + topic.Relationships.SetValue("Siblings", relatedTopic3); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: ALTERNATE RELATIONSHIP: RETURNS CORRECT RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully derives values from the key and - /// type specified by . - /// - /// - /// The uses to set the relationship key to AmbiguousRelationship and the to . AmbiguousRelationship refers to a relationship that is - /// both outgoing and incoming. It should be smart enough to a) look for the AmbigousRelationship instead of the - /// RelationshipAlias, and b) source from the collection. - /// - [Fact] - public async Task Map_AlternateRelationship_ReturnsCorrectRelationship() { - - var outgoingRelation = new Topic("OutgoingRelation", "KeyOnly"); - var incomingRelation = new Topic("IncomingRelation", "KeyOnly"); - var ambiguousRelation = new Topic("AmbiguousRelation", "KeyOnly"); - - var topic = new Topic("Test", "AmbiguousRelation"); - - //Set outgoing relationships - topic.Relationships.SetValue("RelationshipAlias", ambiguousRelation); - topic.Relationships.SetValue("AmbiguousRelationship", outgoingRelation); - - //Set incoming relationships - ambiguousRelation.Relationships.SetValue("RelationshipAlias", topic); - incomingRelation.Relationships.SetValue("AmbiguousRelationship", topic); - - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - - Assert.Single(target?.RelationshipAlias); - Assert.NotNull(GetChildTopic(target?.RelationshipAlias, "IncomingRelation")); + Assert.Equal(2, target?.Cousins.Count); + Assert.NotNull(GetChildTopic(target?.Cousins, "Cousin1")); + Assert.NotNull(GetChildTopic(target?.Cousins, "Cousin2")); + Assert.Null(GetChildTopic(target?.Cousins, "Sibling")); - } + } - /*========================================================================================================================== - | TEST: MAP: CUSTOM COLLECTION: RETURNS COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully derives values from a custom source - /// collection compatible with , where {T} is a , or derivative. - /// - [Fact] - public async Task Map_CustomCollection_ReturnsCollection() { + /*============================================================================================================================ + | TEST: MAP: RELATIONSHIPS: SKIPS DISABLED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully skips disabled. + /// + [Fact] + public async Task Map_Relationships_SkipsDisabled() { - var topic = (ContentTypeDescriptor?)_topicRepository.Load("Root:Configuration:ContentTypes:Page"); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var relatedTopic1 = new Topic("Cousin1", "Relation"); + var relatedTopic2 = new Topic("Cousin2", "Relation"); + var topic = new Topic("Test", "Relation"); - Assert.Equal(8, target?.AttributeDescriptors.Count); - Assert.Equal(2, target?.PermittedContentTypes.Count); + topic.Relationships.SetValue("Cousins", relatedTopic1); + topic.Relationships.SetValue("Cousins", relatedTopic2); - //Ensure custom collections are not recursively followed without instruction - Assert.NotEqual(topic, topic?.PermittedContentTypes.LastOrDefault()); - Assert.NotEmpty(topic?.PermittedContentTypes.LastOrDefault()?.PermittedContentTypes); - Assert.Empty(target?.PermittedContentTypes.LastOrDefault()?.PermittedContentTypes); + topic.IsDisabled = true; + relatedTopic2.IsDisabled = true; - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: NESTED TOPICS: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls the nested topics. - /// - [Fact] - public async Task Map_NestedTopics_ReturnsMappedModel() { + Assert.NotNull(target); + Assert.Single(target.Cousins); + Assert.NotNull(GetChildTopic(target.Cousins, "Cousin1")); + Assert.Null(GetChildTopic(target.Cousins, "Cousin2")); - var topic = new Topic("Test", "Nested"); - var topicList = new Topic("Categories", "List", topic); - _ = new Topic("ChildTopic", "KeyOnly", topic); - _ = new Topic("NestedTopic1", "KeyOnly", topicList); - _ = new Topic("NestedTopic2", "KeyOnly", topicList); + } - topicList.IsHidden = true; + /*============================================================================================================================ + | TEST: MAP: ALTERNATE RELATIONSHIP: RETURNS CORRECT RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully derives values from the key and + /// type specified by . + /// + /// + /// The uses to set the relationship key to AmbiguousRelationship and the to . AmbiguousRelationship refers to a relationship that is + /// both outgoing and incoming. It should be smart enough to a) look for the AmbigousRelationship instead of the + /// RelationshipAlias, and b) source from the collection. + /// + [Fact] + public async Task Map_AlternateRelationship_ReturnsCorrectRelationship() { - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var outgoingRelation = new Topic("OutgoingRelation", "KeyOnly"); + var incomingRelation = new Topic("IncomingRelation", "KeyOnly"); + var ambiguousRelation = new Topic("AmbiguousRelation", "KeyOnly"); - Assert.Equal(2, target?.Categories.Count); + var topic = new Topic("Test", "AmbiguousRelation"); - Assert.NotNull(GetChildTopic(target?.Categories, "NestedTopic1")); - Assert.NotNull(GetChildTopic(target?.Categories, "NestedTopic2")); - Assert.Null(GetChildTopic(target?.Categories, "Categories")); - Assert.Null(GetChildTopic(target?.Categories, "ChildTopic")); + //Set outgoing relationships + topic.Relationships.SetValue("RelationshipAlias", ambiguousRelation); + topic.Relationships.SetValue("AmbiguousRelationship", outgoingRelation); - } + //Set incoming relationships + ambiguousRelation.Relationships.SetValue("RelationshipAlias", topic); + incomingRelation.Relationships.SetValue("AmbiguousRelationship", topic); - /*========================================================================================================================== - | TEST: MAP: CHILDREN: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls child topics. - /// - [Fact] - public async Task Map_Children_ReturnsMappedModel() { - - var topic = new Topic("Test", "Descendent"); - _ = new Topic("ChildTopic1", "Descendent", topic); - _ = new Topic("ChildTopic2", "Descendent", topic); - var childTopic3 = new Topic("ChildTopic3", "Descendent", topic); - var childTopic4 = new Topic("ChildTopic4", "DescendentSpecialized", topic); - _ = new Topic("invalidChildTopic", "KeyOnly", topic); - _ = new Topic("GrandchildTopic", "Descendent", childTopic3); - - childTopic4.Attributes.SetBoolean("IsLeaf", true); - - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - - Assert.Equal(4, target?.Children.Count); - Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic1")); - Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic2")); - Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic3")); - Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic4")); - Assert.True(((DescendentSpecializedTopicViewModel?)GetChildTopic(target?.Children, "ChildTopic4"))?.IsLeaf); - Assert.Null(GetChildTopic(target?.Children, "invalidChildTopic")); - Assert.Null(GetChildTopic(target?.Children, "GrandchildTopic")); - Assert.NotNull(GetChildTopic( - ((DescendentTopicViewModel?)GetChildTopic(target?.Children, "ChildTopic3"))?.Children, - "GrandchildTopic" - )); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: WITH DISABLED: SKIPS DISABLED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with children and tests whether it successfully skips disabled child - /// topics. - /// - [Fact] - public async Task Map_Children_SkipsDisabled() { + Assert.NotNull(target); + Assert.Single(target.RelationshipAlias); + Assert.NotNull(GetChildTopic(target.RelationshipAlias, "IncomingRelation")); - var topic = new Topic("Test", "Descendent"); - _ = new Topic("ChildTopic1", "Descendent", topic); - _ = new Topic("ChildTopic2", "Descendent", topic); - var childTopic3 = new Topic("ChildTopic3", "Descendent", topic); + } - topic.IsDisabled = true; - childTopic3.IsDisabled = true; + /*============================================================================================================================ + | TEST: MAP: CUSTOM COLLECTION: RETURNS COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully derives values from a custom source + /// collection compatible with , where {T} is a , or derivative. + /// + [Fact] + public async Task Map_CustomCollection_ReturnsCollection() { - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var topic = (ContentTypeDescriptor?)_topicRepository.Load("Root:Configuration:ContentTypes:Page"); + var target = await _mappingService.MapAsync(topic); - Assert.Equal(2, target?.Children.Count); - Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic1")); - Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic2")); - Assert.Null(GetChildTopic(target?.Children, "ChildTopic3")); + Assert.NotNull(topic); + Assert.NotNull(target); + Assert.Equal(8, target.AttributeDescriptors.Count); + Assert.Equal(2, target.PermittedContentTypes.Count); - } + //Ensure custom collections are not recursively followed without instruction + var lastPermittedContentType = topic.PermittedContentTypes.LastOrDefault(); + var lastPermittedContentTypeViewModel = target.PermittedContentTypes.LastOrDefault(); - /*========================================================================================================================== - | TEST: MAP: MAP TO PARENT: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether the resulting object's nested complex objects are - /// property mapped with attribute values from the parent, based on their - /// configuration. - /// - [Fact] - public async Task Map_MapToParent_ReturnsMappedModel() { + Assert.NotNull(lastPermittedContentType); + Assert.NotNull(lastPermittedContentTypeViewModel); + Assert.NotEqual(topic, lastPermittedContentType); + Assert.NotEmpty(lastPermittedContentType.PermittedContentTypes); + Assert.Empty(lastPermittedContentTypeViewModel.PermittedContentTypes); - var topic = new Topic("Test", "FlattenChildren"); + } - topic.Attributes.SetValue("PrimaryKey", "Primary Key"); - topic.Attributes.SetValue("AlternateKey", "Alternate Key"); - topic.Attributes.SetValue("AncillaryKey", "Ancillary Key"); - topic.Attributes.SetValue("AliasedKey", "Aliased Key"); + /*============================================================================================================================ + | TEST: MAP: NESTED TOPICS: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls the nested topics. + /// + [Fact] + public async Task Map_NestedTopics_ReturnsMappedModel() { - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var topic = new Topic("Test", "Nested"); + var topicList = new Topic("Categories", "List", topic); + _ = new Topic("ChildTopic", "KeyOnly", topic); + _ = new Topic("NestedTopic1", "KeyOnly", topicList); + _ = new Topic("NestedTopic2", "KeyOnly", topicList); - Assert.Equal("Test", target?.Primary?.Key); - Assert.Equal("Aliased Key", target?.Alternate?.Key); - Assert.Equal("Ancillary Key", target?.Ancillary?.Key); + topicList.IsHidden = true; - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: MAP AS: RETURNS TOPIC REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully maps a topic reference using the - /// type specified in the . - /// - [Fact] - public async Task Map_MapAs_ReturnsTopicReference() { + Assert.Equal(2, target?.Categories.Count); - var topicReference = _topicRepository.Load(11111); + Assert.NotNull(GetChildTopic(target?.Categories, "NestedTopic1")); + Assert.NotNull(GetChildTopic(target?.Categories, "NestedTopic2")); + Assert.Null(GetChildTopic(target?.Categories, "Categories")); + Assert.Null(GetChildTopic(target?.Categories, "ChildTopic")); - Contract.Assume(topicReference); + } - var topic = new Topic("Test", "MapAs"); + /*============================================================================================================================ + | TEST: MAP: CHILDREN: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls child topics. + /// + [Fact] + public async Task Map_Children_ReturnsMappedModel() { + + var topic = new Topic("Test", "Descendent"); + _ = new Topic("ChildTopic1", "Descendent", topic); + _ = new Topic("ChildTopic2", "Descendent", topic); + var childTopic3 = new Topic("ChildTopic3", "Descendent", topic); + var childTopic4 = new Topic("ChildTopic4", "DescendentSpecialized", topic); + _ = new Topic("invalidChildTopic", "KeyOnly", topic); + _ = new Topic("GrandchildTopic", "Descendent", childTopic3); + + childTopic4.Attributes.SetBoolean("IsLeaf", true); + + var target = await _mappingService.MapAsync(topic); + + Assert.Equal(4, target?.Children.Count); + Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic1")); + Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic2")); + Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic3")); + Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic4")); + Assert.True(((DescendentSpecializedTopicViewModel?)GetChildTopic(target?.Children, "ChildTopic4"))?.IsLeaf); + Assert.Null(GetChildTopic(target?.Children, "invalidChildTopic")); + Assert.Null(GetChildTopic(target?.Children, "GrandchildTopic")); + Assert.NotNull(GetChildTopic( + ((DescendentTopicViewModel?)GetChildTopic(target?.Children, "ChildTopic3"))?.Children, + "GrandchildTopic" + )); + } - topic.References.SetValue("TopicReference", topicReference); + /*============================================================================================================================ + | TEST: MAP: WITH DISABLED: SKIPS DISABLED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with children and tests whether it successfully skips disabled child + /// topics. + /// + [Fact] + public async Task Map_Children_SkipsDisabled() { - var target = (MapAsTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + var topic = new Topic("Test", "Descendent"); + _ = new Topic("ChildTopic1", "Descendent", topic); + _ = new Topic("ChildTopic2", "Descendent", topic); + var childTopic3 = new Topic("ChildTopic3", "Descendent", topic); - Assert.NotNull(target?.TopicReference); - Assert.IsType(target?.TopicReference); + topic.IsDisabled = true; + childTopic3.IsDisabled = true; - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: MAP AS: RETURNS RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully maps a relationship collection using - /// the type specified in the . - /// - [Fact] - public async Task Map_MapAs_ReturnsRelationships() { + Assert.Equal(2, target?.Children.Count); + Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic1")); + Assert.NotNull(GetChildTopic(target?.Children, "ChildTopic2")); + Assert.Null(GetChildTopic(target?.Children, "ChildTopic3")); - var relatedTopic = _topicRepository.Load(11111); + } - Contract.Assume(relatedTopic); + /*============================================================================================================================ + | TEST: MAP: MAP TO PARENT: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether the resulting object's nested complex objects are + /// property mapped with attribute values from the parent, based on their + /// configuration. + /// + [Fact] + public async Task Map_MapToParent_ReturnsMappedModel() { - var topic = new Topic("Test", "MapAs"); + var topic = new Topic("Test", "FlattenChildren"); - topic.Relationships.SetValue("Relationships", relatedTopic); + topic.Attributes.SetValue("PrimaryKey", "Primary Key"); + topic.Attributes.SetValue("AlternateKey", "Alternate Key"); + topic.Attributes.SetValue("AncillaryKey", "Ancillary Key"); + topic.Attributes.SetValue("AliasedKey", "Aliased Key"); - var target = (MapAsTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + var target = await _mappingService.MapAsync(topic); - Assert.Single(target?.Relationships); - Assert.IsType(target?.Relationships.FirstOrDefault()); + Assert.Equal("Test", target?.Primary?.Key); + Assert.Equal("Aliased Key", target?.Alternate?.Key); + Assert.Equal("Ancillary Key", target?.Ancillary?.Key); - } + } - /*========================================================================================================================== - | TEST: MAP: TOPIC REFERENCES AS ATTRIBUTE: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully maps referenced topics stored in - /// . - /// - [Fact] - public async Task Map_TopicReferencesAsAttribute_ReturnsMappedModel() { + /*============================================================================================================================ + | TEST: MAP: MAP AS: RETURNS TOPIC REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully maps a topic reference using the + /// type specified in the . + /// + [Fact] + public async Task Map_MapAs_ReturnsTopicReference() { - var topicReference = _topicRepository.Load(11111); + var topicReference = _topicRepository.Load(11111); - Contract.Assume(topicReference); + Contract.Assume(topicReference); - var topic = new Topic("Test", "TopicReference"); + var topic = new Topic("Test", "MapAs"); - topic.Attributes.SetInteger("TopicReferenceId", topicReference.Id); + topic.References.SetValue("TopicReference", topicReference); - var target = (TopicReferenceTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + var target = (MapAsTopicViewModel?)await _mappingService.MapAsync(topic); - Assert.NotNull(target?.TopicReference); - Assert.Equal(topicReference.Key, target?.TopicReference?.Key); + Assert.NotNull(target?.TopicReference); + Assert.IsType(target?.TopicReference); - } + } - /*========================================================================================================================== - | TEST: MAP: TOPIC REFERENCES: RETURNS MAPPED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully maps referenced topics. - /// - [Fact] - public async Task Map_TopicReferences_ReturnsMappedModel() { + /*============================================================================================================================ + | TEST: MAP: MAP AS: RETURNS RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully maps a relationship collection using + /// the type specified in the . + /// + [Fact] + public async Task Map_MapAs_ReturnsRelationships() { - var topicReference = _topicRepository.Load(11111); + var relatedTopic = _topicRepository.Load(11111); - var topic = new Topic("Test", "TopicReference"); + Contract.Assume(relatedTopic); - topic.References.SetValue("TopicReference", topicReference); + var topic = new Topic("Test", "MapAs"); - var target = (TopicReferenceTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + topic.Relationships.SetValue("Relationships", relatedTopic); - Assert.NotNull(target?.TopicReference); - Assert.Equal(topicReference?.Key, target?.TopicReference?.Key); + var target = (MapAsTopicViewModel?)await _mappingService.MapAsync(topic); - } + Assert.NotNull(target); + Assert.Single(target.Relationships); + Assert.IsType(target.Relationships.FirstOrDefault()); - /*========================================================================================================================== - | TEST: MAP: TOPIC REFERENCES: SKIPS DISABLED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully skips disabled topics. - /// - [Fact] - public async Task Map_TopicReferences_SkipsDisabled() { + } - var topic = new Topic("Test", "TopicReference"); - var topicReference = new Topic("Reference", "Page") { - IsDisabled = true - }; + /*============================================================================================================================ + | TEST: MAP: TOPIC REFERENCES AS ATTRIBUTE: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully maps referenced topics stored in + /// . + /// + [Fact] + public async Task Map_TopicReferencesAsAttribute_ReturnsMappedModel() { - topic.References.SetValue("TopicReference", topicReference); + var topicReference = _topicRepository.Load(11111); - var target = (TopicReferenceTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + Contract.Assume(topicReference); - Assert.Null(target?.TopicReference); + var topic = new Topic("Test", "TopicReference"); - } + topic.Attributes.SetInteger("TopicReferenceId", topicReference.Id); - /*========================================================================================================================== - | TEST: MAP: RECURSIVE RELATIONSHIPS: RETURNS GRAPH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully follows relationships per the - /// instructions of each model class. - /// - [Fact] - public async Task Map_RecursiveRelationships_ReturnsGraph() { + var target = (TopicReferenceTopicViewModel?)await _mappingService.MapAsync(topic); - //Self - var topic = new Topic("Test", "Relation"); + Assert.NotNull(target?.TopicReference); + Assert.Equal(topicReference.Key, target?.TopicReference?.Key); - //First cousins - var cousinTopic1 = new Topic("CousinTopic1", "Relation"); - var cousinTopic2 = new Topic("CousinTopic2", "Relation"); - var cousinTopic3 = new Topic("CousinTopic3", "RelationWithChildren"); + } - //First cousins once removed - _ = new Topic("ChildTopic1", "RelationWithChildren", cousinTopic3); - _ = new Topic("ChildTopic2", "RelationWithChildren", cousinTopic3); - var childTopic3 = new Topic("ChildTopic3", "RelationWithChildren", cousinTopic3); + /*============================================================================================================================ + | TEST: MAP: TOPIC REFERENCES: RETURNS MAPPED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully maps referenced topics. + /// + [Fact] + public async Task Map_TopicReferences_ReturnsMappedModel() { - //Other cousins - var secondCousin = new Topic("SecondCousin", "Relation"); - _ = new Topic("CousinOnceRemoved", "Relation", childTopic3); + var topicReference = _topicRepository.Load(11111); - //Set first cousins - topic.Relationships.SetValue("Cousins", cousinTopic1); - topic.Relationships.SetValue("Cousins", cousinTopic2); - topic.Relationships.SetValue("Cousins", cousinTopic3); + var topic = new Topic("Test", "TopicReference"); - //Set ancillary relationships - cousinTopic3.Relationships.SetValue("Cousins", secondCousin); + topic.References.SetValue("TopicReference", topicReference); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var target = (TopicReferenceTopicViewModel?)await _mappingService.MapAsync(topic); - var cousinTarget = GetChildTopic(target?.Cousins, "CousinTopic3") as RelationWithChildrenTopicViewModel; - var distantCousinTarget = GetChildTopic(cousinTarget?.Children, "ChildTopic3") as RelationWithChildrenTopicViewModel; + Assert.NotNull(target?.TopicReference); + Assert.Equal(topicReference?.Key, target?.TopicReference?.Key); - //Because Cousins is set to recurse over Children, its children should be set - Assert.Equal(3, cousinTarget?.Children.Count); + } - //Because Cousins is not set to recurse over Cousins, its cousins should NOT be set (even though there is one cousin) - Assert.Empty(cousinTarget?.Cousins); + /*============================================================================================================================ + | TEST: MAP: TOPIC REFERENCES: SKIPS DISABLED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully skips disabled topics. + /// + [Fact] + public async Task Map_TopicReferences_SkipsDisabled() { - //Because Children is not set to recurse over Children, the grandchildren of a cousin should NOT be set - Assert.Empty(distantCousinTarget?.Children); + var topic = new Topic("Test", "TopicReference"); + var topicReference = new Topic("Reference", "Page") { + IsDisabled = true + }; - } + topic.References.SetValue("TopicReference", topicReference); - /*========================================================================================================================== - | TEST: MAP: SLIDE SHOW: RETURNS DERIVED VIEW MODELS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully crawls a , even though the list is a - /// collection of objects (from which . - /// - [Fact] - public async Task Map_Slideshow_ReturnsDerivedViewModels() { - - var topic = new Topic("Test", "Slideshow"); - var slides = new Topic("ContentItems", "List", topic); - _ = new Topic("ChildTopic1", "Slide", slides); - _ = new Topic("ChildTopic2", "Slide", slides); - _ = new Topic("ChildTopic3", "Slide", slides); - _ = new Topic("ChildTopic4", "ContentItem", slides); - - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - - Assert.Equal(4, target?.ContentItems.Count); - Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic1")); - Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic2")); - Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic3")); - Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic4")); + var target = (TopicReferenceTopicViewModel?)await _mappingService.MapAsync(topic); - } + Assert.Null(target?.TopicReference); - /*========================================================================================================================== - | TEST: MAP: TOPIC ENTITIES: RETURNS TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully includes - /// instances if called for by the model. This isn't a best practice, but is maintained for edge cases. - /// - [Fact] - public async Task Map_TopicEntities_ReturnsTopics() { + } - var relatedTopic1 = new Topic("RelatedTopic1", "KeyOnly"); - var relatedTopic2 = new Topic("RelatedTopic2", "KeyOnly"); - var relatedTopic3 = new Topic("RelatedTopic3", "KeyOnly"); - var topic = new Topic("Test", "RelatedEntity"); + /*============================================================================================================================ + | TEST: MAP: RECURSIVE RELATIONSHIPS: RETURNS GRAPH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully follows relationships per the + /// instructions of each model class. + /// + [Fact] + public async Task Map_RecursiveRelationships_ReturnsGraph() { - topic.Relationships.SetValue("RelatedTopics", relatedTopic1); - topic.Relationships.SetValue("RelatedTopics", relatedTopic2); - topic.Relationships.SetValue("RelatedTopics", relatedTopic3); + //Self + var topic = new Topic("Test", "Relation"); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - var relatedTopic3copy = (getRelatedTopic(target, "RelatedTopic3")); + //First cousins + var cousinTopic1 = new Topic("CousinTopic1", "Relation"); + var cousinTopic2 = new Topic("CousinTopic2", "Relation"); + var cousinTopic3 = new Topic("CousinTopic3", "RelationWithChildren"); - Assert.Equal(3, target?.RelatedTopics.Count); + //First cousins once removed + _ = new Topic("ChildTopic1", "RelationWithChildren", cousinTopic3); + _ = new Topic("ChildTopic2", "RelationWithChildren", cousinTopic3); + var childTopic3 = new Topic("ChildTopic3", "RelationWithChildren", cousinTopic3); - Assert.NotNull(getRelatedTopic(target, "RelatedTopic1")); - Assert.NotNull(getRelatedTopic(target, "RelatedTopic2")); - Assert.NotNull(getRelatedTopic(target, "RelatedTopic3")); + //Other cousins + var secondCousin = new Topic("SecondCousin", "Relation"); + _ = new Topic("CousinOnceRemoved", "Relation", childTopic3); - Assert.Equal(relatedTopic3.Key, relatedTopic3copy?.Key); + //Set first cousins + topic.Relationships.SetValue("Cousins", cousinTopic1); + topic.Relationships.SetValue("Cousins", cousinTopic2); + topic.Relationships.SetValue("Cousins", cousinTopic3); - Topic? getRelatedTopic(RelatedEntityTopicViewModel? topic, string key) - => topic?.RelatedTopics.FirstOrDefault((t) => t.Key.StartsWith(key, StringComparison.Ordinal)); + //Set ancillary relationships + cousinTopic3.Relationships.SetValue("Cousins", secondCousin); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: METADATA LOOKUP: RETURNS LOOKUP ITEMS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether is able to lookup metadata successfully using the - /// . - /// - [Fact] - public async Task Map_MetadataLookup_ReturnsLookupItems() { + var cousinTarget = GetChildTopic(target?.Cousins, "CousinTopic3") as RelationWithChildrenTopicViewModel; + var distantCousinTarget = GetChildTopic(cousinTarget?.Children, "ChildTopic3") as RelationWithChildrenTopicViewModel; - var topic = new Topic("Test", "MetadataLookup"); + Assert.NotNull(cousinTarget); + Assert.NotNull(distantCousinTarget); - var target = (MetadataLookupTopicViewModel?)await _mappingService.MapAsync(topic).ConfigureAwait(false); + //Because Cousins is set to recurse over Children, its children should be set + Assert.Equal(3, cousinTarget.Children.Count); - Assert.Equal(5, target?.Categories.Count); + //Because Cousins is not set to recurse over Cousins, its cousins should NOT be set (even though there is one cousin) + Assert.Empty(cousinTarget.Cousins); - } + //Because Children is not set to recurse over Children, the grandchildren of a cousin should NOT be set + Assert.Empty(distantCousinTarget.Children); - /*========================================================================================================================== - | TEST: MAP: CACHED TOPIC: RETURNS SAME REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and binds two properties to the same association, each with the same - /// [Include()] attribute. Ensures that the result of each property are the same, and only map the specified - /// association. - /// - [Fact] - public async Task Map_CachedTopic_ReturnsSameReference() { + } - var topic = new Topic("Test", "Redundant", null, 1); - var child = new Topic("ChildTopic", "RedundantItem", topic, 2); + /*============================================================================================================================ + | TEST: MAP: SLIDE SHOW: RETURNS DERIVED VIEW MODELS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully crawls a , even though the list is a + /// collection of objects (from which . + /// + [Fact] + public async Task Map_Slideshow_ReturnsDerivedViewModels() { - child.References.SetValue("Reference", topic); + var topic = new Topic("Test", "Slideshow"); + var slides = new Topic("ContentItems", "List", topic); + _ = new Topic("ChildTopic1", "Slide", slides); + _ = new Topic("ChildTopic2", "Slide", slides); + _ = new Topic("ChildTopic3", "Slide", slides); + _ = new Topic("ChildTopic4", "ContentItem", slides); - var mappedTopic = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var target = await _mappingService.MapAsync(topic); - Assert.Equal(mappedTopic?.FirstItem, mappedTopic?.SecondItem); - Assert.Equal(mappedTopic?.FirstItem?.Parent, mappedTopic?.SecondItem?.Parent); - Assert.Null(mappedTopic?.FirstItem?.Reference); - Assert.Null(mappedTopic?.SecondItem?.Reference); + Assert.Equal(4, target?.ContentItems.Count); + Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic1")); + Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic2")); + Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic3")); + Assert.NotNull(GetChildTopic(target?.ContentItems, "ChildTopic4")); - } + } - /*========================================================================================================================== - | TEST: MAP: CACHED TOPIC: RETURNS PROGRESSIVE REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and binds two properties to the same association, each with a - /// different [Include()] attribute. Ensures that the result of each property contains both assocations. - /// - [Fact] - public async Task Map_CachedTopic_ReturnsProgressiveReference() { + /*============================================================================================================================ + | TEST: MAP: TOPIC ENTITIES: RETURNS TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully includes + /// instances if called for by the model. This isn't a best practice, but is maintained for edge cases. + /// + [Fact] + public async Task Map_TopicEntities_ReturnsTopics() { - var topic = new Topic("Test", "Progressive", null, 1); - var child = new Topic("ChildTopic", "RedundantItem", topic, 2); + var relatedTopic1 = new Topic("RelatedTopic1", "KeyOnly"); + var relatedTopic2 = new Topic("RelatedTopic2", "KeyOnly"); + var relatedTopic3 = new Topic("RelatedTopic3", "KeyOnly"); + var topic = new Topic("Test", "RelatedEntity"); - child.References.SetValue("Reference", topic); + topic.Relationships.SetValue("RelatedTopics", relatedTopic1); + topic.Relationships.SetValue("RelatedTopics", relatedTopic2); + topic.Relationships.SetValue("RelatedTopics", relatedTopic3); - var mappedTopic = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var target = await _mappingService.MapAsync(topic); + var relatedTopic3copy = (getRelatedTopic(target, "RelatedTopic3")); - Assert.Equal(mappedTopic?.FirstItem, mappedTopic?.SecondItem); - Assert.Equal(mappedTopic?.FirstItem?.Parent, mappedTopic?.SecondItem?.Reference); + Assert.Equal(3, target?.RelatedTopics.Count); - } + Assert.NotNull(getRelatedTopic(target, "RelatedTopic1")); + Assert.NotNull(getRelatedTopic(target, "RelatedTopic2")); + Assert.NotNull(getRelatedTopic(target, "RelatedTopic3")); - /*========================================================================================================================== - | TEST: MAP: CIRCULAR REFERENCE: RETURNS MAPPED PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether it successfully handles a circular reference by - /// taking advantage of its internal caching mechanism. - /// - [Fact] - public async Task Map_CircularReference_ReturnsCachedParent() { + Assert.Equal(relatedTopic3.Key, relatedTopic3copy?.Key); - var topic = new Topic("Test", "Circular", null, 1); - _ = new Topic("ChildTopic", "Circular", topic, 2); + Topic? getRelatedTopic(RelatedEntityTopicViewModel? topic, string key) + => topic?.RelatedTopics.FirstOrDefault((t) => t.Key.StartsWith(key, StringComparison.Ordinal)); - var mappedTopic = await _mappingService.MapAsync(topic).ConfigureAwait(false); + } - Assert.Equal(mappedTopic, mappedTopic?.Children.First().Parent); + /*============================================================================================================================ + | TEST: MAP: METADATA LOOKUP: RETURNS LOOKUP ITEMS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether is able to lookup metadata successfully using the + /// . + /// + [Fact] + public async Task Map_MetadataLookup_ReturnsLookupItems() { - } + var topic = new Topic("Test", "MetadataLookup"); - /*========================================================================================================================== - | TEST: MAP: FILTER BY COLLECTION TYPE: RETURNS FILTERED COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether the resulting object's property can be filtered by . - /// - [Fact] - public async Task Map_FilterByCollectionType_ReturnsFilteredCollection() { + var target = (MetadataLookupTopicViewModel?)await _mappingService.MapAsync(topic); - var topic = new Topic("Test", "Descendent"); - _ = new Topic("ChildTopic1", "Descendent", topic); - _ = new Topic("ChildTopic2", "DescendentSpecialized", topic); - var childTopic3 = new Topic("ChildTopic3", "DescendentSpecialized", topic); - _ = new Topic("ChildTopic4", "DescendentSpecialized", childTopic3); + Assert.Equal(5, target?.Categories.Count); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + } - var specialized = target?.Children.GetByContentType("DescendentSpecialized"); + /*============================================================================================================================ + | TEST: MAP: CACHED TOPIC: RETURNS SAME REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and binds two properties to the same association, each with the same + /// [Include()] attribute. Ensures that the result of each property are the same, and only map the specified + /// association. + /// + [Fact] + public async Task Map_CachedTopic_ReturnsSameReference() { - Assert.Equal(2, specialized?.Count); - Assert.NotNull(GetChildTopic(specialized, "ChildTopic2")); - Assert.NotNull(GetChildTopic(specialized, "ChildTopic3")); - Assert.Null(GetChildTopic(specialized, "ChildTopic4")); + var topic = new Topic("Test", "Redundant", null, 1); + var child = new Topic("ChildTopic", "RedundantItem", topic, 2); - } + child.References.SetValue("Reference", topic); - /*========================================================================================================================== - | TEST: MAP: GETTER METHODS: MAP METHOD OUTPUT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a property corresponding to a getter method on to ensure that it is - /// correctly populated. - /// - [Fact] - public async Task Map_GetterMethods_MapMethodOutput() { + var mappedTopic = await _mappingService.MapAsync(topic); - var topic = new Topic("Topic", "Sample"); - var childTopic = new Topic("Child", "Page", topic); - var grandChildTopic = new Topic("GrandChild", "Index", childTopic); + Assert.Equal(mappedTopic?.FirstItem, mappedTopic?.SecondItem); + Assert.Equal(mappedTopic?.FirstItem?.Parent, mappedTopic?.SecondItem?.Parent); + Assert.Null(mappedTopic?.FirstItem?.Reference); + Assert.Null(mappedTopic?.SecondItem?.Reference); - var target = await _mappingService.MapAsync(grandChildTopic).ConfigureAwait(false); + } - Assert.Equal("Topic:Child:GrandChild", target?.UniqueKey); + /*============================================================================================================================ + | TEST: MAP: CACHED TOPIC: RETURNS PROGRESSIVE REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and binds two properties to the same association, each with a + /// different [Include()] attribute. Ensures that the result of each property contains both assocations. + /// + [Fact] + public async Task Map_CachedTopic_ReturnsProgressiveReference() { - } + var topic = new Topic("Test", "Progressive", null, 1); + var child = new Topic("ChildTopic", "RedundantItem", topic, 2); - /*========================================================================================================================== - | TEST: MAP: COMPATIBLE PROPERTIES: MAP OBJECT REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps two properties with compatible types without attempting a conversion. This can be used for mapping types that are - /// appropriate for the target view model, such as enums. - /// - [Fact] - public async Task Map_CompatibleProperties_MapObjectReference() { + child.References.SetValue("Reference", topic); - var topic = new TextAttributeDescriptor("Attribute", "TextAttributeDescriptor"); + var mappedTopic = await _mappingService.MapAsync(topic); - topic.VersionHistory.Add(new(1976, 10, 15, 9, 30, 00)); + Assert.Equal(mappedTopic?.FirstItem, mappedTopic?.SecondItem); + Assert.Equal(mappedTopic?.FirstItem?.Parent, mappedTopic?.SecondItem?.Reference); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + } - Assert.Equal(topic.ModelType, target?.ModelType); - Assert.Single(target?.VersionHistory); + /*============================================================================================================================ + | TEST: MAP: CIRCULAR REFERENCE: RETURNS MAPPED PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether it successfully handles a circular reference by + /// taking advantage of its internal caching mechanism. + /// + [Fact] + public async Task Map_CircularReference_ReturnsCachedParent() { - } + var topic = new Topic("Test", "Circular", null, 1); + _ = new Topic("ChildTopic", "Circular", topic, 2); - /*========================================================================================================================== - | TEST: MAP: VALID REQUIRED PROPERTY: IS MAPPED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a required property. Ensures that an error is not thrown if it is set. - /// - [Fact] - public async Task Map_ValidRequiredProperty_IsMapped() { + var mappedTopic = await _mappingService.MapAsync(topic); - var topic = new Topic("Topic", "Required"); + Assert.Equal(mappedTopic, mappedTopic?.Children.First().Parent); - topic.Attributes.SetValue("RequiredAttribute", "Required"); + } - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + /*============================================================================================================================ + | TEST: MAP: FILTER BY COLLECTION TYPE: RETURNS FILTERED COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether the resulting object's property can be filtered by . + /// + [Fact] + public async Task Map_FilterByCollectionType_ReturnsFilteredCollection() { - Assert.Equal("Required", target?.RequiredAttribute); + var topic = new Topic("Test", "Descendent"); + _ = new Topic("ChildTopic1", "Descendent", topic); + _ = new Topic("ChildTopic2", "DescendentSpecialized", topic); + var childTopic3 = new Topic("ChildTopic3", "DescendentSpecialized", topic); + _ = new Topic("ChildTopic4", "DescendentSpecialized", childTopic3); - } + var target = await _mappingService.MapAsync(topic); - /*========================================================================================================================== - | TEST: MAP: INVALID REQUIRED PROPERTY: THROWS VALIDATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a required property. Ensures that an error is thrown if it isn't set. - /// - [Fact] - public async Task Map_InvalidRequiredProperty_ThrowsValidationException() { + var specialized = target?.Children.GetByContentType("DescendentSpecialized"); - var topic = new Topic("Topic", "Required"); + Assert.Equal(2, specialized?.Count); + Assert.NotNull(GetChildTopic(specialized, "ChildTopic2")); + Assert.NotNull(GetChildTopic(specialized, "ChildTopic3")); + Assert.Null(GetChildTopic(specialized, "ChildTopic4")); - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(topic).ConfigureAwait(false) - ).ConfigureAwait(false); + } - } + /*============================================================================================================================ + | TEST: MAP: GETTER METHODS: MAP METHOD OUTPUT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a property corresponding to a getter method on to ensure that it is + /// correctly populated. + /// + [Fact] + public async Task Map_GetterMethods_MapMethodOutput() { - /*========================================================================================================================== - | TEST: MAP: INVALID REQUIRED OBJECT: THROWS VALIDATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has a required property. Ensures that an error is thrown if it isn't set. - /// - [Fact] - public async Task Map_InvalidRequiredObject_ThrowsValidationException() { + var topic = new Topic("Topic", "Sample"); + var childTopic = new Topic("Child", "Page", topic); + var grandChildTopic = new Topic("GrandChild", "Index", childTopic); - var topic = new Topic("Topic", "RequiredObject"); + var target = await _mappingService.MapAsync(grandChildTopic); - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(topic).ConfigureAwait(false) - ).ConfigureAwait(false); + Assert.Equal("Topic:Child:GrandChild", target?.UniqueKey); - } + } - /*========================================================================================================================== - | TEST: MAP: NULL PROPERTY: MAPS DEFAULT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has default properties. Ensures that each is set appropriately. - /// - [Fact] - public async Task Map_NullProperty_MapsDefaultValue() { + /*============================================================================================================================ + | TEST: MAP: COMPATIBLE PROPERTIES: MAP OBJECT REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps two properties with compatible types without attempting a conversion. This can be used for mapping types that are + /// appropriate for the target view model, such as enums. + /// + [Fact] + public async Task Map_CompatibleProperties_MapObjectReference() { - var topic = new Topic("Topic", "DefaultValue"); + var topic = new TextAttributeDescriptor("Attribute", "TextAttributeDescriptor"); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + topic.VersionHistory.Add(new(1976, 10, 15, 9, 30, 00)); - Assert.Equal("Default", target?.DefaultString); - Assert.Equal(10, target?.DefaultInt); - Assert.True(target?.DefaultBool); + var target = await _mappingService.MapAsync(topic); - } + Assert.NotNull(target); + Assert.NotNull(target.VersionHistory); + Assert.Equal(topic.ModelType, target.ModelType); + Assert.Single(target.VersionHistory); - /*========================================================================================================================== - | TEST: MAP: EMPTY ATTRIBUTE: RETAINS INITIAL VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a model that has initialized properties. Ensures that those are retained if the source values are empty. - /// - [Fact] - public async Task Map_EmptyAttribute_RetainsInitialValue() { + } - var topic = new Topic("Topic", "Initialized"); + /*============================================================================================================================ + | TEST: MAP: VALID REQUIRED PROPERTY: IS MAPPED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a required property. Ensures that an error is not thrown if it is set. + /// + [Fact] + public async Task Map_ValidRequiredProperty_IsMapped() { - topic.Attributes.SetValue("InitializedValue", "Initial Value"); - topic.Attributes.SetValue("InitializedValue", ""); + var topic = new Topic("Topic", "Required"); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + topic.Attributes.SetValue("RequiredAttribute", "Required"); - Assert.Equal("Original Value", target?.InitializedValue); + var target = await _mappingService.MapAsync(topic); - } + Assert.Equal("Required", target?.RequiredAttribute); - /*========================================================================================================================== - | TEST: MAP: EXCEEDS MINIMUM VALUE: THROWS VALIDATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Maps a content type that has minimum value properties. Ensures that an error is thrown if the minimum is not met. - /// - [Fact] - public async Task Map_ExceedsMinimumValue_ThrowsValidationException() { + } - var topic = new Topic("Topic", "MinimumLengthProperty"); + /*============================================================================================================================ + | TEST: MAP: INVALID REQUIRED PROPERTY: THROWS VALIDATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a required property. Ensures that an error is thrown if it isn't set. + /// + [Fact] + public async Task Map_InvalidRequiredProperty_ThrowsValidationException() { - topic.Attributes.SetValue("MinimumLength", "Hello World"); + var topic = new Topic("Topic", "Required"); - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(topic).ConfigureAwait(false) - ).ConfigureAwait(false); + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(topic).ConfigureAwait(false) + ); - } + } - /*========================================================================================================================== - | TEST: MAP: FILTER BY ATTRIBUTE: RETURNS FILTERED COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether the resulting object's property can be filtered using stacked - /// instances. - /// - [Fact] - public async Task Map_FilterByAttribute_ReturnsFilteredCollection() { + /*============================================================================================================================ + | TEST: MAP: INVALID REQUIRED OBJECT: THROWS VALIDATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has a required property. Ensures that an error is thrown if it isn't set. + /// + [Fact] + public async Task Map_InvalidRequiredObject_ThrowsValidationException() { - var topic = new Topic("Test", "Filtered"); - var childTopic1 = new Topic("ChildTopic1", "Page", topic); - var childTopic2 = new Topic("ChildTopic2", "Index", topic); - var childTopic3 = new Topic("ChildTopic3", "Page", topic); - var childTopic4 = new Topic("ChildTopic4", "Page", childTopic3); + var topic = new Topic("Topic", "RequiredObject"); - childTopic1.Attributes.SetValue("SomeAttribute", "ValueA"); - childTopic2.Attributes.SetValue("SomeAttribute", "ValueA"); - childTopic3.Attributes.SetValue("SomeAttribute", "ValueA"); - childTopic4.Attributes.SetValue("SomeAttribute", "ValueA"); + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(topic).ConfigureAwait(false) + ); - childTopic1.Attributes.SetValue("SomeOtherAttribute", "ValueB"); - childTopic2.Attributes.SetValue("SomeOtherAttribute", "ValueB"); - childTopic3.Attributes.SetValue("SomeOtherAttribute", "ValueA"); - childTopic4.Attributes.SetValue("SomeOtherAttribute", "ValueA"); + } + /*============================================================================================================================ + | TEST: MAP: NULL PROPERTY: MAPS DEFAULT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has default properties. Ensures that each is set appropriately. + /// + [Fact] + public async Task Map_NullProperty_MapsDefaultValue() { - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + var topic = new Topic("Topic", "DefaultValue"); - Assert.Equal(2, target?.Children.Count); + var target = await _mappingService.MapAsync(topic); - } + Assert.Equal("Default", target?.DefaultString); + Assert.Equal(10, target?.DefaultInt); + Assert.True(target?.DefaultBool); - /*========================================================================================================================== - | TEST: MAP: FILTER BY INVALID ATTRIBUTE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to map a view model that has an invalid value of ContentType - /// ; throws an . - /// - [Fact] - public async Task Map_FilterByInvalidAttribute_ThrowsExceptions() { + } - var topic = new Topic("Test", "FilteredInvalid"); + /*============================================================================================================================ + | TEST: MAP: EMPTY ATTRIBUTE: RETAINS INITIAL VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a model that has initialized properties. Ensures that those are retained if the source values are empty. + /// + [Fact] + public async Task Map_EmptyAttribute_RetainsInitialValue() { - await Assert.ThrowsAsync(async () => - await _mappingService.MapAsync(topic).ConfigureAwait(false) - ).ConfigureAwait(false); + var topic = new Topic("Topic", "Initialized"); - } + topic.Attributes.SetValue("InitializedValue", "Initial Value"); + topic.Attributes.SetValue("InitializedValue", ""); - /*========================================================================================================================== - | TEST: MAP: FILTER BY CONTENT TYPE: RETURNS FILTERED COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether the resulting object's property can be filtered using a - /// instances. - /// - [Fact] - public async Task Map_FilterByContentType_ReturnsFilteredCollection() { + var target = await _mappingService.MapAsync(topic); - var topic = new Topic("Test", "Filtered"); - _ = new Topic("ChildTopic1", "Page", topic); - _ = new Topic("ChildTopic2", "Index", topic); - var childTopic3 = new Topic("ChildTopic3", "Page", topic); - _ = new Topic("ChildTopic4", "Page", childTopic3); + Assert.Equal("Original Value", target?.InitializedValue); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + } - Assert.Equal(2, target?.Children.Count); + /*============================================================================================================================ + | TEST: MAP: EXCEEDS MINIMUM VALUE: THROWS VALIDATION EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Maps a content type that has minimum value properties. Ensures that an error is thrown if the minimum is not met. + /// + [Fact] + public async Task Map_ExceedsMinimumValue_ThrowsValidationException() { - } + var topic = new Topic("Topic", "MinimumLengthProperty"); - /*========================================================================================================================== - | TEST: MAP: FLATTEN ATTRIBUTE: RETURNS FLAT COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether the resulting object's property is properly flattened. - /// - [Fact] - public async Task Map_FlattenAttribute_ReturnsFlatCollection() { - - var topic = new Topic("Test", "FlattenChildren"); - - for (var i = 0; i < 5; i++) { - var childTopic = new Topic("Child" + i, "Page", topic); - for (var j = 0; j < 5; j++) { - _ = new Topic("GrandChild" + i + j, "FlattenChildren", childTopic); - } - } + topic.Attributes.SetValue("MinimumLength", "Hello World"); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(topic).ConfigureAwait(false) + ); - Assert.Equal(25, target?.Children.Count); + } - } + /*============================================================================================================================ + | TEST: MAP: FILTER BY ATTRIBUTE: RETURNS FILTERED COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether the resulting object's property can be filtered using stacked + /// instances. + /// + [Fact] + public async Task Map_FilterByAttribute_ReturnsFilteredCollection() { - /*========================================================================================================================== - | TEST: MAP: FLATTEN ATTRIBUTE: EXCLUDE TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and tests whether the resulting object's property excludes any or nested topics. - /// - [Fact] - public async Task Map_FlattenAttribute_ExcludeTopics() { + var topic = new Topic("Test", "Filtered"); + var childTopic1 = new Topic("ChildTopic1", "Page", topic); + var childTopic2 = new Topic("ChildTopic2", "Index", topic); + var childTopic3 = new Topic("ChildTopic3", "Page", topic); + var childTopic4 = new Topic("ChildTopic4", "Page", childTopic3); - var topic = new Topic("Test", "FlattenChildren"); - var childTopic = new Topic("Child", "FlattenChildren", topic); - var grandChildTopic = new Topic("Grandchild", "FlattenChildren", childTopic); - var listTopic = new Topic("List", "List", childTopic); - _ = new Topic("Nested", "FlattenChildren", listTopic); + childTopic1.Attributes.SetValue("SomeAttribute", "ValueA"); + childTopic2.Attributes.SetValue("SomeAttribute", "ValueA"); + childTopic3.Attributes.SetValue("SomeAttribute", "ValueA"); + childTopic4.Attributes.SetValue("SomeAttribute", "ValueA"); - grandChildTopic.IsDisabled = true; + childTopic1.Attributes.SetValue("SomeOtherAttribute", "ValueB"); + childTopic2.Attributes.SetValue("SomeOtherAttribute", "ValueB"); + childTopic3.Attributes.SetValue("SomeOtherAttribute", "ValueA"); + childTopic4.Attributes.SetValue("SomeOtherAttribute", "ValueA"); - var target = await _mappingService.MapAsync(topic).ConfigureAwait(false); - Assert.Single(target?.Children); + var target = await _mappingService.MapAsync(topic); - } + Assert.Equal(2, target?.Children.Count); - /*========================================================================================================================== - | TEST: MAP: CACHED TOPIC: RETURNS CACHED MODEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a as well as a and ensures that - /// the same instance of a mapped object is returned after two calls. - /// - [Fact] - public async Task Map_CachedTopic_ReturnsCachedModel() { + } - var cachedMappingService = new CachedTopicMappingService(_mappingService); + /*============================================================================================================================ + | TEST: MAP: FILTER BY INVALID ATTRIBUTE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to map a view model that has an invalid value of ContentType + /// ; throws an . + /// + [Fact] + public async Task Map_FilterByInvalidAttribute_ThrowsExceptions() { - var topic = new Topic("Test", "Filtered", null, 5); + var topic = new Topic("Test", "FilteredInvalid"); - var target1 = (FilteredTopicViewModel?)await cachedMappingService.MapAsync(topic).ConfigureAwait(false); - var target2 = (FilteredTopicViewModel?)await cachedMappingService.MapAsync(topic).ConfigureAwait(false); + await Assert.ThrowsAsync(async () => + await _mappingService.MapAsync(topic).ConfigureAwait(false) + ); - Assert.Equal(target1, target2); + } - } + /*============================================================================================================================ + | TEST: MAP: FILTER BY CONTENT TYPE: RETURNS FILTERED COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether the resulting object's property can be filtered using a + /// instances. + /// + [Fact] + public async Task Map_FilterByContentType_ReturnsFilteredCollection() { - /*========================================================================================================================== - | TEST: MAP: CACHED TOPIC: RETURNS UNIQUE REFERENCE PER TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a as well as a and ensures that - /// a different instance of a mapped object is returned after two calls, assuming the types are different. - /// - [Fact] - public async Task Map_CachedTopic_ReturnsUniqueReferencePerType() { + var topic = new Topic("Test", "Filtered"); + _ = new Topic("ChildTopic1", "Page", topic); + _ = new Topic("ChildTopic2", "Index", topic); + var childTopic3 = new Topic("ChildTopic3", "Page", topic); + _ = new Topic("ChildTopic4", "Page", childTopic3); - var cachedMappingService = new CachedTopicMappingService(_mappingService); + var target = await _mappingService.MapAsync(topic); - var topic = new Topic("Test", "Filtered", null, 5); + Assert.Equal(2, target?.Children.Count); - var target1 = await cachedMappingService.MapAsync(topic).ConfigureAwait(false); - var target2 = await cachedMappingService.MapAsync(topic).ConfigureAwait(false); - var target3 = (TopicViewModel?)await cachedMappingService.MapAsync(topic).ConfigureAwait(false); + } - Assert.Equal(target1, target2); - Assert.NotEqual(target1, target3); + /*============================================================================================================================ + | TEST: MAP: FLATTEN ATTRIBUTE: RETURNS FLAT COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether the resulting object's property is properly flattened. + /// + [Fact] + public async Task Map_FlattenAttribute_ReturnsFlatCollection() { + + var topic = new Topic("Test", "FlattenChildren"); + for (var i = 0; i < 5; i++) { + var childTopic = new Topic("Child" + i, "Page", topic); + for (var j = 0; j < 5; j++) { + _ = new Topic("GrandChild" + i + j, "FlattenChildren", childTopic); + } } - /*========================================================================================================================== - | METHOD: GET CHILD TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A helper function which retrieves a child topic based on the key. - /// - public static KeyOnlyTopicViewModel? GetChildTopic(IEnumerable? topicCollection, string key) - => topicCollection?.FirstOrDefault((t) => t.Key?.StartsWith(key, StringComparison.Ordinal)?? false); + var target = await _mappingService.MapAsync(topic); + + Assert.Equal(25, target?.Children.Count); + + } + + /*============================================================================================================================ + | TEST: MAP: FLATTEN ATTRIBUTE: EXCLUDE TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and tests whether the resulting object's property excludes any or nested topics. + /// + [Fact] + public async Task Map_FlattenAttribute_ExcludeTopics() { + + var topic = new Topic("Test", "FlattenChildren"); + var childTopic = new Topic("Child", "FlattenChildren", topic); + var grandChildTopic = new Topic("Grandchild", "FlattenChildren", childTopic); + var listTopic = new Topic("List", "List", childTopic); + _ = new Topic("Nested", "FlattenChildren", listTopic); + + grandChildTopic.IsDisabled = true; + + var target = await _mappingService.MapAsync(topic); + + Assert.NotNull(target); + Assert.Single(target.Children); + + } + + /*============================================================================================================================ + | TEST: MAP: CACHED TOPIC: RETURNS CACHED MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a as well as a and ensures that + /// the same instance of a mapped object is returned after two calls. + /// + [Fact] + public async Task Map_CachedTopic_ReturnsCachedModel() { + + var cachedMappingService = new CachedTopicMappingService(_mappingService); + + var topic = new Topic("Test", "Filtered", null, 5); + + var target1 = (FilteredTopicViewModel?)await cachedMappingService.MapAsync(topic); + var target2 = (FilteredTopicViewModel?)await cachedMappingService.MapAsync(topic); + + Assert.Equal(target1, target2); + + } + + /*============================================================================================================================ + | TEST: MAP: CACHED TOPIC: RETURNS UNIQUE REFERENCE PER TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a as well as a and ensures that + /// a different instance of a mapped object is returned after two calls, assuming the types are different. + /// + [Fact] + public async Task Map_CachedTopic_ReturnsUniqueReferencePerType() { + + var cachedMappingService = new CachedTopicMappingService(_mappingService); + + var topic = new Topic("Test", "Filtered", null, 5); + + var target1 = await cachedMappingService.MapAsync(topic); + var target2 = await cachedMappingService.MapAsync(topic); + var target3 = (TopicViewModel?)await cachedMappingService.MapAsync(topic); + + Assert.Equal(target1, target2); + Assert.NotEqual(target1, target3); + + } + + /*============================================================================================================================ + | METHOD: GET CHILD TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A helper function which retrieves a child topic based on the key. + /// + public static KeyOnlyTopicViewModel? GetChildTopic(IEnumerable? topicCollection, string key) + => topicCollection?.FirstOrDefault((t) => t.Key?.StartsWith(key, StringComparison.Ordinal)?? false); - public static TopicViewModel? GetChildTopic(IEnumerable? topicCollection, string key) - => topicCollection?.FirstOrDefault((t) => t.Key.StartsWith(key, StringComparison.Ordinal)); + public static TopicViewModel? GetChildTopic(IEnumerable? topicCollection, string key) + => topicCollection?.FirstOrDefault((t) => t.Key.StartsWith(key, StringComparison.Ordinal)); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TopicQueryingTest.cs b/OnTopic.Tests/TopicQueryingTest.cs index b2492196..bd139e30 100644 --- a/OnTopic.Tests/TopicQueryingTest.cs +++ b/OnTopic.Tests/TopicQueryingTest.cs @@ -12,344 +12,343 @@ using OnTopic.Tests.Fixtures; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC QUERYING TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +[Xunit.Collection("Shared Repository")] +public class TopicQueryingTest { /*============================================================================================================================ - | CLASS: TOPIC QUERYING TEST + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - [Xunit.Collection("Shared Repository")] - public class TopicQueryingTest { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. + /// + public TopicQueryingTest(TopicInfrastructureFixture fixture) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; + Contract.Requires(fixture, nameof(fixture)); - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. - /// - public TopicQueryingTest(TopicInfrastructureFixture fixture) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(fixture, nameof(fixture)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = fixture.CachedTopicRepository; - - } - - /*========================================================================================================================== - | TEST: FIND ALL BY ATTRIBUTE: RETURNS CORRECT TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Looks for a deeply nested child topic using only the attribute value. - /// - [Fact] - public void FindAllByAttribute_ReturnsCorrectTopics() { - - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); - var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); - var grandNieceTopic = new Topic("GrandNieceTopic", "Page", childTopic, 3); - var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); - - grandChildTopic.Attributes.SetValue("Foo", "Baz"); - grandNieceTopic.Attributes.SetValue("Foo", "Bar"); - greatGrandChildTopic.Attributes.SetValue("Foo", "Bar"); - - Assert.Equal(greatGrandChildTopic, parentTopic.FindAllByAttribute("Foo", "Bar").First()); - Assert.Equal(2, parentTopic.FindAllByAttribute("Foo", "Bar").Count); - Assert.Equal(grandChildTopic, parentTopic.FindAllByAttribute("Foo", "Baz").First()); - - } - - /*========================================================================================================================== - | TEST: FIND FIRST PARENT: RETURNS CORRECT TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a deeply nested , returns the first parent which satisfies a delegate. - /// - [Fact] - public void FindFirstParent_ReturnsCorrectTopic() { + _topicRepository = fixture.CachedTopicRepository; - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); - var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); - var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); + } - var foundTopic = greatGrandChildTopic.FindFirstParent(t => t.Id is 5); + /*============================================================================================================================ + | TEST: FIND ALL BY ATTRIBUTE: RETURNS CORRECT TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Looks for a deeply nested child topic using only the attribute value. + /// + [Fact] + public void FindAllByAttribute_ReturnsCorrectTopics() { - Assert.Equal(childTopic, foundTopic); + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); + var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); + var grandNieceTopic = new Topic("GrandNieceTopic", "Page", childTopic, 3); + var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); - } + grandChildTopic.Attributes.SetValue("Foo", "Baz"); + grandNieceTopic.Attributes.SetValue("Foo", "Bar"); + greatGrandChildTopic.Attributes.SetValue("Foo", "Bar"); - /*========================================================================================================================== - | TEST: FIND FIRST PARENT: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Correctly returns null if the delegate cannot be satisfied. - /// - [Fact] - public void FindFirstParent_ReturnsNull() { + Assert.Equal(greatGrandChildTopic, parentTopic.FindAllByAttribute("Foo", "Bar").First()); + Assert.Equal(2, parentTopic.FindAllByAttribute("Foo", "Bar").Count); + Assert.Equal(grandChildTopic, parentTopic.FindAllByAttribute("Foo", "Baz").First()); - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); + } - var foundTopic = childTopic.FindFirstParent(t => t.Id is 10); + /*============================================================================================================================ + | TEST: FIND FIRST PARENT: RETURNS CORRECT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a deeply nested , returns the first parent which satisfies a delegate. + /// + [Fact] + public void FindFirstParent_ReturnsCorrectTopic() { - Assert.Null(foundTopic); + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); + var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); + var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); - } + var foundTopic = greatGrandChildTopic.FindFirstParent(t => t.Id is 5); - /*========================================================================================================================== - | TEST: GET ROOT TOPIC: RETURNS ROOT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a deeply nested , returns the root . - /// - [Fact] - public void GetRootTopic_ReturnsRootTopic() { + Assert.Equal(childTopic, foundTopic); - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); - var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); - var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); + } - var rootTopic = greatGrandChildTopic.GetRootTopic(); + /*============================================================================================================================ + | TEST: FIND FIRST PARENT: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Correctly returns null if the delegate cannot be satisfied. + /// + [Fact] + public void FindFirstParent_ReturnsNull() { - Assert.Equal(parentTopic, rootTopic); + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); - } + var foundTopic = childTopic.FindFirstParent(t => t.Id is 10); - /*========================================================================================================================== - | TEST: GET ROOT TOPIC: RETURNS CURRENT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a root , returns the current . - /// - [Fact] - public void GetRootTopic_ReturnsCurrentTopic() { + Assert.Null(foundTopic); - var topic = new Topic("ParentTopic", "Page", null, 1); + } - var rootTopic = topic.GetRootTopic(); + /*============================================================================================================================ + | TEST: GET ROOT TOPIC: RETURNS ROOT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a deeply nested , returns the root . + /// + [Fact] + public void GetRootTopic_ReturnsRootTopic() { - Assert.Equal(topic, rootTopic); + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); + var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); + var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); - } + var rootTopic = greatGrandChildTopic.GetRootTopic(); - /*========================================================================================================================== - | TEST: GET BY UNIQUE KEY: ROOT KEY: RETURNS ROOT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a root , returns the root . - /// - [Fact] - public void GetByUniqueKey_RootKey_ReturnsRootTopic() { + Assert.Equal(parentTopic, rootTopic); - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - _ = new Topic("ChildTopic", "Page", parentTopic, 2); + } - var foundTopic = parentTopic.GetByUniqueKey("ParentTopic"); + /*============================================================================================================================ + | TEST: GET ROOT TOPIC: RETURNS CURRENT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a root , returns the current . + /// + [Fact] + public void GetRootTopic_ReturnsCurrentTopic() { - Assert.NotNull(foundTopic); - Assert.Equal(parentTopic, foundTopic); + var topic = new Topic("ParentTopic", "Page", null, 1); - } + var rootTopic = topic.GetRootTopic(); - /*========================================================================================================================== - | TEST: GET BY UNIQUE KEY: VALID KEY: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a deeply nested , returns the expected . - /// - [Fact] - public void GetByUniqueKey_ValidKey_ReturnsTopic() { + Assert.Equal(topic, rootTopic); - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); - var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); - var greatGrandChildTopic1 = new Topic("GreatGrandChildTopic1", "Page", grandChildTopic, 7); - var greatGrandChildTopic2 = new Topic("GreatGrandChildTopic2", "Page", grandChildTopic, 7); + } - var foundTopic = greatGrandChildTopic1.GetByUniqueKey("ParentTopic:ChildTopic:GrandChildTopic:GreatGrandChildTopic2"); + /*============================================================================================================================ + | TEST: GET BY UNIQUE KEY: ROOT KEY: RETURNS ROOT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a root , returns the root . + /// + [Fact] + public void GetByUniqueKey_RootKey_ReturnsRootTopic() { - Assert.Equal(greatGrandChildTopic2, foundTopic); + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + _ = new Topic("ChildTopic", "Page", parentTopic, 2); - } + var foundTopic = parentTopic.GetByUniqueKey("ParentTopic"); - /*========================================================================================================================== - | TEST: GET BY UNIQUE KEY: INVALID KEY: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given an invalid UniqueKey, the returns - /// null. - /// - [Fact] - public void GetByUniqueKey_InvalidKey_ReturnsNull() { + Assert.NotNull(foundTopic); + Assert.Equal(parentTopic, foundTopic); - var parentTopic = new Topic("ParentTopic", "Page", null, 1); - var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); - var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); - var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); + } - var foundTopic = greatGrandChildTopic.GetByUniqueKey("ParentTopic:ChildTopic:GrandChildTopic:GreatGrandChildTopic2"); + /*============================================================================================================================ + | TEST: GET BY UNIQUE KEY: VALID KEY: RETURNS TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a deeply nested , returns the expected . + /// + [Fact] + public void GetByUniqueKey_ValidKey_ReturnsTopic() { - Assert.Null(foundTopic); + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); + var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); + var greatGrandChildTopic1 = new Topic("GreatGrandChildTopic1", "Page", grandChildTopic, 7); + var greatGrandChildTopic2 = new Topic("GreatGrandChildTopic2", "Page", grandChildTopic, 7); - } + var foundTopic = greatGrandChildTopic1.GetByUniqueKey("ParentTopic:ChildTopic:GrandChildTopic:GreatGrandChildTopic2"); - /*========================================================================================================================== - | TEST: GET CONTENT TYPE: VALID CONTENT TYPE: RETURNS CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a deeply nested , returns the expected . - /// - [Fact] - public void GetContentType_ValidContentType_ReturnsContentType() { + Assert.Equal(greatGrandChildTopic2, foundTopic); - var topic = _topicRepository.Load(11111); - var contentTypeDescriptor = topic?.GetContentTypeDescriptor(); + } - Assert.NotNull(contentTypeDescriptor); - Assert.Equal("Page", contentTypeDescriptor?.Key); + /*============================================================================================================================ + | TEST: GET BY UNIQUE KEY: INVALID KEY: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given an invalid UniqueKey, the returns + /// null. + /// + [Fact] + public void GetByUniqueKey_InvalidKey_ReturnsNull() { - } + var parentTopic = new Topic("ParentTopic", "Page", null, 1); + var childTopic = new Topic("ChildTopic", "Page", parentTopic, 5); + var grandChildTopic = new Topic("GrandChildTopic", "Page", childTopic, 20); + var greatGrandChildTopic = new Topic("GreatGrandChildTopic", "Page", grandChildTopic, 7); - /*========================================================================================================================== - | TEST: GET CONTENT TYPE: INVALID CONTENT TYPE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given an invalid , the returns null. - /// - [Fact] - public void GetContentType_InvalidContentType_ReturnsNull() { + var foundTopic = greatGrandChildTopic.GetByUniqueKey("ParentTopic:ChildTopic:GrandChildTopic:GreatGrandChildTopic2"); - var parentTopic = _topicRepository.Load(11111); - var topic = new Topic("Test", "NonExistent", parentTopic); - var contentTypeDescriptor = topic.GetContentTypeDescriptor(); + Assert.Null(foundTopic); - Assert.Null(contentTypeDescriptor); + } - //Revert state - _topicRepository.Delete(topic); + /*============================================================================================================================ + | TEST: GET CONTENT TYPE: VALID CONTENT TYPE: RETURNS CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a deeply nested , returns the expected . + /// + [Fact] + public void GetContentType_ValidContentType_ReturnsContentType() { - } + var topic = _topicRepository.Load(11111); + var contentTypeDescriptor = topic?.GetContentTypeDescriptor(); - /*========================================================================================================================== - | TEST: GET CONTENT TYPE: INVALID TYPE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given an invalid , the returns null. - /// - /// - /// This varies from in that it returns a valid which doesn't derive from . - /// - [Fact] - public void GetContentType_InvalidType_ReturnsNull() { - - var parentTopic = _topicRepository.Load(11111); - var topic = new Topic("Test", "Title", parentTopic); - var contentTypeDescriptor = topic.GetContentTypeDescriptor(); - - Assert.Null(contentTypeDescriptor); - - //Revert state - _topicRepository.Delete(topic); - - } - - /*========================================================================================================================== - | TEST: ANY DIRTY: DIRTY COLLECTION: RETURN TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a with at least one that , - /// returns true. - /// - [Fact] - public void AnyDirty_DirtyCollection_ReturnTrue() { + Assert.NotNull(contentTypeDescriptor); + Assert.Equal("Page", contentTypeDescriptor?.Key); - var topics = new TopicCollection { - new Topic("Test", "Page") - }; + } - Assert.True(topics.AnyDirty()); + /*============================================================================================================================ + | TEST: GET CONTENT TYPE: INVALID CONTENT TYPE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given an invalid , the returns null. + /// + [Fact] + public void GetContentType_InvalidContentType_ReturnsNull() { - } + var parentTopic = _topicRepository.Load(11111); + var topic = new Topic("Test", "NonExistent", parentTopic); + var contentTypeDescriptor = topic.GetContentTypeDescriptor(); - /*========================================================================================================================== - | TEST: ANY DIRTY: CLEAN COLLECTION: RETURN FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a with no s that are , - /// returns false. - /// - [Fact] - public void AnyDirty_CleanCollection_ReturnFalse() { + Assert.Null(contentTypeDescriptor); - var topics = new TopicCollection { - new Topic("Test", "Page", null, 1) - }; + //Revert state + _topicRepository.Delete(topic); - Assert.False(topics.AnyDirty()); + } - } + /*============================================================================================================================ + | TEST: GET CONTENT TYPE: INVALID TYPE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given an invalid , the returns null. + /// + /// + /// This varies from in that it returns a valid which doesn't derive from . + /// + [Fact] + public void GetContentType_InvalidType_ReturnsNull() { - /*========================================================================================================================== - | TEST: ANY NEW: CONTAINS NEW: RETURN TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a with at least one that , returns - /// true. - /// - [Fact] - public void AnyNew_ContainsNew_ReturnTrue() { + var parentTopic = _topicRepository.Load(11111); + var topic = new Topic("Test", "Title", parentTopic); + var contentTypeDescriptor = topic.GetContentTypeDescriptor(); - var topics = new TopicCollection { - new Topic("Test", "Page") - }; + Assert.Null(contentTypeDescriptor); - Assert.True(topics.AnyNew()); + //Revert state + _topicRepository.Delete(topic); - } + } - /*========================================================================================================================== - | TEST: ANY NEW: CONTAINS EXISTING: RETURN FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a with no s that are , returns - /// false. - /// - [Fact] - public void AnyNew_ContainsExisting_ReturnFalse() { + /*============================================================================================================================ + | TEST: ANY DIRTY: DIRTY COLLECTION: RETURN TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a with at least one that , + /// returns true. + /// + [Fact] + public void AnyDirty_DirtyCollection_ReturnTrue() { + + var topics = new TopicCollection { + new Topic("Test", "Page") + }; + + Assert.True(topics.AnyDirty()); + + } + + /*============================================================================================================================ + | TEST: ANY DIRTY: CLEAN COLLECTION: RETURN FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a with no s that are , + /// returns false. + /// + [Fact] + public void AnyDirty_CleanCollection_ReturnFalse() { + + var topics = new TopicCollection { + new Topic("Test", "Page", null, 1) + }; + + Assert.False(topics.AnyDirty()); + + } + + /*============================================================================================================================ + | TEST: ANY NEW: CONTAINS NEW: RETURN TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a with at least one that , returns + /// true. + /// + [Fact] + public void AnyNew_ContainsNew_ReturnTrue() { + + var topics = new TopicCollection { + new Topic("Test", "Page") + }; + + Assert.True(topics.AnyNew()); + + } + + /*============================================================================================================================ + | TEST: ANY NEW: CONTAINS EXISTING: RETURN FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a with no s that are , returns + /// false. + /// + [Fact] + public void AnyNew_ContainsExisting_ReturnFalse() { - var topics = new TopicCollection { - new Topic("Test", "Page", null, 1) - }; + var topics = new TopicCollection { + new Topic("Test", "Page", null, 1) + }; - Assert.False(topics.AnyNew()); + Assert.False(topics.AnyNew()); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TopicReferenceCollectionTest.cs b/OnTopic.Tests/TopicReferenceCollectionTest.cs index 35cc11dc..4a0ac88b 100644 --- a/OnTopic.Tests/TopicReferenceCollectionTest.cs +++ b/OnTopic.Tests/TopicReferenceCollectionTest.cs @@ -8,467 +8,466 @@ using OnTopic.Collections.Specialized; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC REFERENCE COLLECTION TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the , with a particular emphasis on the custom features +/// such as , , , and the cross-referencing of reciprocal values in the property. +/// +[ExcludeFromCodeCoverage] +public class TopicReferenceCollectionTest { /*============================================================================================================================ - | CLASS: TOPIC REFERENCE COLLECTION TEST + | TEST: ADD: NEW REFERENCE: IS DIRTY \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the , with a particular emphasis on the custom features - /// such as , , , and the cross-referencing of reciprocal values in the property. + /// Assembles a new , adds a new reference, and confirms that + /// is correctly set. /// - [ExcludeFromCodeCoverage] - public class TopicReferenceCollectionTest { - - /*========================================================================================================================== - | TEST: ADD: NEW REFERENCE: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference, and confirms that - /// is correctly set. - /// - [Fact] - public void Add_NewReference_IsDirty() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference); - - Assert.Single(topic.References); - Assert.True(topic.References.IsDirty()); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: NEW REFERENCE: NOT DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , and confirms that - /// is not set. - /// - [Fact] - public void SetValue_NewReference_NotDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var reference = new Topic("Reference", "Page", null, 2); - - topic.References.SetValue("Reference", reference, false); - - Assert.Single(topic.References); - Assert.False(topic.References.IsDirty()); - - } - - /*========================================================================================================================== - | TEST: REMOVE: EXISTING REFERENCE: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new with a topic reference, removes that reference using , and confirms that is set. - /// - [Fact] - public void Remove_ExistingReference_IsDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference, false); - topic.References.Remove("Reference"); - - Assert.Empty(topic.References); - Assert.True(topic.References.IsDirty()); - - } - - /*========================================================================================================================== - | TEST: CLEAR: EXISTING REFERENCES: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , calls and confirms that is set. Also confirms that items are correctly removed - /// from recipricol . - /// - [Fact] - public void Clear_ExistingReferences_IsDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var reference = new Topic("Reference", "Page"); - - topic.References.Add(new("Reference1", reference, false)); - topic.References.Add(new("Reference2", null, false)); - topic.References.Clear(); - - Assert.Empty(topic.References); - Assert.Empty(reference.IncomingRelationships.GetValues("Reference")); - Assert.True(topic.References.IsDirty()); - - } - - /*========================================================================================================================== - | TEST: ADD: NEW TOPIC: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new and adds a new reference using with set to false - /// , confirming that remains true - /// since the target is unsaved. - /// - [Fact] - public void Add_NewTopic_IsDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference, false); - - Assert.True(topic.References.IsDirty()); - - } - - /*========================================================================================================================== - | TEST: ADD: NEW REFERENCE: INCOMING RELATIONSHIP SET - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , and confirms that - /// reference is correctly set. - /// - [Fact] - public void Add_NewReference_IncomingRelationshipSet() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference); - - Assert.Single(reference.IncomingRelationships.GetValues("Reference")); - - } - - /*========================================================================================================================== - | TEST: REMOVE: EXISTING REFERENCE: INCOMING RELATIONSHIP REMOVED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , removes the - /// reference using , and confirms that - /// the reference is correctly removed as well. - /// - /// - /// This calls twice. The first to confirm that the is removed, the second to ensure that the attempt to call isn't disrupted by the fact that the is null. - /// - [Fact] - public void Remove_ExistingReference_IncomingRelationshipRemoved() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.Add(new("Reference1", reference, false)); - topic.References.Add(new("Reference2", null, false)); - - topic.References.Remove("Reference1"); - topic.References.Remove("Reference2"); - - Assert.Empty(reference.IncomingRelationships.GetValues("Reference")); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: EXISTING REFERENCE: TOPIC UPDATED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , updates the - /// reference using , and confirms that the reference and are - /// correctly updated. - /// - [Fact] - public void SetValue_ExistingReference_TopicUpdated() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - var newReference = new Topic("NewReference", "Page"); - - topic.References.SetValue("Reference", reference); - topic.References.SetValue("Reference", newReference); - - Assert.Equal(newReference, topic.References.GetValue("Reference")); - Assert.Empty(reference.IncomingRelationships.GetValues("Reference")); - Assert.Single(newReference.IncomingRelationships.GetValues("Reference")); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: NULL REFERENCE: TOPIC UPDATED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , updates the - /// reference using with a null value, and confirms that the reference and are correctly removed. - /// - /// - /// This calls twice. The first to confirm that the is set, the second to ensure that - /// the attempt to call isn't disrupted by the fact that the will now be null. - /// - [Fact] - public void SetValue_ExistingReference_IncomingRelationshipsUpdates() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference); - topic.References.SetValue("Reference", null); - topic.References.SetValue("Reference", null); - - Assert.False(topic.References.Contains("Reference")); - Assert.Null(topic.References.GetValue("Reference")); - Assert.Equal(0, reference.IncomingRelationships.GetValues("Reference")?.Count); - - } - - /*========================================================================================================================== - | TEST: SET VALUE: NULL REFERENCE: TOPIC REMOVED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference using , updates the - /// reference with a null value using , and confirms that the reference is correctly removed. - /// - [Fact] - public void SetValue_NullReference_TopicRemoved() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference); - topic.References.SetValue("Reference", null); - - Assert.Empty(topic.References); - Assert.Null(topic.References.GetValue("Reference")); - - } - - /*========================================================================================================================== - | TEST: ADD: NEW REFERENCE: TOPIC IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference, and confirms that - /// is correctly set. - /// - [Fact] - public void Add_NewReference_TopicIsDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var reference = new Topic("Reference", "Page", null, 2); - - topic.References.SetValue("Reference", reference); - - Assert.True(topic.IsDirty(true)); - Assert.False(reference.IsDirty(true)); - - } - - /*========================================================================================================================== - | TEST: GET TOPIC: EXISTING REFERENCE: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference, and confirms that - /// correctly returns the . - /// - [Fact] - public void GetTopic_ExistingReference_ReturnsTopic() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference); - - Assert.Equal(reference, topic.References.GetValue("Reference")); - - } - - /*========================================================================================================================== - | TEST: GET TOPIC: MISSING REFERENCE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new , adds a new reference, and confirms that - /// correctly returns null - /// if an incorrect referencedKey is entered. - /// - [Fact] - public void GetTopic_MissingReference_ReturnsNull() { - - var topic = new Topic("Topic", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("Reference", reference); - - Assert.Null(topic.References.GetValue("MissingReference")); - - } - - /*========================================================================================================================== - | TEST: GET TOPIC: INHERITED REFERENCE: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new with a , adds a new reference to the , and confirms that correctly returns the related topic reference, inheriting from both - /// and . - /// - [Fact] - public void GetTopic_InheritedReference_ReturnsTopic() { - - var parentTopic = new Topic("Parent", "Page"); - var topic = new Topic("Topic", "Page", parentTopic); - var baseTopic = new Topic("Base", "Page"); - var reference = new Topic("Reference", "Page"); - - parentTopic.BaseTopic = baseTopic; - baseTopic.References.SetValue("Reference", reference); - - Assert.Equal(reference, topic.References.GetValue("Reference", true)); - - } - - /*========================================================================================================================== - | TEST: GET TOPIC: INHERITED REFERENCE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new with a , adds a new reference to the , and confirms that correctly returns null if an incorrect referencedKey is - /// entered. - /// - [Fact] - public void GetTopic_InheritedReference_ReturnsNull() { - - var topic = new Topic("Topic", "Page"); - var baseTopic = new Topic("Base", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.BaseTopic = baseTopic; - baseTopic.References.SetValue("Reference", reference); - - Assert.Null(topic.References.GetValue("MissingReference", true)); - - } - - /*========================================================================================================================== - | TEST: GET TOPIC: INHERITED REFERENCE WITHOUT INHERITANCE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new with a , adds a new reference to the , and confirms that correctly returns null if inheritFromBase is set to - /// false. - /// - [Fact] - public void GetTopic_InheritedReferenceWithoutInheritance_ReturnsNull() { - - var topic = new Topic("Topic", "Page"); - var baseTopic = new Topic("Base", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.BaseTopic = baseTopic; - baseTopic.References.SetValue("Reference", reference); - - Assert.Null(topic.References.GetValue("Reference", null, false, false)); - - } - - /*========================================================================================================================== - | TEST: ADD: TOPIC REFERENCE WITH BUSINESS LOGIC: IS RETURNED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a topic reference on a topic instance; ensures it is routed through the corresponding property and correctly - /// retrieved. - /// - [Fact] - public void Add_TopicReferenceWithBusinessLogic_IsReturned() { - - var topic = new CustomTopic("Test", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("TopicReference", reference); - - Assert.Equal(reference, topic.TopicReference); - - } - - /*========================================================================================================================== - | TEST: ADD: TOPIC REFERENCE WITH BUSINESS LOGIC: REMOVES REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a topic reference on a topic instance, then sets it to null, ensuring that it is correctly removed. - /// - [Fact] - public void Add_TopicReferenceWithBusinessLogic_RemovedReference() { - - var topic = new CustomTopic("Test", "Page"); - var reference = new Topic("Reference", "Page"); - - topic.References.SetValue("BaseTopic", reference); - topic.References.SetValue("BaseTopic", null); - - Assert.Null(topic.TopicReference); - - } - - /*========================================================================================================================== - | TEST: ADD: TOPIC REFERENCE WITH BUSINESS LOGIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a topic reference on a topic instance with an invalid value; ensures an - /// is thrown. - /// - [Fact] - public void Add_TopicReferenceWithBusinessLogic_ThrowsException() { - - var topic = new CustomTopic("Test", "Page"); - var reference = new Topic("Reference", "Container"); - - Assert.Throws(() => - topic.References.SetValue("TopicReference", reference) - ); - - } - - /*========================================================================================================================== - | TEST: SET: TOPIC REFERENCE WITH BUSINESS LOGIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a topic reference on a topic instance with an invalid value; ensures an - /// is thrown. - /// - [Fact] - public void Set_TopicReferenceWithBusinessLogic_ThrowsException() { - - var topic = new CustomTopic("Test", "Page"); - var reference = new Topic("Reference", "Container"); + [Fact] + public void Add_NewReference_IsDirty() { - Assert.Throws(() => - topic.References.Add(new("TopicReference", reference)) - ); - - } - - } //Class -} //Namespace \ No newline at end of file + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference); + + Assert.Single(topic.References); + Assert.True(topic.References.IsDirty()); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: NEW REFERENCE: NOT DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , and confirms that + /// is not set. + /// + [Fact] + public void SetValue_NewReference_NotDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var reference = new Topic("Reference", "Page", null, 2); + + topic.References.SetValue("Reference", reference, false); + + Assert.Single(topic.References); + Assert.False(topic.References.IsDirty()); + + } + + /*============================================================================================================================ + | TEST: REMOVE: EXISTING REFERENCE: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new with a topic reference, removes that reference using , and confirms that is set. + /// + [Fact] + public void Remove_ExistingReference_IsDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference, false); + topic.References.Remove("Reference"); + + Assert.Empty(topic.References); + Assert.True(topic.References.IsDirty()); + + } + + /*============================================================================================================================ + | TEST: CLEAR: EXISTING REFERENCES: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , calls and confirms that is set. Also confirms that items are correctly removed + /// from recipricol . + /// + [Fact] + public void Clear_ExistingReferences_IsDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var reference = new Topic("Reference", "Page"); + + topic.References.Add(new("Reference1", reference, false)); + topic.References.Add(new("Reference2", null, false)); + topic.References.Clear(); + + Assert.Empty(topic.References); + Assert.Empty(reference.IncomingRelationships.GetValues("Reference")); + Assert.True(topic.References.IsDirty()); + + } + + /*============================================================================================================================ + | TEST: ADD: NEW TOPIC: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new and adds a new reference using with set to false + /// , confirming that remains true + /// since the target is unsaved. + /// + [Fact] + public void Add_NewTopic_IsDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference, false); + + Assert.True(topic.References.IsDirty()); + + } + + /*============================================================================================================================ + | TEST: ADD: NEW REFERENCE: INCOMING RELATIONSHIP SET + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , and confirms that + /// reference is correctly set. + /// + [Fact] + public void Add_NewReference_IncomingRelationshipSet() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference); + + Assert.Single(reference.IncomingRelationships.GetValues("Reference")); + + } + + /*============================================================================================================================ + | TEST: REMOVE: EXISTING REFERENCE: INCOMING RELATIONSHIP REMOVED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , removes the + /// reference using , and confirms that + /// the reference is correctly removed as well. + /// + /// + /// This calls twice. The first to confirm that the is removed, the second to ensure that the attempt to call isn't disrupted by the fact that the is null. + /// + [Fact] + public void Remove_ExistingReference_IncomingRelationshipRemoved() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.Add(new("Reference1", reference, false)); + topic.References.Add(new("Reference2", null, false)); + + topic.References.Remove("Reference1"); + topic.References.Remove("Reference2"); + + Assert.Empty(reference.IncomingRelationships.GetValues("Reference")); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: EXISTING REFERENCE: TOPIC UPDATED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , updates the + /// reference using , and confirms that the reference and are + /// correctly updated. + /// + [Fact] + public void SetValue_ExistingReference_TopicUpdated() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + var newReference = new Topic("NewReference", "Page"); + + topic.References.SetValue("Reference", reference); + topic.References.SetValue("Reference", newReference); + + Assert.Equal(newReference, topic.References.GetValue("Reference")); + Assert.Empty(reference.IncomingRelationships.GetValues("Reference")); + Assert.Single(newReference.IncomingRelationships.GetValues("Reference")); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: NULL REFERENCE: TOPIC UPDATED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , updates the + /// reference using with a null value, and confirms that the reference and are correctly removed. + /// + /// + /// This calls twice. The first to confirm that the is set, the second to ensure that + /// the attempt to call isn't disrupted by the fact that the will now be null. + /// + [Fact] + public void SetValue_ExistingReference_IncomingRelationshipsUpdates() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference); + topic.References.SetValue("Reference", null); + topic.References.SetValue("Reference", null); + + Assert.False(topic.References.Contains("Reference")); + Assert.Null(topic.References.GetValue("Reference")); + Assert.Equal(0, reference.IncomingRelationships.GetValues("Reference")?.Count); + + } + + /*============================================================================================================================ + | TEST: SET VALUE: NULL REFERENCE: TOPIC REMOVED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference using , updates the + /// reference with a null value using , and confirms that the reference is correctly removed. + /// + [Fact] + public void SetValue_NullReference_TopicRemoved() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference); + topic.References.SetValue("Reference", null); + + Assert.Empty(topic.References); + Assert.Null(topic.References.GetValue("Reference")); + + } + + /*============================================================================================================================ + | TEST: ADD: NEW REFERENCE: TOPIC IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference, and confirms that + /// is correctly set. + /// + [Fact] + public void Add_NewReference_TopicIsDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var reference = new Topic("Reference", "Page", null, 2); + + topic.References.SetValue("Reference", reference); + + Assert.True(topic.IsDirty(true)); + Assert.False(reference.IsDirty(true)); + + } + + /*============================================================================================================================ + | TEST: GET TOPIC: EXISTING REFERENCE: RETURNS TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference, and confirms that + /// correctly returns the . + /// + [Fact] + public void GetTopic_ExistingReference_ReturnsTopic() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference); + + Assert.Equal(reference, topic.References.GetValue("Reference")); + + } + + /*============================================================================================================================ + | TEST: GET TOPIC: MISSING REFERENCE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new , adds a new reference, and confirms that + /// correctly returns null + /// if an incorrect referencedKey is entered. + /// + [Fact] + public void GetTopic_MissingReference_ReturnsNull() { + + var topic = new Topic("Topic", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("Reference", reference); + + Assert.Null(topic.References.GetValue("MissingReference")); + + } + + /*============================================================================================================================ + | TEST: GET TOPIC: INHERITED REFERENCE: RETURNS TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new with a , adds a new reference to the , and confirms that correctly returns the related topic reference, inheriting from both + /// and . + /// + [Fact] + public void GetTopic_InheritedReference_ReturnsTopic() { + + var parentTopic = new Topic("Parent", "Page"); + var topic = new Topic("Topic", "Page", parentTopic); + var baseTopic = new Topic("Base", "Page"); + var reference = new Topic("Reference", "Page"); + + parentTopic.BaseTopic = baseTopic; + baseTopic.References.SetValue("Reference", reference); + + Assert.Equal(reference, topic.References.GetValue("Reference", true)); + + } + + /*============================================================================================================================ + | TEST: GET TOPIC: INHERITED REFERENCE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new with a , adds a new reference to the , and confirms that correctly returns null if an incorrect referencedKey is + /// entered. + /// + [Fact] + public void GetTopic_InheritedReference_ReturnsNull() { + + var topic = new Topic("Topic", "Page"); + var baseTopic = new Topic("Base", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.BaseTopic = baseTopic; + baseTopic.References.SetValue("Reference", reference); + + Assert.Null(topic.References.GetValue("MissingReference", true)); + + } + + /*============================================================================================================================ + | TEST: GET TOPIC: INHERITED REFERENCE WITHOUT INHERITANCE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new with a , adds a new reference to the , and confirms that correctly returns null if inheritFromBase is set to + /// false. + /// + [Fact] + public void GetTopic_InheritedReferenceWithoutInheritance_ReturnsNull() { + + var topic = new Topic("Topic", "Page"); + var baseTopic = new Topic("Base", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.BaseTopic = baseTopic; + baseTopic.References.SetValue("Reference", reference); + + Assert.Null(topic.References.GetValue("Reference", null, false, false)); + + } + + /*============================================================================================================================ + | TEST: ADD: TOPIC REFERENCE WITH BUSINESS LOGIC: IS RETURNED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a topic reference on a topic instance; ensures it is routed through the corresponding property and correctly + /// retrieved. + /// + [Fact] + public void Add_TopicReferenceWithBusinessLogic_IsReturned() { + + var topic = new CustomTopic("Test", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("TopicReference", reference); + + Assert.Equal(reference, topic.TopicReference); + + } + + /*============================================================================================================================ + | TEST: ADD: TOPIC REFERENCE WITH BUSINESS LOGIC: REMOVES REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a topic reference on a topic instance, then sets it to null, ensuring that it is correctly removed. + /// + [Fact] + public void Add_TopicReferenceWithBusinessLogic_RemovedReference() { + + var topic = new CustomTopic("Test", "Page"); + var reference = new Topic("Reference", "Page"); + + topic.References.SetValue("BaseTopic", reference); + topic.References.SetValue("BaseTopic", null); + + Assert.Null(topic.TopicReference); + + } + + /*============================================================================================================================ + | TEST: ADD: TOPIC REFERENCE WITH BUSINESS LOGIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a topic reference on a topic instance with an invalid value; ensures an + /// is thrown. + /// + [Fact] + public void Add_TopicReferenceWithBusinessLogic_ThrowsException() { + + var topic = new CustomTopic("Test", "Page"); + var reference = new Topic("Reference", "Container"); + + Assert.Throws(() => + topic.References.SetValue("TopicReference", reference) + ); + + } + + /*============================================================================================================================ + | TEST: SET: TOPIC REFERENCE WITH BUSINESS LOGIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a topic reference on a topic instance with an invalid value; ensures an + /// is thrown. + /// + [Fact] + public void Set_TopicReferenceWithBusinessLogic_ThrowsException() { + + var topic = new CustomTopic("Test", "Page"); + var reference = new Topic("Reference", "Container"); + + Assert.Throws(() => + topic.References.Add(new("TopicReference", reference)) + ); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TopicRelationshipMultiMapTest.cs b/OnTopic.Tests/TopicRelationshipMultiMapTest.cs index 7136a232..48c736af 100644 --- a/OnTopic.Tests/TopicRelationshipMultiMapTest.cs +++ b/OnTopic.Tests/TopicRelationshipMultiMapTest.cs @@ -8,603 +8,602 @@ using OnTopic.Collections.Specialized; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC RELATIONSHIP MULTI-MAP TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TopicRelationshipMultiMapTest { /*============================================================================================================================ - | CLASS: TOPIC RELATIONSHIP MULTI-MAP TEST + | TEST: SET VALUE: CREATES RELATIONSHIP \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Sets a relationship and confirms that it is accessible. /// - [ExcludeFromCodeCoverage] - public class TopicRelationshipMultiMapTest { + [Fact] + public void SetValue_CreatesRelationship() { - /*========================================================================================================================== - | TEST: SET VALUE: CREATES RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a relationship and confirms that it is accessible. - /// - [Fact] - public void SetValue_CreatesRelationship() { + var parent = new Topic("Parent", "Page"); + var related = new Topic("Related", "Page"); - var parent = new Topic("Parent", "Page"); - var related = new Topic("Related", "Page"); + parent.Relationships.SetValue("Friends", related); - parent.Relationships.SetValue("Friends", related); + Assert.Equal(parent.Relationships.GetValues("Friends").First(), related); - Assert.Equal(parent.Relationships.GetValues("Friends").First(), related); + } - } + /*============================================================================================================================ + | TEST: REMOVE: INVALID RELATIONSHIP KEY: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to remove a from a where the is invalid. In this case, should + /// return false. + /// + [Fact] + public void Remove_InvalidRelationshipKey_ReturnsFalse() { - /*========================================================================================================================== - | TEST: REMOVE: INVALID RELATIONSHIP KEY: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to remove a from a where the is invalid. In this case, should - /// return false. - /// - [Fact] - public void Remove_InvalidRelationshipKey_ReturnsFalse() { + var parent = new Topic("Parent", "Page"); + var unrelated = new Topic("Unrelated", "Page"); - var parent = new Topic("Parent", "Page"); - var unrelated = new Topic("Unrelated", "Page"); + Assert.False(parent.Relationships.Remove("Unrelated", unrelated)); - Assert.False(parent.Relationships.Remove("Unrelated", unrelated)); + } - } + /*============================================================================================================================ + | TEST: REMOVE: INVALID TOPIC KEY: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to remove a from a where the is does not + /// exist. In this case, should return false. + /// + [Fact] + public void Remove_InvalidTopicKey_ReturnsFalse() { - /*========================================================================================================================== - | TEST: REMOVE: INVALID TOPIC KEY: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to remove a from a where the is does not - /// exist. In this case, should return false. - /// - [Fact] - public void Remove_InvalidTopicKey_ReturnsFalse() { + var multiMap = new TopicMultiMap(); + var unrelated = new Topic("Unrelated", "Page"); - var multiMap = new TopicMultiMap(); - var unrelated = new Topic("Unrelated", "Page"); + multiMap.Add("Related", new("Test", "Page")); - multiMap.Add("Related", new("Test", "Page")); + Assert.False(multiMap.Remove("Related", unrelated)); - Assert.False(multiMap.Remove("Related", unrelated)); + } - } + /*============================================================================================================================ + | TEST: REMOVE: REMOVES RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a relationship and then removes it by key, and confirms that it is removed. + /// + [Fact] + public void Remove_RemovesRelationship() { - /*========================================================================================================================== - | TEST: REMOVE: REMOVES RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a relationship and then removes it by key, and confirms that it is removed. - /// - [Fact] - public void Remove_RemovesRelationship() { + var parent = new Topic("Parent", "Page"); + var related = new Topic("Related", "Page"); - var parent = new Topic("Parent", "Page"); - var related = new Topic("Related", "Page"); + parent.Relationships.SetValue("Friends", related); + parent.Relationships.Remove("Friends", related); - parent.Relationships.SetValue("Friends", related); - parent.Relationships.Remove("Friends", related); + Assert.Null(parent.Relationships.GetValues("Friends").FirstOrDefault()); - Assert.Null(parent.Relationships.GetValues("Friends").FirstOrDefault()); + } - } + /*============================================================================================================================ + | TEST: REMOVE: REMOVES INCOMING RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a relationship and then removes it by key, and confirms that it is removed from the incoming relationships + /// property. + /// + [Fact] + public void Remove_RemovesIncomingRelationship() { - /*========================================================================================================================== - | TEST: REMOVE: REMOVES INCOMING RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a relationship and then removes it by key, and confirms that it is removed from the incoming relationships - /// property. - /// - [Fact] - public void Remove_RemovesIncomingRelationship() { + var parent = new Topic("Parent", "Page"); + var related = new Topic("Related", "Page"); + var relationships = new TopicRelationshipMultiMap(parent); - var parent = new Topic("Parent", "Page"); - var related = new Topic("Related", "Page"); - var relationships = new TopicRelationshipMultiMap(parent); + relationships.SetValue("Friends", related); + relationships.Remove("Friends", related); - relationships.SetValue("Friends", related); - relationships.Remove("Friends", related); + Assert.Null(related.IncomingRelationships.GetValues("Friends").FirstOrDefault()); - Assert.Null(related.IncomingRelationships.GetValues("Friends").FirstOrDefault()); + } - } + /*============================================================================================================================ + | TEST: SET VALUE: CREATES INCOMING RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a relationship and confirms that it is accessible on incoming relationships property. + /// + [Fact] + public void SetValue_CreatesIncomingRelationship() { - /*========================================================================================================================== - | TEST: SET VALUE: CREATES INCOMING RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a relationship and confirms that it is accessible on incoming relationships property. - /// - [Fact] - public void SetValue_CreatesIncomingRelationship() { + var parent = new Topic("Parent", "Page"); + var related = new Topic("Related", "Page"); + var relationships = new TopicRelationshipMultiMap(parent); - var parent = new Topic("Parent", "Page"); - var related = new Topic("Related", "Page"); - var relationships = new TopicRelationshipMultiMap(parent); + relationships.SetValue("Friends", related); - relationships.SetValue("Friends", related); + Assert.Equal(related.IncomingRelationships.GetValues("Friends").First(), parent); - Assert.Equal(related.IncomingRelationships.GetValues("Friends").First(), parent); + } - } + /*============================================================================================================================ + | TEST: SET VALUE: INCOMING RELATIONSHIPS: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to set a relationship on a that is marked as isIncoming + /// without setting the isIncoming parameter on and verifies that a is thrown. + /// + [Fact] + public void SetValue_IncomingRelationships_ThrowsException() { - /*========================================================================================================================== - | TEST: SET VALUE: INCOMING RELATIONSHIPS: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to set a relationship on a that is marked as isIncoming - /// without setting the isIncoming parameter on and verifies that a is thrown. - /// - [Fact] - public void SetValue_IncomingRelationships_ThrowsException() { - - var parent = new Topic("Parent", "Page"); - var related = new Topic("Related", "Page"); - var relationships = new TopicRelationshipMultiMap(parent, true); - - Assert.Throws(() => - relationships.SetValue("Friends", related) - ); + var parent = new Topic("Parent", "Page"); + var related = new Topic("Related", "Page"); + var relationships = new TopicRelationshipMultiMap(parent, true); - } + Assert.Throws(() => + relationships.SetValue("Friends", related) + ); - /*========================================================================================================================== - | TEST: REMOVE: INCOMING RELATIONSHIPS: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to remove a relationship from a that is marked as isIncoming - /// without setting the isIncoming parameter on and verifies that a is thrown. - /// - [Fact] - public void Remove_IncomingRelationships_ThrowsException() { - - var parent = new Topic("Parent", "Page"); - var related = new Topic("Related", "Page"); - var relationships = new TopicRelationshipMultiMap(parent, true); - - Assert.Throws(() => - relationships.Remove("Friends", related) - ); + } - } + /*============================================================================================================================ + | TEST: REMOVE: INCOMING RELATIONSHIPS: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to remove a relationship from a that is marked as isIncoming + /// without setting the isIncoming parameter on and verifies that a is thrown. + /// + [Fact] + public void Remove_IncomingRelationships_ThrowsException() { + + var parent = new Topic("Parent", "Page"); + var related = new Topic("Related", "Page"); + var relationships = new TopicRelationshipMultiMap(parent, true); - /*========================================================================================================================== - | TEST: SET VALUE: UPDATES KEY COUNT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets relationships in multiple namespaces, and the correct number of keys are returned. - /// - [Fact] - public void SetValue_UpdatesKeyCount() { + Assert.Throws(() => + relationships.Remove("Friends", related) + ); - var parent = new Topic("Parent", "Page"); - var relationships = new TopicRelationshipMultiMap(parent); + } - for (var i = 0; i < 5; i++) { - relationships.SetValue("Relationship" + i, new Topic("Related" + i, "Page")); - } + /*============================================================================================================================ + | TEST: SET VALUE: UPDATES KEY COUNT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets relationships in multiple namespaces, and the correct number of keys are returned. + /// + [Fact] + public void SetValue_UpdatesKeyCount() { - Assert.Equal(5, relationships.Keys.Count); - Assert.Contains("Relationship3", relationships.Keys); + var parent = new Topic("Parent", "Page"); + var relationships = new TopicRelationshipMultiMap(parent); + for (var i = 0; i < 5; i++) { + relationships.SetValue("Relationship" + i, new Topic("Related" + i, "Page")); } - /*========================================================================================================================== - | TEST: GET ENUMERATOR: RETURNS KEY/VALUES PAIRS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Enumerates over the , ensuring that the enumerator defined by the interface implementation successfully relays the call to the underlying - /// . - /// - [Fact] - public void GetEnumerator_ReturnsKeyValuesPairs() { + Assert.Equal(5, relationships.Keys.Count); + Assert.Contains("Relationship3", relationships.Keys); - var counter = 0; - var multiMap = new TopicMultiMap(); - var readOnlyRelationships = new ReadOnlyTopicMultiMap(multiMap); + } - for (var i = 0; i < 5; i++) { - multiMap.Add(new("Relationship" + i, new())); - } + /*============================================================================================================================ + | TEST: GET ENUMERATOR: RETURNS KEY/VALUES PAIRS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Enumerates over the , ensuring that the enumerator defined by the interface implementation successfully relays the call to the underlying + /// . + /// + [Fact] + public void GetEnumerator_ReturnsKeyValuesPairs() { - foreach (var pair in readOnlyRelationships) { - counter++; - } + var counter = 0; + var multiMap = new TopicMultiMap(); + var readOnlyRelationships = new ReadOnlyTopicMultiMap(multiMap); - Assert.Equal(5, readOnlyRelationships.Count); - Assert.Equal(5, counter); + for (var i = 0; i < 5; i++) { + multiMap.Add(new("Relationship" + i, new())); + } + foreach (var pair in readOnlyRelationships) { + counter++; } - /*========================================================================================================================== - | TEST: INDEXER: RETURNS KEY/VALUES PAIRS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and ensures that a can be - /// retrieved by via the indexer. - /// - [Fact] - public void Indexer_ReturnsKeyValuesPair() { + Assert.Equal(5, readOnlyRelationships.Count); + Assert.Equal(5, counter); - var multiMap = new TopicMultiMap(); - var readOnlyTopicMultiMap = new ReadOnlyTopicMultiMap(multiMap); - var topics = new TopicCollection(); - var keyValuesPair = new KeyValuesPair("Relationship", topics); - var topic = new Topic("Test", "Test"); + } - topics.Add(topic); - multiMap.Add(keyValuesPair); + /*============================================================================================================================ + | TEST: INDEXER: RETURNS KEY/VALUES PAIRS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and ensures that a can be + /// retrieved by via the indexer. + /// + [Fact] + public void Indexer_ReturnsKeyValuesPair() { - Assert.Single(readOnlyTopicMultiMap); - Assert.Equal(topic, readOnlyTopicMultiMap["Relationship"].FirstOrDefault()); + var multiMap = new TopicMultiMap(); + var readOnlyTopicMultiMap = new ReadOnlyTopicMultiMap(multiMap); + var topics = new TopicCollection(); + var keyValuesPair = new KeyValuesPair("Relationship", topics); + var topic = new Topic("Test", "Test"); - } + topics.Add(topic); + multiMap.Add(keyValuesPair); - /*========================================================================================================================== - | TEST: GET ALL VALUES: RETURNS ALL TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets relationships in multiple namespaces, and ensures they are all returned via . - /// - [Fact] - public void GetAllValues_ReturnsAllTopics() { + Assert.Single(readOnlyTopicMultiMap); + Assert.Equal(topic, readOnlyTopicMultiMap["Relationship"].FirstOrDefault()); - var parent = new Topic("Parent", "Page"); - var relationships = new TopicRelationshipMultiMap(parent); + } - for (var i = 0; i < 5; i++) { - relationships.SetValue("Relationship" + i, new Topic("Related" + i, "Page")); - } + /*============================================================================================================================ + | TEST: GET ALL VALUES: RETURNS ALL TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets relationships in multiple namespaces, and ensures they are all returned via . + /// + [Fact] + public void GetAllValues_ReturnsAllTopics() { - Assert.Equal(5, relationships.Count); - Assert.Equal("Related3", relationships.GetValues("Relationship3").First().Key); - Assert.Equal(5, relationships.GetAllValues().Count); + var parent = new Topic("Parent", "Page"); + var relationships = new TopicRelationshipMultiMap(parent); + for (var i = 0; i < 5; i++) { + relationships.SetValue("Relationship" + i, new Topic("Related" + i, "Page")); } - /*========================================================================================================================== - | TEST: GET ALL VALUES: CONTENT TYPES: RETURNS ALL CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets relationships in multiple namespaces, with different ContentTypes, then filters the results of by content type. - /// - [Fact] - public void GetAllValues_ContentTypes_ReturnsAllContentTypes() { + Assert.Equal(5, relationships.Count); + Assert.Equal("Related3", relationships.GetValues("Relationship3").First().Key); + Assert.Equal(5, relationships.GetAllValues().Count); - var parent = new Topic("Parent", "Page"); - var relationships = new TopicRelationshipMultiMap(parent); + } - for (var i = 0; i < 5; i++) { - relationships.SetValue("Relationship" + i, new Topic("Related" + i, "ContentType" + i)); - } + /*============================================================================================================================ + | TEST: GET ALL VALUES: CONTENT TYPES: RETURNS ALL CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets relationships in multiple namespaces, with different ContentTypes, then filters the results of by content type. + /// + [Fact] + public void GetAllValues_ContentTypes_ReturnsAllContentTypes() { - Assert.Equal(5, relationships.Keys.Count); - Assert.Single(relationships.GetAllValues("ContentType3")); + var parent = new Topic("Parent", "Page"); + var relationships = new TopicRelationshipMultiMap(parent); + for (var i = 0; i < 5; i++) { + relationships.SetValue("Relationship" + i, new Topic("Related" + i, "ContentType" + i)); } - /*========================================================================================================================== - | TEST: SET TOPIC: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a topic to a and confirms that is set. - /// - [Fact] - public void SetTopic_IsDirty() { + Assert.Equal(5, relationships.Keys.Count); + Assert.Single(relationships.GetAllValues("ContentType3")); - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page"); + } + + /*============================================================================================================================ + | TEST: SET TOPIC: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a topic to a and confirms that is set. + /// + [Fact] + public void SetTopic_IsDirty() { - relationships.SetValue("Related", related); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page"); - Assert.True(relationships.IsDirty()); + relationships.SetValue("Related", related); - } + Assert.True(relationships.IsDirty()); - /*========================================================================================================================== - | TEST: SET VALUE: IS DUPLICATE: IS NOT DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a duplicate topic to a and confirms that value of is false. - /// - [Fact] - public void SetValue_IsDuplicate_IsNotDirty() { + } - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page", null, 2); + /*============================================================================================================================ + | TEST: SET VALUE: IS DUPLICATE: IS NOT DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a duplicate topic to a and confirms that value of is false. + /// + [Fact] + public void SetValue_IsDuplicate_IsNotDirty() { - relationships.SetValue("Related", related); - relationships.MarkClean(); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page", null, 2); - relationships.SetValue("Related", related); + relationships.SetValue("Related", related); + relationships.MarkClean(); - Assert.False(relationships.IsDirty()); + relationships.SetValue("Related", related); - } + Assert.False(relationships.IsDirty()); - /*========================================================================================================================== - | TEST: SET VALUE: IS DUPLICATE: STAYS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a duplicate topic to a and confirms that value of is false. - /// - [Fact] - public void SetSetValue_IsDuplicate_StaysDirty() { + } - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); - var related1 = new Topic("Topic", "Page"); - var related2 = new Topic("Topic", "Page"); + /*============================================================================================================================ + | TEST: SET VALUE: IS DUPLICATE: STAYS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a duplicate topic to a and confirms that value of is false. + /// + [Fact] + public void SetSetValue_IsDuplicate_StaysDirty() { - relationships.SetValue("Related", related1); - relationships.SetValue("Related", related2); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); + var related1 = new Topic("Topic", "Page"); + var related2 = new Topic("Topic", "Page"); - Assert.True(relationships.IsDirty()); + relationships.SetValue("Related", related1); + relationships.SetValue("Related", related2); - } + Assert.True(relationships.IsDirty()); - /*========================================================================================================================== - | TEST: REMOVE: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes an existing from a and conirms that the value for - /// returns true. - /// - [Fact] - public void Remove_IsDirty() { + } - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page"); + /*============================================================================================================================ + | TEST: REMOVE: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes an existing from a and conirms that the value for + /// returns true. + /// + [Fact] + public void Remove_IsDirty() { - relationships.SetValue("Related", related); - relationships.MarkClean(); - relationships.Remove("Related", related); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page"); - Assert.True(relationships.IsDirty()); + relationships.SetValue("Related", related); + relationships.MarkClean(); + relationships.Remove("Related", related); - } + Assert.True(relationships.IsDirty()); - /*========================================================================================================================== - | TEST: REMOVE: MISSING TOPIC: IS NOT DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes a non-existent from a and conirms that the value - /// for returns false. - /// - [Fact] - public void Remove_MissingTopic_IsNotDirty() { + } - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page"); + /*============================================================================================================================ + | TEST: REMOVE: MISSING TOPIC: IS NOT DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes a non-existent from a and conirms that the value + /// for returns false. + /// + [Fact] + public void Remove_MissingTopic_IsNotDirty() { - var isSuccessful = relationships.Remove("Related", related); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page"); - Assert.False(isSuccessful); - Assert.False(relationships.IsDirty()); + var isSuccessful = relationships.Remove("Related", related); - } + Assert.False(isSuccessful); + Assert.False(relationships.IsDirty()); - /*========================================================================================================================== - | TEST: REMOVE: MISSING TOPIC: STAYS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes a non-existent from a and conirms that the value - /// for stays true. - /// - [Fact] - public void Remove_MissingTopic_StaysDirty() { + } - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic1", "Page"); - var missing = new Topic("Topic2", "Page"); + /*============================================================================================================================ + | TEST: REMOVE: MISSING TOPIC: STAYS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes a non-existent from a and conirms that the value + /// for stays true. + /// + [Fact] + public void Remove_MissingTopic_StaysDirty() { - relationships.SetValue("Related", related); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic1", "Page"); + var missing = new Topic("Topic2", "Page"); - var isSuccessful = relationships.Remove("Related", missing); + relationships.SetValue("Related", related); - Assert.False(isSuccessful); - Assert.True(relationships.IsDirty()); + var isSuccessful = relationships.Remove("Related", missing); - } + Assert.False(isSuccessful); + Assert.True(relationships.IsDirty()); - /*========================================================================================================================== - | TEST: CLEAR: EXISTING TOPICS: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Call and confirms that value of is true. - /// - [Fact] - public void Clear_ExistingTopics_IsDirty() { + } - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page"); + /*============================================================================================================================ + | TEST: CLEAR: EXISTING TOPICS: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Call and confirms that value of is true. + /// + [Fact] + public void Clear_ExistingTopics_IsDirty() { - relationships.SetValue("Related", related); - relationships.MarkClean(); - relationships.Clear("Related"); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page"); - Assert.True(relationships.IsDirty()); + relationships.SetValue("Related", related); + relationships.MarkClean(); + relationships.Clear("Related"); - } + Assert.True(relationships.IsDirty()); + + } - /*========================================================================================================================== - | TEST: CLEAR: NO TOPICS: IS NOT DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Call with no existing s and confirms that the - /// value of is set to false. - /// - [Fact] - public void Clear_NoTopics_IsNotDirty() { + /*============================================================================================================================ + | TEST: CLEAR: NO TOPICS: IS NOT DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Call with no existing s and confirms that the + /// value of is set to false. + /// + [Fact] + public void Clear_NoTopics_IsNotDirty() { - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); - relationships.Clear("Related"); + relationships.Clear("Related"); - Assert.False(relationships.IsDirty()); + Assert.False(relationships.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: SET VALUE: MARK NOT DIRTY: IS NOT DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an existing to a and confirms that returns false if is called with the markDirty parameter set to false. - /// - [Fact] - public void SetValue_MarkNotDirty_IsNotDirty() { + /*============================================================================================================================ + | TEST: SET VALUE: MARK NOT DIRTY: IS NOT DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an existing to a and confirms that returns false if is called with the markDirty parameter set to false. + /// + [Fact] + public void SetValue_MarkNotDirty_IsNotDirty() { - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page", null, 2); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page", null, 2); - relationships.SetValue("Related", related, false); + relationships.SetValue("Related", related, false); - Assert.False(relationships.IsDirty()); + Assert.False(relationships.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: SET VALUE: NEW PARENT: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an existing to a associated with a and confirms that returns true - /// even if is called with the - /// markDirty parameter set to false. - /// - [Fact] - public void SetValue_NewParent_IsDirty() { + /*============================================================================================================================ + | TEST: SET VALUE: NEW PARENT: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an existing to a associated with a and confirms that returns true + /// even if is called with the + /// markDirty parameter set to false. + /// + [Fact] + public void SetValue_NewParent_IsDirty() { - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page", null, 1); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page", null, 1); - relationships.SetValue("Related", related, false); + relationships.SetValue("Related", related, false); - Assert.True(relationships.IsDirty()); + Assert.True(relationships.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: SET VALUE: NEW TOPIC: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a new to a associated with an existing and confirms that returns true even if is called with the markDirty parameter - /// set to false. - /// - [Fact] - public void SetValue_NewTopic_IsDirty() { + /*============================================================================================================================ + | TEST: SET VALUE: NEW TOPIC: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a new to a associated with an existing and confirms that returns true even if is called with the markDirty parameter + /// set to false. + /// + [Fact] + public void SetValue_NewTopic_IsDirty() { - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page"); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page"); - relationships.SetValue("Related", related, false); + relationships.SetValue("Related", related, false); - Assert.True(relationships.IsDirty()); + Assert.True(relationships.IsDirty()); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: MARK CLEAN: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an to a associated with a . - /// Confirms that returns false after calling . - /// - [Fact] - public void IsDirty_MarkClean_ReturnsFalse() { + /*============================================================================================================================ + | TEST: IS DIRTY: MARK CLEAN: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an to a associated with a . + /// Confirms that returns false after calling . + /// + [Fact] + public void IsDirty_MarkClean_ReturnsFalse() { - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page", null, 2); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page", null, 2); - relationships.SetValue("Related", related); + relationships.SetValue("Related", related); - relationships.MarkClean("Related"); + relationships.MarkClean("Related"); - Assert.False(relationships.IsDirty()); - Assert.False(relationships.IsDirty("Related")); + Assert.False(relationships.IsDirty()); + Assert.False(relationships.IsDirty("Related")); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: MARK CLEAN: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an to a associated with a that is - /// . Confirms that returns true even - /// after calling since new topics cannot be clean. - /// - [Fact] - public void IsDirty_MarkClean_ReturnsTrue() { + /*============================================================================================================================ + | TEST: IS DIRTY: MARK CLEAN: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an to a associated with a that is + /// . Confirms that returns true even + /// after calling since new topics cannot be clean. + /// + [Fact] + public void IsDirty_MarkClean_ReturnsTrue() { - var topic = new Topic("Test", "Page"); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page", null, 2); + var topic = new Topic("Test", "Page"); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page", null, 2); - relationships.SetValue("Related", related, false); + relationships.SetValue("Related", related, false); - relationships.MarkClean(); - relationships.MarkClean("Related"); + relationships.MarkClean(); + relationships.MarkClean("Related"); - Assert.True(relationships.IsDirty()); - Assert.True(relationships.IsDirty("Related")); + Assert.True(relationships.IsDirty()); + Assert.True(relationships.IsDirty("Related")); - } + } - /*========================================================================================================================== - | TEST: IS DIRTY: MARK CLEAN WITH NEW TOPIC: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds an to a associated with a . - /// Confirms that returns true even after calling if any of the s in the are marked as . - /// - [Fact] - public void IsDirty_MarkCleanWithNewTopic_ReturnsTrue() { + /*============================================================================================================================ + | TEST: IS DIRTY: MARK CLEAN WITH NEW TOPIC: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds an to a associated with a . + /// Confirms that returns true even after calling if any of the s in the are marked as . + /// + [Fact] + public void IsDirty_MarkCleanWithNewTopic_ReturnsTrue() { - var topic = new Topic("Test", "Page", null, 1); - var relationships = new TopicRelationshipMultiMap(topic); - var related = new Topic("Topic", "Page"); + var topic = new Topic("Test", "Page", null, 1); + var relationships = new TopicRelationshipMultiMap(topic); + var related = new Topic("Topic", "Page"); - relationships.SetValue("Related", related, false); + relationships.SetValue("Related", related, false); - relationships.MarkClean(); - relationships.MarkClean("Related"); + relationships.MarkClean(); + relationships.MarkClean("Related"); - Assert.True(relationships.IsDirty()); - Assert.True(relationships.IsDirty("Related")); + Assert.True(relationships.IsDirty()); + Assert.True(relationships.IsDirty("Related")); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TopicRepositoryBaseTest.cs b/OnTopic.Tests/TopicRepositoryBaseTest.cs index 300b9324..efa9b764 100644 --- a/OnTopic.Tests/TopicRepositoryBaseTest.cs +++ b/OnTopic.Tests/TopicRepositoryBaseTest.cs @@ -11,1143 +11,1142 @@ using OnTopic.TestDoubles.Metadata; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC REPOSITORY BASE TESTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +/// +/// These tests evaluate features that are specific to the class. +/// +[ExcludeFromCodeCoverage] +public class TopicRepositoryBaseTest { /*============================================================================================================================ - | CLASS: TOPIC REPOSITORY BASE TESTS + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly StubTopicRepository _topicRepository; + readonly CachedTopicRepository _cachedTopicRepository; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Initializes a new instance of the with shared resources. /// /// - /// These tests evaluate features that are specific to the class. + /// This uses the to provide data, and then to + /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a + /// relatively lightweight façade to any , and prevents the need to duplicate logic for + /// crawling the object graph. /// - [ExcludeFromCodeCoverage] - public class TopicRepositoryBaseTest { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly StubTopicRepository _topicRepository; - readonly CachedTopicRepository _cachedTopicRepository; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This uses the to provide data, and then to - /// manage the in-memory representation of the data. While this introduces some overhead to the tests, the latter is a - /// relatively lightweight façade to any , and prevents the need to duplicate logic for - /// crawling the object graph. - /// - public TopicRepositoryBaseTest() { - _topicRepository = new StubTopicRepository(); - _cachedTopicRepository = new CachedTopicRepository(_topicRepository); - } + public TopicRepositoryBaseTest() { + _topicRepository = new StubTopicRepository(); + _cachedTopicRepository = new CachedTopicRepository(_topicRepository); + } - /*========================================================================================================================== - | TEST: LOAD: VALID TOPIC ID: RETURNS EXPECTED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a valid and - /// confirms that the expected topic is returned. - /// - [Fact] - public void Load_ValidTopicId_ReturnsExpectedTopic() { + /*============================================================================================================================ + | TEST: LOAD: VALID TOPIC ID: RETURNS EXPECTED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a valid and + /// confirms that the expected topic is returned. + /// + [Fact] + public void Load_ValidTopicId_ReturnsExpectedTopic() { - var topic = _topicRepository.Load(11111); + var topic = _topicRepository.Load(11111); - Assert.Equal(11111, topic?.Id); + Assert.Equal(11111, topic?.Id); - } + } - /*========================================================================================================================== - | TEST: LOAD: INVALID TOPIC ID: RETURNS EXPECTED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with an invalid and - /// confirms that no topic is returned. - /// - [Fact] - public void Load_InvalidTopicId_ReturnsExpectedTopic() => - Assert.Null(_topicRepository.Load(11113)); - - /*========================================================================================================================== - | TEST: LOAD: NEGATIVE TOPIC ID: RETURNS ROOT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a negative and - /// confirms that the root topic is returned. - /// - [Fact] - public void Load_NegativeTopicId_ReturnsRootTopic() => - Assert.Equal("Root", _cachedTopicRepository.Load(-2)?.GetUniqueKey()); - - /*========================================================================================================================== - | TEST: LOAD: VALID DATE: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a valid date and ensures that topic - /// with that date is returned. - /// - [Fact] - public void Load_ValidDate_ReturnsTopic() { - - var version = DateTime.UtcNow.AddDays(-1); - var topic = _cachedTopicRepository.Load(11111, version); - - Assert.True(topic?.VersionHistory.Contains(version)); - Assert.Equal(version.AddTicks(-(version.Ticks % TimeSpan.TicksPerSecond)), topic?.LastModified); + /*============================================================================================================================ + | TEST: LOAD: INVALID TOPIC ID: RETURNS EXPECTED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with an invalid and + /// confirms that no topic is returned. + /// + [Fact] + public void Load_InvalidTopicId_ReturnsExpectedTopic() => + Assert.Null(_topicRepository.Load(11113)); - } + /*============================================================================================================================ + | TEST: LOAD: NEGATIVE TOPIC ID: RETURNS ROOT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a negative and + /// confirms that the root topic is returned. + /// + [Fact] + public void Load_NegativeTopicId_ReturnsRootTopic() => + Assert.Equal("Root", _cachedTopicRepository.Load(-2)?.GetUniqueKey()); - /*========================================================================================================================== - | TEST: ROLLBACK: TOPIC: UPDATES LAST MODIFIED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a valid date and ensures that the value is updated. - /// - [Fact] - public void Rollback_Topic_UpdatesLastModified() { + /*============================================================================================================================ + | TEST: LOAD: VALID DATE: RETURNS TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a valid date and ensures that topic + /// with that date is returned. + /// + [Fact] + public void Load_ValidDate_ReturnsTopic() { - var version = DateTime.UtcNow.AddDays(-1); - var topic = _topicRepository.Load(11111); + var version = DateTime.UtcNow.AddDays(-1); + var topic = _cachedTopicRepository.Load(11111, version); - if (topic is not null) { - topic.VersionHistory.Add(version); - _topicRepository.Rollback(topic, version); - } + Assert.True(topic?.VersionHistory.Contains(version)); + Assert.Equal(version.AddTicks(-(version.Ticks % TimeSpan.TicksPerSecond)), topic?.LastModified); - Assert.True(topic?.VersionHistory.Contains(version)); - Assert.Equal(version.AddTicks(-(version.Ticks % TimeSpan.TicksPerSecond)), topic?.LastModified); + } - } + /*============================================================================================================================ + | TEST: ROLLBACK: TOPIC: UPDATES LAST MODIFIED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a valid date and ensures that the value is updated. + /// + [Fact] + public void Rollback_Topic_UpdatesLastModified() { - /*========================================================================================================================== - | TEST: LOAD: FUTURE DATE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a future and - /// confirms that an exception is thrown. - /// - [Fact] - public void Load_FutureDate_ThrowsException() => - Assert.Throws(() => - _cachedTopicRepository.Load(1111, DateTime.UtcNow.AddDays(1)) - ); - - /*========================================================================================================================== - | TEST: LOAD: OLD DATE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls with a date prior to versioning being - /// introduced and ensures that an exception is thrown. - /// - [Fact] - public void Load_OldDate_ThrowsException() => - Assert.Throws(() => - _cachedTopicRepository.Load(1111, new DateTime(2010, 10, 15)) - ); - - /*========================================================================================================================== - | TEST: DELETE: BASE TOPIC: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic which other topics, outside of the graph, derive from. Expects exception. - /// - [Fact] - public void Delete_BaseTopic_ThrowsException() { - - var root = new Topic("Root", "Page"); - var topic = new Topic("Topic", "Page", root); - var child = new Topic("Child", "Page", topic); - var derivedTopic = new Topic("Derived", "Page", root) { - BaseTopic = child - }; - - Assert.Throws(() => - _topicRepository.Delete(topic, true) - ); + var version = DateTime.UtcNow.AddDays(-1); + var topic = _topicRepository.Load(11111); + if (topic is not null) { + topic.VersionHistory.Add(version); + _topicRepository.Rollback(topic, version); } - /*========================================================================================================================== - | TEST: DELETE: INTERNAL DERIVED TOPIC: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic which another topic within the graph derives from. Expects success. - /// - [Fact] - public void Delete_InternallyDerivedTopic_Succeeds() { + Assert.True(topic?.VersionHistory.Contains(version)); + Assert.Equal(version.AddTicks(-(version.Ticks % TimeSpan.TicksPerSecond)), topic?.LastModified); - var root = new Topic("Root", "Page"); - var topic = new Topic("Topic", "Page", root); - var child = new Topic("Child", "Page", topic); - _ = new Topic("Derived", "Page", topic) { - BaseTopic = child - }; + } - _topicRepository.Delete(topic, true); + /*============================================================================================================================ + | TEST: LOAD: FUTURE DATE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a future and + /// confirms that an exception is thrown. + /// + [Fact] + public void Load_FutureDate_ThrowsException() => + Assert.Throws(() => + _cachedTopicRepository.Load(1111, DateTime.UtcNow.AddDays(1)) + ); - Assert.Empty(root.Children); + /*============================================================================================================================ + | TEST: LOAD: OLD DATE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls with a date prior to versioning being + /// introduced and ensures that an exception is thrown. + /// + [Fact] + public void Load_OldDate_ThrowsException() => + Assert.Throws(() => + _cachedTopicRepository.Load(1111, new DateTime(2010, 10, 15)) + ); - } + /*============================================================================================================================ + | TEST: DELETE: BASE TOPIC: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic which other topics, outside of the graph, derive from. Expects exception. + /// + [Fact] + public void Delete_BaseTopic_ThrowsException() { - /*========================================================================================================================== - | TEST: DELETE: DESCENDANTS: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic with descendant topics. Expects exception if isRecursive is set to false. - /// - [Fact] - public void Delete_Descendants_ThrowsException() { + var root = new Topic("Root", "Page"); + var topic = new Topic("Topic", "Page", root); + var child = new Topic("Child", "Page", topic); + var derivedTopic = new Topic("Derived", "Page", root) { + BaseTopic = child + }; - var topic = new Topic("Topic", "Page"); - _ = new Topic("Child", "Page", topic); + Assert.Throws(() => + _topicRepository.Delete(topic, true) + ); - Assert.Throws(() => - _topicRepository.Delete(topic, false) - ); + } - } + /*============================================================================================================================ + | TEST: DELETE: INTERNAL DERIVED TOPIC: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic which another topic within the graph derives from. Expects success. + /// + [Fact] + public void Delete_InternallyDerivedTopic_Succeeds() { - /*========================================================================================================================== - | TEST: DELETE: DESCENDANTS WITH RECURSIVE: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic with descendant topics. Expects no exception if isRecursive is set to true. - /// - [Fact] - public void Delete_DescendantsWithRecursive_Succeeds() { + var root = new Topic("Root", "Page"); + var topic = new Topic("Topic", "Page", root); + var child = new Topic("Child", "Page", topic); + _ = new Topic("Derived", "Page", topic) { + BaseTopic = child + }; - var root = new Topic("Root", "Page"); - var topic = new Topic("Topic", "Page", root); - _ = new Topic("Child", "Page", topic); + _topicRepository.Delete(topic, true); - _topicRepository.Delete(topic, true); + Assert.Empty(root.Children); - Assert.Empty(root.Children); + } - } + /*============================================================================================================================ + | TEST: DELETE: DESCENDANTS: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic with descendant topics. Expects exception if isRecursive is set to false. + /// + [Fact] + public void Delete_Descendants_ThrowsException() { - /*========================================================================================================================== - | TEST: DELETE: NESTED TOPICS: SUCCEEDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic with nested topics. Expects no exception, even if isRecursive is set to false. - /// - [Fact] - public void Delete_NestedTopics_Succeeds() { + var topic = new Topic("Topic", "Page"); + _ = new Topic("Child", "Page", topic); - var root = new Topic("Root", "Page"); - var topic = new Topic("Topic", "Page", root); - _ = new Topic("Child", "List", topic); + Assert.Throws(() => + _topicRepository.Delete(topic, false) + ); - _topicRepository.Delete(topic, false); + } - Assert.Empty(root.Children); + /*============================================================================================================================ + | TEST: DELETE: DESCENDANTS WITH RECURSIVE: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic with descendant topics. Expects no exception if isRecursive is set to true. + /// + [Fact] + public void Delete_DescendantsWithRecursive_Succeeds() { - } + var root = new Topic("Root", "Page"); + var topic = new Topic("Topic", "Page", root); + _ = new Topic("Child", "Page", topic); - /*========================================================================================================================== - | TEST: DELETE: ASSOCIATIONS: DELETE ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic with outgoing relationships and topic references. Additionally, deletes those associations from the - /// target topics' collection. - /// - [Fact] - public void Delete_Relationships_DeleteRelationships() { + _topicRepository.Delete(topic, true); - var root = new Topic("Root", "Page"); - var topic = new Topic("Topic", "Page", root); - var child = new Topic("Child", "Page", topic); - var associated = new Topic("Associated", "Page", root); + Assert.Empty(root.Children); - child.Relationships.SetValue("Related", associated); - child.References.SetValue("Referenced", associated); + } - _topicRepository.Delete(topic, true); + /*============================================================================================================================ + | TEST: DELETE: NESTED TOPICS: SUCCEEDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic with nested topics. Expects no exception, even if isRecursive is set to false. + /// + [Fact] + public void Delete_NestedTopics_Succeeds() { - Assert.Empty(associated.IncomingRelationships.GetValues("Related")); - Assert.Empty(associated.IncomingRelationships.GetValues("Referenced")); + var root = new Topic("Root", "Page"); + var topic = new Topic("Topic", "Page", root); + _ = new Topic("Child", "List", topic); - } + _topicRepository.Delete(topic, false); - /*========================================================================================================================== - | TEST: DELETE: INCOMING RELATIONSHIPS: DELETE ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes a topic with incoming relationships. Deletes the relationships or references from the associated topic. - /// - [Fact] - public void Delete_IncomingRelationships_DeleteAssociations() { + Assert.Empty(root.Children); - var root = new Topic("Root", "Page"); - var topic = new Topic("Topic", "Page", root); - var child = new Topic("Child", "Page", topic); - var source1 = new Topic("Source1", "Page", root); - var source2 = new Topic("Source2", "Page", root); + } - source1.Relationships.SetValue("Associations", child); - source2.References.SetValue("Associations", child); + /*============================================================================================================================ + | TEST: DELETE: ASSOCIATIONS: DELETE ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic with outgoing relationships and topic references. Additionally, deletes those associations from the + /// target topics' collection. + /// + [Fact] + public void Delete_Relationships_DeleteRelationships() { - _topicRepository.Delete(topic, true); + var root = new Topic("Root", "Page"); + var topic = new Topic("Topic", "Page", root); + var child = new Topic("Child", "Page", topic); + var associated = new Topic("Associated", "Page", root); - Assert.Empty(source1.Relationships.GetValues("Associations")); + child.Relationships.SetValue("Related", associated); + child.References.SetValue("Referenced", associated); - } + _topicRepository.Delete(topic, true); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: ANY ATTRIBUTES: RETURNS ALL ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, without any filtering by whether or not the attribute is an . - /// - [Fact] - public void GetAttributes_AnyAttributes_ReturnsAllAttributes() { + Assert.Empty(associated.IncomingRelationships.GetValues("Related")); + Assert.Empty(associated.IncomingRelationships.GetValues("Referenced")); - var topic = new Topic("Test", "ContentTypes"); + } - topic.Attributes.SetValue("Title", "Title"); + /*============================================================================================================================ + | TEST: DELETE: INCOMING RELATIONSHIPS: DELETE ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Deletes a topic with incoming relationships. Deletes the relationships or references from the associated topic. + /// + [Fact] + public void Delete_IncomingRelationships_DeleteAssociations() { - var attributes = _topicRepository.GetAttributesProxy(topic, null); + var root = new Topic("Root", "Page"); + var topic = new Topic("Topic", "Page", root); + var child = new Topic("Child", "Page", topic); + var source1 = new Topic("Source1", "Page", root); + var source2 = new Topic("Source2", "Page", root); - Assert.Single(attributes); + source1.Relationships.SetValue("Associations", child); + source2.References.SetValue("Associations", child); - } + _topicRepository.Delete(topic, true); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: EMPTY ATTRIBUTES: SKIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, without any filtering by whether or not the attribute is an . Any s with a null or empty value should - /// be skipped. - /// - [Fact] - public void GetAttributes_EmptyAttributes_Skips() { + Assert.Empty(source1.Relationships.GetValues("Associations")); - var topic = new Topic("Test", "ContentTypes"); + } - topic.Attributes.SetValue("EmptyAttribute", ""); - topic.Attributes.SetValue("NullAttribute", null); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: ANY ATTRIBUTES: RETURNS ALL ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, without any filtering by whether or not the attribute is an . + /// + [Fact] + public void GetAttributes_AnyAttributes_ReturnsAllAttributes() { - var attributes = _topicRepository.GetAttributesProxy(topic, null); + var topic = new Topic("Test", "ContentTypes"); - Assert.DoesNotContain(attributes, a => a.Key is "EmptyAttribute"); - Assert.DoesNotContain(attributes, a => a.Key is "NullAttribute"); + topic.Attributes.SetValue("Title", "Title"); - } + var attributes = _topicRepository.GetAttributesProxy(topic, null); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: INDEXED ATTRIBUTES: RETURNS INDEXED ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, filtering by . - /// - [Fact] - public void GetAttributes_IndexedAttributes_ReturnsIndexedAttributes() { + Assert.Single(attributes); - var topic = new Topic("Test", "ContentTypes"); + } - topic.Attributes.SetValue("Title", "Title"); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: EMPTY ATTRIBUTES: SKIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, without any filtering by whether or not the attribute is an . Any s with a null or empty value should + /// be skipped. + /// + [Fact] + public void GetAttributes_EmptyAttributes_Skips() { - var attributes = _topicRepository.GetAttributesProxy(topic, false); + var topic = new Topic("Test", "ContentTypes"); - Assert.Empty(attributes); + topic.Attributes.SetValue("EmptyAttribute", ""); + topic.Attributes.SetValue("NullAttribute", null); - } + var attributes = _topicRepository.GetAttributesProxy(topic, null); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: EXTENDED ATTRIBUTES: RETURNS EXTENDED ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, filtering by . - /// - [Fact] - public void GetAttributes_ExtendedAttributes_ReturnsExtendedAttributes() { + Assert.DoesNotContain(attributes, a => a.Key is "EmptyAttribute"); + Assert.DoesNotContain(attributes, a => a.Key is "NullAttribute"); - var topic = new Topic("Test", "ContentTypes"); + } - topic.Attributes.SetValue("Title", "Title"); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: INDEXED ATTRIBUTES: RETURNS INDEXED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, filtering by . + /// + [Fact] + public void GetAttributes_IndexedAttributes_ReturnsIndexedAttributes() { - var attributes = _topicRepository.GetAttributesProxy(topic, true); + var topic = new Topic("Test", "ContentTypes"); - Assert.Single(attributes); + topic.Attributes.SetValue("Title", "Title"); - } + var attributes = _topicRepository.GetAttributesProxy(topic, false); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: EXTENDED ATTRIBUTE MISMATCH: RETURNS EXTENDED ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, filtering by . Expects an to be returned even if it's not but its - /// disagrees with . - /// - [Fact] - public void GetAttributes_ExtendedAttributeMismatch_ReturnsExtendedAttributes() { - - var topic = new Topic("Test", "Page", null, 1); - - topic.Attributes.SetValue("Title", "Title", markDirty: false, isExtendedAttribute: false); - topic.Attributes.SetValue("IsHidden", "0", markDirty: false, isExtendedAttribute: true); - topic.Attributes.SetValue("MetaTitle", "Metatitle", markDirty: false, isExtendedAttribute: null); - topic.Attributes.SetValue("Arbitrary", "Value", markDirty: false, isExtendedAttribute: true); - - var dirtyExtended = _topicRepository.GetAttributesProxy(topic, true, true); - var dirtyIndexed = _topicRepository.GetAttributesProxy(topic, false, true); - var cleanExtended = _topicRepository.GetAttributesProxy(topic, true, false); - var cleanIndexed = _topicRepository.GetAttributesProxy(topic, false, false); - - //Expect Title, even though it isn't IsDirty - Assert.Single(dirtyExtended); - Assert.Equal("Title", dirtyExtended.FirstOrDefault()?.Key); - - //Expect IsHidden, even though it isn't IsDirty - Assert.Single(dirtyIndexed); - Assert.Equal("IsHidden", dirtyIndexed.FirstOrDefault()?.Key); - - //Expect Metatitle, since it's clean, and not mismatched - Assert.Single(cleanExtended); - Assert.Equal("MetaTitle", cleanExtended.FirstOrDefault()?.Key); - - //Expect Arbitrary, since it's arbitrary and it's length is less than 255 - Assert.Single(cleanIndexed); - Assert.Equal("Arbitrary", cleanIndexed.FirstOrDefault()?.Key); + Assert.Empty(attributes); - } + } - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: EXTENDED ATTRIBUTE MISMATCH: RETURNS NOTHING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, filtering by . Expects the to not be returned even though its - /// disagrees with , since it won't match the 's isExtendedAttribute call. - /// - [Fact] - public void GetAttributes_ExtendedAttributeMismatch_ReturnsNothing() { + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: EXTENDED ATTRIBUTES: RETURNS EXTENDED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, filtering by . + /// + [Fact] + public void GetAttributes_ExtendedAttributes_ReturnsExtendedAttributes() { - var topic = new Topic("Test", "ContentTypes"); + var topic = new Topic("Test", "ContentTypes"); - topic.Attributes.SetValue("Title", "Title", markDirty: false, isExtendedAttribute: false); + topic.Attributes.SetValue("Title", "Title"); - var attributes = _topicRepository.GetAttributesProxy(topic, false, true); + var attributes = _topicRepository.GetAttributesProxy(topic, true); - Assert.Empty(attributes); + Assert.Single(attributes); - } + } - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: EXCLUDE LAST MODIFIED: RETURNS OTHER ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of attributes from a topic, filtering by excludeLastModified. Confirms that s are not returned which start with LastModified. - /// - [Fact] - public void GetAttributes_ExcludeLastModified_ReturnsOtherAttributes() { + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: EXTENDED ATTRIBUTE MISMATCH: RETURNS EXTENDED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, filtering by . Expects an to be returned even if it's not but its + /// disagrees with . + /// + [Fact] + public void GetAttributes_ExtendedAttributeMismatch_ReturnsExtendedAttributes() { - var topic = new Topic("Test", "ContentTypes"); + var topic = new Topic("Test", "Page", null, 1); - topic.Attributes.SetDateTime("LastModified", DateTime.Now); - topic.Attributes.SetValue("LastModifiedBy", "Unit Tests"); + topic.Attributes.SetValue("Title", "Title", markDirty: false, isExtendedAttribute: false); + topic.Attributes.SetValue("IsHidden", "0", markDirty: false, isExtendedAttribute: true); + topic.Attributes.SetValue("MetaTitle", "Metatitle", markDirty: false, isExtendedAttribute: null); + topic.Attributes.SetValue("Arbitrary", "Value", markDirty: false, isExtendedAttribute: true); - var attributes = _topicRepository.GetAttributesProxy(topic, null, excludeLastModified: true); + var dirtyExtended = _topicRepository.GetAttributesProxy(topic, true, true); + var dirtyIndexed = _topicRepository.GetAttributesProxy(topic, false, true); + var cleanExtended = _topicRepository.GetAttributesProxy(topic, true, false); + var cleanIndexed = _topicRepository.GetAttributesProxy(topic, false, false); - Assert.Empty(attributes); + //Expect Title, even though it isn't IsDirty + Assert.Single(dirtyExtended); + Assert.Equal("Title", dirtyExtended.FirstOrDefault()?.Key); - } + //Expect IsHidden, even though it isn't IsDirty + Assert.Single(dirtyIndexed); + Assert.Equal("IsHidden", dirtyIndexed.FirstOrDefault()?.Key); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: ARBITRARY ATTRIBUTE WITH SHORT VALUE: RETURNS AS INDEXED ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets an arbitrary (unmatched) attribute on a with a value shorter than 255 characters, then - /// ensures that it is returned as an an indexed when calling . - /// - [Fact] - public void GetAttributes_ArbitraryAttributeWithShortValue_ReturnsAsIndexedAttributes() { + //Expect Metatitle, since it's clean, and not mismatched + Assert.Single(cleanExtended); + Assert.Equal("MetaTitle", cleanExtended.FirstOrDefault()?.Key); - var topic = new Topic("Test", "ContentTypes"); + //Expect Arbitrary, since it's arbitrary and it's length is less than 255 + Assert.Single(cleanIndexed); + Assert.Equal("Arbitrary", cleanIndexed.FirstOrDefault()?.Key); - topic.Attributes.SetValue("ArbitraryAttribute", "Value"); + } - var attributes = _topicRepository.GetAttributesProxy(topic, false); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: EXTENDED ATTRIBUTE MISMATCH: RETURNS NOTHING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, filtering by . Expects the to not be returned even though its + /// disagrees with , since it won't match the 's isExtendedAttribute call. + /// + [Fact] + public void GetAttributes_ExtendedAttributeMismatch_ReturnsNothing() { - Assert.Contains(attributes, a => a.Key is "ArbitraryAttribute"); + var topic = new Topic("Test", "ContentTypes"); - } + topic.Attributes.SetValue("Title", "Title", markDirty: false, isExtendedAttribute: false); - /*========================================================================================================================== - | TEST: GET ATTRIBUTES: ARBITRARY ATTRIBUTE WITH LONG VALUE: RETURNS AS EXTENDED ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets an arbitrary (unmatched) attribute on a with a value longer than 255 characters, then - /// ensures that it is returned as an an when calling . - /// - [Fact] - public void GetAttributes_ArbitraryAttributeWithLongValue_ReturnsAsExtendedAttributes() { + var attributes = _topicRepository.GetAttributesProxy(topic, false, true); - var topic = new Topic("Test", "ContentTypes"); + Assert.Empty(attributes); - topic.Attributes.SetValue("ArbitraryAttribute", new string('x', 256)); + } - var attributes = _topicRepository.GetAttributesProxy(topic, true); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: EXCLUDE LAST MODIFIED: RETURNS OTHER ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of attributes from a topic, filtering by excludeLastModified. Confirms that s are not returned which start with LastModified. + /// + [Fact] + public void GetAttributes_ExcludeLastModified_ReturnsOtherAttributes() { - Assert.Contains(attributes, a => a.Key is "ArbitraryAttribute"); + var topic = new Topic("Test", "ContentTypes"); - } + topic.Attributes.SetDateTime("LastModified", DateTime.Now); + topic.Attributes.SetValue("LastModifiedBy", "Unit Tests"); - /*========================================================================================================================== - | TEST: GET UNMATCHED ATTRIBUTES: RETURNS ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Using , ensures that any attributes that exist on the - /// but not the are returned. - /// - [Fact] - public void GetUnmatchedAttributes_ReturnsAttributes() { + var attributes = _topicRepository.GetAttributesProxy(topic, null, excludeLastModified: true); - var topic = new Topic("Test", "Page", null, 1); + Assert.Empty(attributes); - topic.Attributes.SetValue("Title", "Title"); + } - var attributes = _topicRepository.GetUnmatchedAttributesProxy(topic); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: ARBITRARY ATTRIBUTE WITH SHORT VALUE: RETURNS AS INDEXED ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets an arbitrary (unmatched) attribute on a with a value shorter than 255 characters, then + /// ensures that it is returned as an an indexed when calling . + /// + [Fact] + public void GetAttributes_ArbitraryAttributeWithShortValue_ReturnsAsIndexedAttributes() { - Assert.True(attributes.Any()); - Assert.DoesNotContain(attributes, a => a.Key is "Title"); + var topic = new Topic("Test", "ContentTypes"); - } + topic.Attributes.SetValue("ArbitraryAttribute", "Value"); - /*========================================================================================================================== - | TEST: GET UNMATCHED ATTRIBUTES: EMPTY ARBITRARY ATTRIBUTES: RETURNS ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Using , ensures that any attributes that exist on the - /// but not the and are either null or empty are - /// returned. This ensures that arbitrary attributes can be deleted programmatically, instead of lingering as orphans in - /// the database. - /// - [Fact] - public void GetUnmatchedAttributes_EmptyArbitraryAttributes_ReturnsAttributes() { + var attributes = _topicRepository.GetAttributesProxy(topic, false); - var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor", null, 1); + Assert.Contains(attributes, a => a.Key is "ArbitraryAttribute"); - topic.Attributes.SetValue("ArbitraryAttribute", "Value"); - topic.Attributes.SetValue("ArbitraryAttribute", ""); - topic.Attributes.SetValue("AnotherArbitraryAttribute", "Value"); - topic.Attributes.SetValue("YetAnotherArbitraryAttribute", "Value"); - topic.Attributes.SetValue("YetAnotherArbitraryAttribute", null); + } - var attributes = _topicRepository.GetUnmatchedAttributesProxy(topic); + /*============================================================================================================================ + | TEST: GET ATTRIBUTES: ARBITRARY ATTRIBUTE WITH LONG VALUE: RETURNS AS EXTENDED ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets an arbitrary (unmatched) attribute on a with a value longer than 255 characters, then + /// ensures that it is returned as an an when calling . + /// + [Fact] + public void GetAttributes_ArbitraryAttributeWithLongValue_ReturnsAsExtendedAttributes() { - Assert.Contains(attributes, a => a.Key is "ArbitraryAttribute"); - Assert.Contains(attributes, a => a.Key is "YetAnotherArbitraryAttribute"); - Assert.DoesNotContain(attributes, a => a.Key is "AnotherArbitraryAttribute"); + var topic = new Topic("Test", "ContentTypes"); - } + topic.Attributes.SetValue("ArbitraryAttribute", new string('x', 256)); - /*========================================================================================================================== - | TEST: GET CONTENT TYPE DESCRIPTORS: RETURNS CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of s from the and ensures that - /// the expected number (2) are present. - /// - [Fact] - public void GetContentTypeDescriptors_ReturnsContentTypes() { + var attributes = _topicRepository.GetAttributesProxy(topic, true); - var contentTypes = _topicRepository.GetContentTypeDescriptors(); + Assert.Contains(attributes, a => a.Key is "ArbitraryAttribute"); - Assert.Equal(15, contentTypes.Count); - Assert.NotNull(contentTypes.GetValue("ContentTypeDescriptor")); - Assert.NotNull(contentTypes.GetValue("Page")); - Assert.NotNull(contentTypes.GetValue("LookupListItem")); + } - } + /*============================================================================================================================ + | TEST: GET UNMATCHED ATTRIBUTES: RETURNS ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Using , ensures that any attributes that exist on the + /// but not the are returned. + /// + [Fact] + public void GetUnmatchedAttributes_ReturnsAttributes() { - /*========================================================================================================================== - | TEST: GET CONTENT TYPE DESCRIPTORS: WITH TOPIC GRAPH: RETURNS MERGED CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of s from the alongside a separate - /// topic graph and ensures the two are properly merged. - /// - [Fact] - public void GetContentTypeDescriptors_WithTopicGraph_ReturnsMergedContentTypes() { + var topic = new Topic("Test", "Page", null, 1); - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var rootContentType = contentTypes["ContentTypes"]; - var newContentType = new ContentTypeDescriptor("NewContentType", "ContentTypeDescriptor", rootContentType); - var contentTypeCount = contentTypes.Count; + topic.Attributes.SetValue("Title", "Title"); - _topicRepository.SetContentTypeDescriptorsProxy(rootContentType); + var attributes = _topicRepository.GetUnmatchedAttributesProxy(topic); - Assert.NotEqual(contentTypeCount, contentTypes.Count); - Assert.Contains(newContentType, contentTypes); + Assert.True(attributes.Any()); + Assert.DoesNotContain(attributes, a => a.Key is "Title"); - } + } - /*========================================================================================================================== - | TEST: GET CONTENT TYPE DESCRIPTOR: GET VALID CONTENT TYPE: RETURNS CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to retrieve a specific by its . - /// - [Fact] - public void GetContentTypeDescriptor_GetValidContentType_ReturnsContentType() { + /*============================================================================================================================ + | TEST: GET UNMATCHED ATTRIBUTES: EMPTY ARBITRARY ATTRIBUTES: RETURNS ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Using , ensures that any attributes that exist on the + /// but not the and are either null or empty are + /// returned. This ensures that arbitrary attributes can be deleted programmatically, instead of lingering as orphans in + /// the database. + /// + [Fact] + public void GetUnmatchedAttributes_EmptyArbitraryAttributes_ReturnsAttributes() { - var topic = new Topic("Test", "Page"); - var contentType = _topicRepository.GetContentTypeDescriptorProxy(topic); + var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor", null, 1); - Assert.NotNull(contentType); + topic.Attributes.SetValue("ArbitraryAttribute", "Value"); + topic.Attributes.SetValue("ArbitraryAttribute", ""); + topic.Attributes.SetValue("AnotherArbitraryAttribute", "Value"); + topic.Attributes.SetValue("YetAnotherArbitraryAttribute", "Value"); + topic.Attributes.SetValue("YetAnotherArbitraryAttribute", null); - } + var attributes = _topicRepository.GetUnmatchedAttributesProxy(topic); - /*========================================================================================================================== - | TEST: GET CONTENT TYPE DESCRIPTOR: GET NEW CONTENT TYPE: RETURNS FROM TOPIC GRAPH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to retrieve a that hasn't yet been persisted to the data store. Instead, - /// attempts to retrieve it from the 's graph. - /// - [Fact] - public void GetContentTypeDescriptor_GetNewContentType_ReturnsFromTopicGraph() { + Assert.Contains(attributes, a => a.Key is "ArbitraryAttribute"); + Assert.Contains(attributes, a => a.Key is "YetAnotherArbitraryAttribute"); + Assert.DoesNotContain(attributes, a => a.Key is "AnotherArbitraryAttribute"); - var rootTopic = _topicRepository.Load("Root"); - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var rootContentType = contentTypes.GetValue("ContentTypes"); - var newContentType = new ContentTypeDescriptor("NewContentType", "ContentTypeDescriptor", rootContentType); - var topic = new Topic("Test", "NewContentType", rootTopic); + } - var contentType = _topicRepository.GetContentTypeDescriptorProxy(topic); + /*============================================================================================================================ + | TEST: GET CONTENT TYPE DESCRIPTORS: RETURNS CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of s from the and ensures that + /// the expected number (2) are present. + /// + [Fact] + public void GetContentTypeDescriptors_ReturnsContentTypes() { - Assert.NotNull(contentType); - Assert.Equal(contentType, newContentType); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); - } + Assert.Equal(15, contentTypes.Count); + Assert.NotNull(contentTypes.GetValue("ContentTypeDescriptor")); + Assert.NotNull(contentTypes.GetValue("Page")); + Assert.NotNull(contentTypes.GetValue("LookupListItem")); - /*========================================================================================================================== - | TEST: GET CONTENT TYPE DESCRIPTOR: MISSING ROOT CONTENT ROOT: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to retrieve a when the doesn't contain a - /// root content type at Root:Configuration:ContentTypes. In this case, it should return null. This will - /// typically only occur when initializing a new database, and is an unexpected condition. - /// - [Fact] - public void GetContentTypeDescriptor_MissingRootContentType_ReturnsNull() { + } - var topicRepository = new StubTopicRepository(); - var configuration = topicRepository.Load("Root:Configuration"); - var topic = new Topic("Test", "Page"); + /*============================================================================================================================ + | TEST: GET CONTENT TYPE DESCRIPTORS: WITH TOPIC GRAPH: RETURNS MERGED CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of s from the alongside a separate + /// topic graph and ensures the two are properly merged. + /// + [Fact] + public void GetContentTypeDescriptors_WithTopicGraph_ReturnsMergedContentTypes() { - topicRepository.Delete(configuration!, true); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var rootContentType = contentTypes["ContentTypes"]; + var newContentType = new ContentTypeDescriptor("NewContentType", "ContentTypeDescriptor", rootContentType); + var contentTypeCount = contentTypes.Count; - var contentType = topicRepository.GetContentTypeDescriptorProxy(topic); + _topicRepository.SetContentTypeDescriptorsProxy(rootContentType); - Assert.Null(contentType); + Assert.NotEqual(contentTypeCount, contentTypes.Count); + Assert.Contains(newContentType, contentTypes); - } + } - /*========================================================================================================================== - | TEST: GET CONTENT TYPE DESCRIPTOR: GET INVALID CONTENT TYPE: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to retrieve an invalid . - /// - [Fact] - public void GetContentTypeDescriptor_GetInvalidContentType_ReturnsNull() { + /*============================================================================================================================ + | TEST: GET CONTENT TYPE DESCRIPTOR: GET VALID CONTENT TYPE: RETURNS CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to retrieve a specific by its . + /// + [Fact] + public void GetContentTypeDescriptor_GetValidContentType_ReturnsContentType() { - var topic = new Topic("Test", "InvalidContentType"); - var contentType = _topicRepository.GetContentTypeDescriptorProxy(topic); + var topic = new Topic("Test", "Page"); + var contentType = _topicRepository.GetContentTypeDescriptorProxy(topic); - Assert.Null(contentType); + Assert.NotNull(contentType); - } + } - /*========================================================================================================================== - | TEST: SAVE: CONTENT TYPE DESCRIPTOR: UPDATES CONTENT TYPE CACHE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads the , then saves a new via , and ensures that it is - /// immediately reflected in the cache of s. - /// - [Fact] - public void Save_ContentTypeDescriptor_UpdatesContentTypeCache() { + /*============================================================================================================================ + | TEST: GET CONTENT TYPE DESCRIPTOR: GET NEW CONTENT TYPE: RETURNS FROM TOPIC GRAPH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to retrieve a that hasn't yet been persisted to the data store. Instead, + /// attempts to retrieve it from the 's graph. + /// + [Fact] + public void GetContentTypeDescriptor_GetNewContentType_ReturnsFromTopicGraph() { - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var topic = new ContentTypeDescriptor("NewContentType", "ContentTypeDescriptor"); + var rootTopic = _topicRepository.Load("Root"); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var rootContentType = contentTypes.GetValue("ContentTypes"); + var newContentType = new ContentTypeDescriptor("NewContentType", "ContentTypeDescriptor", rootContentType); + var topic = new Topic("Test", "NewContentType", rootTopic); - _topicRepository.Save(topic); + var contentType = _topicRepository.GetContentTypeDescriptorProxy(topic); - Assert.Contains(topic, contentTypes); + Assert.NotNull(contentType); + Assert.Equal(contentType, newContentType); - } + } - /*========================================================================================================================== - | TEST: SAVE: CONTENT TYPE DESCRIPTOR: UPDATES PERMITTED CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads the , then saves an existing via , and ensures that - /// it the cache is updated. - /// - [Fact] - public void Save_ContentTypeDescriptor_UpdatesPermittedContentTypes() { + /*============================================================================================================================ + | TEST: GET CONTENT TYPE DESCRIPTOR: MISSING ROOT CONTENT ROOT: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to retrieve a when the doesn't contain a + /// root content type at Root:Configuration:ContentTypes. In this case, it should return null. This will + /// typically only occur when initializing a new database, and is an unexpected condition. + /// + [Fact] + public void GetContentTypeDescriptor_MissingRootContentType_ReturnsNull() { - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var contentTypesRoot = contentTypes.GetValue("ContentTypes"); - var pageContentType = contentTypes.GetValue("Page"); - var lookupContentType = contentTypes.GetValue("Lookup"); + var topicRepository = new StubTopicRepository(); + var configuration = topicRepository.Load("Root:Configuration"); + var topic = new Topic("Test", "Page"); - Contract.Assume(pageContentType); - Contract.Assume(lookupContentType); - Contract.Assume(contentTypesRoot); + topicRepository.Delete(configuration!, true); - var initialCount = pageContentType.PermittedContentTypes.Count; + var contentType = topicRepository.GetContentTypeDescriptorProxy(topic); - pageContentType.Relationships.SetValue("ContentTypes", lookupContentType); + Assert.Null(contentType); - _topicRepository.Save(contentTypesRoot, true); + } - Assert.NotEqual(initialCount, pageContentType.PermittedContentTypes.Count); + /*============================================================================================================================ + | TEST: GET CONTENT TYPE DESCRIPTOR: GET INVALID CONTENT TYPE: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to retrieve an invalid . + /// + [Fact] + public void GetContentTypeDescriptor_GetInvalidContentType_ReturnsNull() { - } + var topic = new Topic("Test", "InvalidContentType"); + var contentType = _topicRepository.GetContentTypeDescriptorProxy(topic); - /*========================================================================================================================== - | TEST: SAVE: NEW TOPIC: UPDATES VERSION HISTORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves a new and confirms that the is correctly updated with a - /// new version. - /// - [Fact] - public void Save_NewTopic_UpdatesVersionHistory() { + Assert.Null(contentType); - var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); - var topic = new Topic("Test", "Page", parent); + } - _topicRepository.Save(topic); + /*============================================================================================================================ + | TEST: SAVE: CONTENT TYPE DESCRIPTOR: UPDATES CONTENT TYPE CACHE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads the , then saves a new via , and ensures that it is + /// immediately reflected in the cache of s. + /// + [Fact] + public void Save_ContentTypeDescriptor_UpdatesContentTypeCache() { - Assert.True(topic.VersionHistory.Count > 0); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var topic = new ContentTypeDescriptor("NewContentType", "ContentTypeDescriptor"); - } + _topicRepository.Save(topic); - /*========================================================================================================================== - | TEST: SAVE: IS RECURSIVE: SAVES CHILD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves a new with a child and confirms that the of the - /// child is correctly updated. - /// - [Fact] - public void Save_IsRecursive_SavesChild() { + Assert.Contains(topic, contentTypes); - var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); - var topic = new Topic("Test", "Page", parent); - var child = new Topic("Child", "Page", topic); + } - _topicRepository.Save(topic, true); + /*============================================================================================================================ + | TEST: SAVE: CONTENT TYPE DESCRIPTOR: UPDATES PERMITTED CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads the , then saves an existing via , and ensures that + /// it the cache is updated. + /// + [Fact] + public void Save_ContentTypeDescriptor_UpdatesPermittedContentTypes() { - Assert.False(child.IsNew); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var contentTypesRoot = contentTypes.GetValue("ContentTypes"); + var pageContentType = contentTypes.GetValue("Page"); + var lookupContentType = contentTypes.GetValue("Lookup"); - } + Contract.Assume(pageContentType); + Contract.Assume(lookupContentType); + Contract.Assume(contentTypesRoot); - /*========================================================================================================================== - | TEST: SAVE: UNRESOLVED REFERENCE: RESOLVES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves a new with an unresolved and confirms that it successfully - /// resolves it by marking the collection as as false. - /// - [Fact] - public void Save_UnresolvedReference_Resolves() { + var initialCount = pageContentType.PermittedContentTypes.Count; - var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); - var topic = new Topic("Test", "Page", parent); - var reference = new Topic("Reference", "Page", topic); + pageContentType.Relationships.SetValue("ContentTypes", lookupContentType); - topic.References.SetValue("Test", reference); + _topicRepository.Save(contentTypesRoot, true); - _topicRepository.Save(topic, true); + Assert.NotEqual(initialCount, pageContentType.PermittedContentTypes.Count); - } + } - /*========================================================================================================================== - | TEST: SAVE: UNRESOLVED REFERENCE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves a new with an unresolved and confirms that it throws the - /// expected if that reference cannot be resolved. - /// - [Fact] - public void Save_UnresolvedReference_ThrowsException() { + /*============================================================================================================================ + | TEST: SAVE: NEW TOPIC: UPDATES VERSION HISTORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves a new and confirms that the is correctly updated with a + /// new version. + /// + [Fact] + public void Save_NewTopic_UpdatesVersionHistory() { - var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); - var topic = new Topic("Test", "Page", parent); - var reference = new Topic("Reference", "Page", parent); + var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); + var topic = new Topic("Test", "Page", parent); - topic.References.SetValue("Test", reference); + _topicRepository.Save(topic); - Assert.Throws(() => - _topicRepository.Save(topic, true) - ); + Assert.True(topic.VersionHistory.Count > 0); - } + } - /*========================================================================================================================== - | TEST: SAVE: INVALID CONTENT TYPE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves a new with an invalid and confirms that it throws the - /// expected . - /// - [Fact] - public void Save_InvalidContentType_ThrowsException() => - Assert.Throws(() => - _topicRepository.Save(new("Test", "InvalidContentType")) - ); - - /*========================================================================================================================== - | TEST: DELETE: CONTENT TYPE DESCRIPTOR: UPDATES CONTENT TYPE CACHE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads the , then deletes one of the - /// s via , and ensures that it - /// is immediately reflected in the cache of s. - /// - [Fact] - public void Delete_ContentTypeDescriptor_UpdatesContentTypeCache() { - - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var contentType = contentTypes.Contains("Page")? contentTypes["Page"] : null; - - Contract.Assume(contentType); - - _topicRepository.Delete(contentType); - - Assert.DoesNotContain(contentType, contentTypes); + /*============================================================================================================================ + | TEST: SAVE: IS RECURSIVE: SAVES CHILD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves a new with a child and confirms that the of the + /// child is correctly updated. + /// + [Fact] + public void Save_IsRecursive_SavesChild() { - } + var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); + var topic = new Topic("Test", "Page", parent); + var child = new Topic("Child", "Page", topic); - /*========================================================================================================================== - | TEST: MOVE: AFTER SIBLING: SET CORRECTLY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Moves a after a sibling in another parent, and ensures it is set correctly. - /// - [Fact] - public void Move_AfterSibling_SetCorrectly() { + _topicRepository.Save(topic, true); - var source = new Topic("Source", "Page"); - var topic = new Topic("Test", "Page", source); - var target = new Topic("Target", "Page"); - var sibling = new Topic("Sibling", "Page", target); - var olderSibling = new Topic("OlderSibling", "Page", target); + Assert.False(child.IsNew); - _topicRepository.Move(topic, target, sibling); + } - Assert.Equal(target, topic.Parent); - Assert.Equal(0, target.Children.IndexOf(sibling)); - Assert.Equal(1, target.Children.IndexOf(topic)); - Assert.Equal(2, target.Children.IndexOf(olderSibling)); + /*============================================================================================================================ + | TEST: SAVE: UNRESOLVED REFERENCE: RESOLVES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves a new with an unresolved and confirms that it successfully + /// resolves it by marking the collection as as false. + /// + [Fact] + public void Save_UnresolvedReference_Resolves() { - } + var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); + var topic = new Topic("Test", "Page", parent); + var reference = new Topic("Reference", "Page", topic); - /*========================================================================================================================== - | TEST: MOVE: CONTENT TYPE DESCRIPTOR: UPDATES CONTENT TYPE CACHE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads the , then moves one of the - /// s via , and ensures - /// that it is immediately reflected in the cache of s. - /// - [Fact] - public void Move_ContentTypeDescriptor_UpdatesContentTypeCache() { + topic.References.SetValue("Test", reference); - var contentTypes = _topicRepository.GetContentTypeDescriptors(); - var pageContentType = contentTypes.Contains("Page")? contentTypes["Page"] : null; - var contactContentType = contentTypes.Contains("Contact")? contentTypes["Contact"] : null; - var contactAttributeCount = contactContentType?.AttributeDescriptors.Count; + _topicRepository.Save(topic, true); - Contract.Assume(contactContentType); - Contract.Assume(pageContentType); + } - _topicRepository.Move(contactContentType, pageContentType); + /*============================================================================================================================ + | TEST: SAVE: UNRESOLVED REFERENCE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves a new with an unresolved and confirms that it throws the + /// expected if that reference cannot be resolved. + /// + [Fact] + public void Save_UnresolvedReference_ThrowsException() { - Assert.NotEqual(contactContentType?.AttributeDescriptors.Count, contactAttributeCount); + var parent = _topicRepository.Load("Root:Web:Web_3:Web_3_0"); + var topic = new Topic("Test", "Page", parent); + var reference = new Topic("Reference", "Page", parent); - } + topic.References.SetValue("Test", reference); - /*========================================================================================================================== - | TEST: SAVE: ATTRIBUTE DESCRIPTOR: UPDATES CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a with a child . Adds a new to the parent. Ensures that the - /// of the child reflects the change. - /// - [Fact] - public void Save_AttributeDescriptor_UpdatesContentType() { + Assert.Throws(() => + _topicRepository.Save(topic, true) + ); - var contentType = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor", null, 1); - var attributeList = new Topic("Attributes", "List", contentType, 2); - var childContentType = new ContentTypeDescriptor("Child", "ContentTypeDescriptor", contentType, 3); + } - Contract.Assume(childContentType); + /*============================================================================================================================ + | TEST: SAVE: INVALID CONTENT TYPE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves a new with an invalid and confirms that it throws the + /// expected . + /// + [Fact] + public void Save_InvalidContentType_ThrowsException() => + Assert.Throws(() => + _topicRepository.Save(new("Test", "InvalidContentType")) + ); - var attributeCount = childContentType.AttributeDescriptors.Count; + /*============================================================================================================================ + | TEST: DELETE: CONTENT TYPE DESCRIPTOR: UPDATES CONTENT TYPE CACHE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads the , then deletes one of the + /// s via , and ensures that it + /// is immediately reflected in the cache of s. + /// + [Fact] + public void Delete_ContentTypeDescriptor_UpdatesContentTypeCache() { - var newAttribute = new BooleanAttributeDescriptor("NewAttribute", "BooleanAttributeDescriptor", attributeList); + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var contentType = contentTypes.Contains("Page")? contentTypes["Page"] : null; - Contract.Assume(newAttribute); + Contract.Assume(contentType); - _topicRepository.Save(newAttribute); + _topicRepository.Delete(contentType); - Assert.Equal(attributeCount+1, childContentType.AttributeDescriptors.Count); + Assert.DoesNotContain(contentType, contentTypes); - } + } - /*========================================================================================================================== - | TEST: DELETE: ATTRIBUTE DESCRIPTOR: UPDATES CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a with a child . Adds a new to the parent, then immediately deletes it. Ensures that the of the child reflects the change. - /// - [Fact] - public void Delete_AttributeDescriptor_UpdatesContentTypeCache() { + /*============================================================================================================================ + | TEST: MOVE: AFTER SIBLING: SET CORRECTLY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Moves a after a sibling in another parent, and ensures it is set correctly. + /// + [Fact] + public void Move_AfterSibling_SetCorrectly() { - var contentType = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor"); - var attributeList = new Topic("Attributes", "List", contentType); - var newAttribute = new BooleanAttributeDescriptor("NewAttribute", "BooleanAttributeDescriptor", attributeList); - var childContentType = new ContentTypeDescriptor("Child", "ContentTypeDescriptor", contentType); + var source = new Topic("Source", "Page"); + var topic = new Topic("Test", "Page", source); + var target = new Topic("Target", "Page"); + var sibling = new Topic("Sibling", "Page", target); + var olderSibling = new Topic("OlderSibling", "Page", target); - Contract.Assume(childContentType); - Contract.Assume(newAttribute); + _topicRepository.Move(topic, target, sibling); - var attributeCount = childContentType.AttributeDescriptors.Count; + Assert.Equal(target, topic.Parent); + Assert.Equal(0, target.Children.IndexOf(sibling)); + Assert.Equal(1, target.Children.IndexOf(topic)); + Assert.Equal(2, target.Children.IndexOf(olderSibling)); - _topicRepository.Delete(newAttribute); + } - Assert.True(childContentType.AttributeDescriptors.Count < attributeCount); + /*============================================================================================================================ + | TEST: MOVE: CONTENT TYPE DESCRIPTOR: UPDATES CONTENT TYPE CACHE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads the , then moves one of the + /// s via , and ensures + /// that it is immediately reflected in the cache of s. + /// + [Fact] + public void Move_ContentTypeDescriptor_UpdatesContentTypeCache() { - } + var contentTypes = _topicRepository.GetContentTypeDescriptors(); + var pageContentType = contentTypes.Contains("Page")? contentTypes["Page"] : null; + var contactContentType = contentTypes.Contains("Contact")? contentTypes["Contact"] : null; + var contactAttributeCount = contactContentType?.AttributeDescriptors.Count; - /*========================================================================================================================== - | TEST: LOAD: TOPIC LOADED EVENT: IS RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a topic using and ensures that the event is raised. - /// - [Fact] - public void Load_TopicLoadedEvent_IsRaised() { + Contract.Assume(contactContentType); + Contract.Assume(pageContentType); - var hasFired = false; + _topicRepository.Move(contactContentType, pageContentType); - _cachedTopicRepository.TopicLoaded += eventHandler; + Assert.NotEqual(contactContentType?.AttributeDescriptors.Count, contactAttributeCount); - var topic = _topicRepository.Load("Root:Web"); + } - _cachedTopicRepository.TopicLoaded -= eventHandler; + /*============================================================================================================================ + | TEST: SAVE: ATTRIBUTE DESCRIPTOR: UPDATES CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a with a child . Adds a new to the parent. Ensures that the + /// of the child reflects the change. + /// + [Fact] + public void Save_AttributeDescriptor_UpdatesContentType() { - Assert.True(hasFired); + var contentType = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor", null, 1); + var attributeList = new Topic("Attributes", "List", contentType, 2); + var childContentType = new ContentTypeDescriptor("Child", "ContentTypeDescriptor", contentType, 3); - void eventHandler(object? sender, TopicLoadEventArgs eventArgs) => hasFired = true; + Contract.Assume(childContentType); - } + var attributeCount = childContentType.AttributeDescriptors.Count; - /*========================================================================================================================== - | TEST: LOAD: TOPIC LOADED EVENT: IS RAISED WITH VERSION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Loads a topic using and ensures that the event is raised. - /// - [Fact] - public void Load_TopicLoadedEvent_IsRaisedWithVersion() { + var newAttribute = new BooleanAttributeDescriptor("NewAttribute", "BooleanAttributeDescriptor", attributeList); - var hasFired = false; - var topicId = _topicRepository.Load("Root:Web")?.Id; - var version = DateTime.UtcNow; + Contract.Assume(newAttribute); - _cachedTopicRepository.TopicLoaded += eventHandler; + _topicRepository.Save(newAttribute); - var topic = _topicRepository.Load(topicId?? -1, version); + Assert.Equal(attributeCount+1, childContentType.AttributeDescriptors.Count); - _cachedTopicRepository.TopicLoaded -= eventHandler; + } - Assert.True(hasFired); - Assert.Equal(topicId, topic?.Id); - Assert.Equal(version, topic?.VersionHistory.LastOrDefault()); + /*============================================================================================================================ + | TEST: DELETE: ATTRIBUTE DESCRIPTOR: UPDATES CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a with a child . Adds a new to the parent, then immediately deletes it. Ensures that the of the child reflects the change. + /// + [Fact] + public void Delete_AttributeDescriptor_UpdatesContentTypeCache() { - void eventHandler(object? sender, TopicLoadEventArgs eventArgs) => hasFired = true; + var contentType = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor"); + var attributeList = new Topic("Attributes", "List", contentType); + var newAttribute = new BooleanAttributeDescriptor("NewAttribute", "BooleanAttributeDescriptor", attributeList); + var childContentType = new ContentTypeDescriptor("Child", "ContentTypeDescriptor", contentType); - } + Contract.Assume(childContentType); + Contract.Assume(newAttribute); + + var attributeCount = childContentType.AttributeDescriptors.Count; - /*========================================================================================================================== - | TEST: DELETE: TOPIC DELETED EVENT: IS RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a and then immediately deletes it. Ensures that the event is raised. - /// - [Fact] - public void Delete_TopicDeletedEvent_IsRaised() { + _topicRepository.Delete(newAttribute); - var topic = new Topic("Test", "Page"); - var hasFired = false; + Assert.True(childContentType.AttributeDescriptors.Count < attributeCount); - _cachedTopicRepository.Save(topic); - _cachedTopicRepository.TopicDeleted += eventHandler; - _cachedTopicRepository.Delete(topic); - _cachedTopicRepository.TopicDeleted -= eventHandler; + } - Assert.True(hasFired); + /*============================================================================================================================ + | TEST: LOAD: TOPIC LOADED EVENT: IS RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a topic using and ensures that the event is raised. + /// + [Fact] + public void Load_TopicLoadedEvent_IsRaised() { - void eventHandler(object? sender, TopicEventArgs eventArgs) => hasFired = true; + var hasFired = false; - } + _cachedTopicRepository.TopicLoaded += eventHandler; - /*========================================================================================================================== - | TEST: SAVE: TOPIC SAVED EVENT: IS RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a and then immediately saves it. Ensures that the event is raised. - /// - [Fact] - public void Save_TopicSavedEvent_IsRaised() { + var topic = _topicRepository.Load("Root:Web"); - var topic = new Topic("Test", "Page"); - var hasFired = false; + _cachedTopicRepository.TopicLoaded -= eventHandler; - _cachedTopicRepository.TopicSaved += eventHandler; - _cachedTopicRepository.Save(topic); - _cachedTopicRepository.TopicSaved -= eventHandler; + Assert.True(hasFired); - Assert.True(hasFired); + void eventHandler(object? sender, TopicLoadEventArgs eventArgs) => hasFired = true; - void eventHandler(object? sender, TopicSaveEventArgs eventArgs) => hasFired = true; + } - } + /*============================================================================================================================ + | TEST: LOAD: TOPIC LOADED EVENT: IS RAISED WITH VERSION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Loads a topic using and ensures that the event is raised. + /// + [Fact] + public void Load_TopicLoadedEvent_IsRaisedWithVersion() { - /*========================================================================================================================== - | TEST: SAVE: TOPIC RENAMED EVENT: IS RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a and then immediately saves it. Ensures that the event is raised. - /// - [Fact] - public void Save_TopicRenamedEvent_IsRaised() { + var hasFired = false; + var topicId = _topicRepository.Load("Root:Web")?.Id; + var version = DateTime.UtcNow; - var topic = new Topic("Test", "Page", null, 1); - var hasFired = false; + _cachedTopicRepository.TopicLoaded += eventHandler; - topic.Key = "New"; + var topic = _topicRepository.Load(topicId?? -1, version); - _cachedTopicRepository.TopicRenamed += eventHandler; - _cachedTopicRepository.Save(topic); - _cachedTopicRepository.TopicRenamed -= eventHandler; + _cachedTopicRepository.TopicLoaded -= eventHandler; - Assert.True(hasFired); + Assert.True(hasFired); + Assert.Equal(topicId, topic?.Id); + Assert.Equal(version, topic?.VersionHistory.LastOrDefault()); - void eventHandler(object? sender, TopicRenameEventArgs eventArgs) => hasFired = true; + void eventHandler(object? sender, TopicLoadEventArgs eventArgs) => hasFired = true; - } + } - /*========================================================================================================================== - | TEST: SAVE: TOPIC MOVED EVENT: IS RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a , changes its parent, and then saves it. Ensures that the event is raised. - /// - [Fact] - public void Save_TopicMovedEvent_IsRaised() { + /*============================================================================================================================ + | TEST: DELETE: TOPIC DELETED EVENT: IS RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a and then immediately deletes it. Ensures that the event is raised. + /// + [Fact] + public void Delete_TopicDeletedEvent_IsRaised() { - var topic = new Topic("Test", "Page", null, 1); - var parent = new Topic("Products", "Page", null, 2); - var hasFired = false; + var topic = new Topic("Test", "Page"); + var hasFired = false; - topic.Parent = parent; + _cachedTopicRepository.Save(topic); + _cachedTopicRepository.TopicDeleted += eventHandler; + _cachedTopicRepository.Delete(topic); + _cachedTopicRepository.TopicDeleted -= eventHandler; - _cachedTopicRepository.TopicMoved += eventHandler; - _cachedTopicRepository.Save(topic); - _cachedTopicRepository.TopicMoved -= eventHandler; + Assert.True(hasFired); - Assert.True(hasFired); + void eventHandler(object? sender, TopicEventArgs eventArgs) => hasFired = true; - void eventHandler(object? sender, TopicMoveEventArgs eventArgs) => hasFired = true; + } - } + /*============================================================================================================================ + | TEST: SAVE: TOPIC SAVED EVENT: IS RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a and then immediately saves it. Ensures that the event is raised. + /// + [Fact] + public void Save_TopicSavedEvent_IsRaised() { - /*========================================================================================================================== - | TEST: MOVE: TOPIC MOVED EVENT: IS RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a and then immediately moves it. Ensures that the event is raised. - /// - [Fact] - public void Move_TopicMovedEvent_IsRaised() { + var topic = new Topic("Test", "Page"); + var hasFired = false; - var topic = new Topic("Test", "Page", null, 1); - var parent = new Topic("Products", "Page", null, 2); - var hasFired = false; + _cachedTopicRepository.TopicSaved += eventHandler; + _cachedTopicRepository.Save(topic); + _cachedTopicRepository.TopicSaved -= eventHandler; - _cachedTopicRepository.TopicMoved += eventHandler; - _cachedTopicRepository.Move(topic, parent); - _cachedTopicRepository.TopicMoved -= eventHandler; + Assert.True(hasFired); - Assert.True(hasFired); + void eventHandler(object? sender, TopicSaveEventArgs eventArgs) => hasFired = true; - void eventHandler(object? sender, TopicMoveEventArgs eventArgs) => hasFired = true; + } - } + /*============================================================================================================================ + | TEST: SAVE: TOPIC RENAMED EVENT: IS RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a and then immediately saves it. Ensures that the event is raised. + /// + [Fact] + public void Save_TopicRenamedEvent_IsRaised() { - /*========================================================================================================================== - | TEST: MOVE: SAME LOCATION: EVENT NOT RAISED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a and then moves it to the exact same location in the tree. Ensures that the event is not raised. - /// - [Fact] - public void Move_SameLocation_EventNotRaised() { + var topic = new Topic("Test", "Page", null, 1); + var hasFired = false; - var parent = new Topic("Parent", "Page", null, 1); - var sibling = new Topic("Sibling", "Page", parent, 2); - var topic = new Topic("Test", "Page", parent, 3); - var hasFired = false; + topic.Key = "New"; - _cachedTopicRepository.TopicMoved += eventHandler; - _cachedTopicRepository.Move(topic, parent, sibling); - _cachedTopicRepository.TopicMoved -= eventHandler; + _cachedTopicRepository.TopicRenamed += eventHandler; + _cachedTopicRepository.Save(topic); + _cachedTopicRepository.TopicRenamed -= eventHandler; - Assert.False(hasFired); + Assert.True(hasFired); - void eventHandler(object? sender, TopicMoveEventArgs eventArgs) => hasFired = true; + void eventHandler(object? sender, TopicRenameEventArgs eventArgs) => hasFired = true; - } + } + + /*============================================================================================================================ + | TEST: SAVE: TOPIC MOVED EVENT: IS RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a , changes its parent, and then saves it. Ensures that the event is raised. + /// + [Fact] + public void Save_TopicMovedEvent_IsRaised() { + + var topic = new Topic("Test", "Page", null, 1); + var parent = new Topic("Products", "Page", null, 2); + var hasFired = false; + + topic.Parent = parent; + + _cachedTopicRepository.TopicMoved += eventHandler; + _cachedTopicRepository.Save(topic); + _cachedTopicRepository.TopicMoved -= eventHandler; + + Assert.True(hasFired); + + void eventHandler(object? sender, TopicMoveEventArgs eventArgs) => hasFired = true; + + } + + /*============================================================================================================================ + | TEST: MOVE: TOPIC MOVED EVENT: IS RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a and then immediately moves it. Ensures that the event is raised. + /// + [Fact] + public void Move_TopicMovedEvent_IsRaised() { + + var topic = new Topic("Test", "Page", null, 1); + var parent = new Topic("Products", "Page", null, 2); + var hasFired = false; + + _cachedTopicRepository.TopicMoved += eventHandler; + _cachedTopicRepository.Move(topic, parent); + _cachedTopicRepository.TopicMoved -= eventHandler; + + Assert.True(hasFired); + + void eventHandler(object? sender, TopicMoveEventArgs eventArgs) => hasFired = true; + + } + + /*============================================================================================================================ + | TEST: MOVE: SAME LOCATION: EVENT NOT RAISED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a and then moves it to the exact same location in the tree. Ensures that the event is not raised. + /// + [Fact] + public void Move_SameLocation_EventNotRaised() { + + var parent = new Topic("Parent", "Page", null, 1); + var sibling = new Topic("Sibling", "Page", parent, 2); + var topic = new Topic("Test", "Page", parent, 3); + var hasFired = false; + + _cachedTopicRepository.TopicMoved += eventHandler; + _cachedTopicRepository.Move(topic, parent, sibling); + _cachedTopicRepository.TopicMoved -= eventHandler; + + Assert.False(hasFired); + + void eventHandler(object? sender, TopicMoveEventArgs eventArgs) => hasFired = true; + + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TopicTest.cs b/OnTopic.Tests/TopicTest.cs index 23bad445..0340cda3 100644 --- a/OnTopic.Tests/TopicTest.cs +++ b/OnTopic.Tests/TopicTest.cs @@ -8,526 +8,525 @@ using OnTopic.Repositories; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TOPIC TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TopicTest { + + /*============================================================================================================================ + | TEST: CREATE: RETURNS TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a topic using the factory method, and ensures it's correctly returned. + /// + [Fact] + public void Create_ReturnsTopic() { + var topic = TopicFactory.Create("Test", "Page"); + Assert.NotNull(topic); + Assert.Equal("Test", topic.Key); + Assert.Equal("Page", topic.ContentType); + } + + /*============================================================================================================================ + | TEST: CREATE: CONTENT TYPE: RETURNS DERIVED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a topic of a content type which maps to a class derived from , and ensures the derived + /// version of the class is returned. + /// + [Fact] + public void Create_ContentType_ReturnsDerivedTopic() { + var topic = TopicFactory.Create("Test", "ContentTypeDescriptor"); + Assert.NotNull(topic); + Assert.IsType(topic); + } + + /*============================================================================================================================ + | TEST: CREATE: ATTRIBUTE DESCRIPTOR: RETURNS FALLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a topic with a ending with AttributeDescriptor and ensures that, by + /// convention, a is returned. + /// + /// + /// This is a special use case to address the fact that we expect concrete types of to + /// be in external plugin libraries, but the only needs to know that they're an . This is similar to how other types will fallback to if no matching type + /// can be found in the . + /// + [Fact] + public void Create_AttributeDescriptor_ReturnsFallback() { + var topic = TopicFactory.Create("Test", "ArbitraryAttributeDescriptor"); + Assert.NotNull(topic); + Assert.IsType(topic); + } + + /*============================================================================================================================ + | TEST: ID: CHANGE VALUE: THROWS ARGUMENT EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a topic using the factory method, and ensures that the ID cannot be modified. + /// + [Fact] + public void Id_ChangeValue_ThrowsArgumentException() { + + var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor", null, 123); + + Assert.Throws(() => + topic.Id = 124 + ); + + } + + /*============================================================================================================================ + | TEST: KEY: CHANGE VALUE: UPDATES PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Changes a , and confirms that the 's + /// collection is updated to reflect the new . + /// + /// + /// By default, won't automatically update its key if the underlying changed. We have code that will handle that, however. + /// + [Fact] + public void Key_ChangeValue_UpdatesParent() { + + var parent = new ContentTypeDescriptor("Test", "ContentTypeDescriptor", null, 1); + var topic = new ContentTypeDescriptor("Original", "ContentTypeDescriptor", parent, 2) { + Key = "New" + }; + + Assert.Equal("New", topic.Key); + Assert.True(topic.IsDirty("Key")); + Assert.True(parent.Children.Contains("New")); + Assert.False(parent.Children.Contains("Original")); + + } + + /*============================================================================================================================ + | TEST: PARENT: SET VALUE: UPDATES PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets the parent of a topic and ensures it is correctly reflected in the object model. + /// + [Fact] + public void Parent_SetValue_UpdatesParent() { + + var parentTopic = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor"); + var childTopic = new ContentTypeDescriptor("Child", "ContentTypeDescriptor"); + + parentTopic.Id = 5; + childTopic.Parent = parentTopic; + + Assert.Equal(parentTopic.Children["Child"], childTopic); + Assert.Equal(5, childTopic.Parent.Id); + + } + + /*============================================================================================================================ + | TEST: PARENT: SET TO DESCENDANT: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets the to a that is a descendant, and ensure it throws an . + /// + [Fact] + public void Parent_SetToDescendant_ThrowsException() { + + var parentTopic = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor"); + var childTopic = new ContentTypeDescriptor("Child", "ContentTypeDescriptor", parentTopic); + + Assert.Throws(() => + parentTopic.Parent = childTopic + ); + + } + + /*============================================================================================================================ + | TEST: PARENT: DUPLICATE KEY: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets the to a whose already exists in the new + /// and ensures that an is thrown. + /// + [Fact] + public void Parent_DuplicateKey_ThrowsException() { + + var parentTopic = new Topic("Parent", "ContentTypeDescriptor"); + _ = new Topic("Child", "ContentTypeDescriptor", parentTopic); + + Assert.Throws(() => + _ = new Topic("Child", "ContentTypeDescriptor", parentTopic) + ); + + } + + /*============================================================================================================================ + | TEST: PARENT: CHANGE VALUE: UPDATES PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Changes the parent of a topic and ensures it is correctly reflected in the object model. + /// + [Fact] + public void Parent_ChangeValue_UpdatesParent() { + + var sourceParent = new ContentTypeDescriptor("SourceParent", "ContentTypeDescriptor", null, 5); + var targetParent = new ContentTypeDescriptor("TargetParent", "ContentTypeDescriptor", null, 10); + var childTopic = new ContentTypeDescriptor("ChildTopic", "ContentTypeDescriptor", sourceParent) { + Parent = targetParent + }; + + Assert.Equal(targetParent.Children["ChildTopic"], childTopic); + Assert.True(targetParent.Children.Contains("ChildTopic")); + Assert.False(sourceParent.Children.Contains("ChildTopic")); + Assert.Equal(10, childTopic.Parent.Id); + + } + + /*============================================================================================================================ + | TEST: UNIQUE KEY: RETURNS UNIQUE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures the Unique Key is correct for a deeply nested child. + /// + [Fact] + public void UniqueKey_ReturnsUniqueKey() { + + var parentTopic = new Topic("ParentTopic", "Page"); + var childTopic = new Topic("ChildTopic", "Page"); + var grandChildTopic = new Topic("GrandChildTopic", "Page"); + + childTopic.Parent = parentTopic; + grandChildTopic.Parent = childTopic; + + Assert.Equal("ParentTopic:ChildTopic:GrandChildTopic", grandChildTopic.GetUniqueKey()); + Assert.Equal("/ParentTopic/ChildTopic/GrandChildTopic/", grandChildTopic.GetWebPath()); + + } + + /*============================================================================================================================ + | TEST: IS VISIBLE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that returns expected values based on and + /// . + /// + [Fact] + public void IsVisible_ReturnsExpectedValue() { + + var hiddenTopic = new Topic("HiddenTopic", "Page"); + var disabledTopic = new Topic("DisabledTopic", "Page"); + var visibleTopic = new Topic("VisibleTopic", "Page"); + + hiddenTopic.IsHidden = true; + disabledTopic.IsDisabled = true; + + Assert.False(hiddenTopic.IsVisible()); + Assert.False(hiddenTopic.IsVisible(true)); + Assert.False(disabledTopic.IsVisible()); + Assert.True(disabledTopic.IsVisible(true)); + Assert.True(visibleTopic.IsVisible()); + Assert.True(visibleTopic.IsVisible(true)); + + } + + /*============================================================================================================================ + | TEST: TITLE: NULL VALUE: RETURNS KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that the title falls back appropriately. + /// + [Fact] + public void Title_NullValue_ReturnsKey() { + + var titledTopic = new Topic("TitledTopic", "Page"); + var untitledTopic = new Topic("UntitledTopic", "Page"); + + titledTopic.Title = "Titled Topic"; + + Assert.Equal("UntitledTopic", untitledTopic.Title); + Assert.Equal("Titled Topic", titledTopic.Title); + + } + + /*============================================================================================================================ + | TEST: LAST MODIFIED: UPDATE VALUE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Returns the last modified date via , and ensures it's returned correctly. + /// + [Fact] + public void LastModified_UpdateLastModified_ReturnsExpectedValue() { + + var topic = new Topic("Topic1", "Page"); + var lastModified = new DateTime(1976, 10, 15); + + topic.LastModified = lastModified; + + Assert.Equal(lastModified, topic.LastModified); + + } /*============================================================================================================================ - | CLASS: TOPIC TEST + | TEST: LAST MODIFIED: UPDATE VALUE: RETURNS EXPECTED VALUE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the class. + /// Returns the last modified date via , and ensures it's returned correctly. /// - [ExcludeFromCodeCoverage] - public class TopicTest { - - /*========================================================================================================================== - | TEST: CREATE: RETURNS TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a topic using the factory method, and ensures it's correctly returned. - /// - [Fact] - public void Create_ReturnsTopic() { - var topic = TopicFactory.Create("Test", "Page"); - Assert.NotNull(topic); - Assert.Equal("Test", topic.Key); - Assert.Equal("Page", topic.ContentType); - } - - /*========================================================================================================================== - | TEST: CREATE: CONTENT TYPE: RETURNS DERIVED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a topic of a content type which maps to a class derived from , and ensures the derived - /// version of the class is returned. - /// - [Fact] - public void Create_ContentType_ReturnsDerivedTopic() { - var topic = TopicFactory.Create("Test", "ContentTypeDescriptor"); - Assert.NotNull(topic); - Assert.IsType(topic); - } - - /*========================================================================================================================== - | TEST: CREATE: ATTRIBUTE DESCRIPTOR: RETURNS FALLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a topic with a ending with AttributeDescriptor and ensures that, by - /// convention, a is returned. - /// - /// - /// This is a special use case to address the fact that we expect concrete types of to - /// be in external plugin libraries, but the only needs to know that they're an . This is similar to how other types will fallback to if no matching type - /// can be found in the . - /// - [Fact] - public void Create_AttributeDescriptor_ReturnsFallback() { - var topic = TopicFactory.Create("Test", "ArbitraryAttributeDescriptor"); - Assert.NotNull(topic); - Assert.IsType(topic); - } - - /*========================================================================================================================== - | TEST: ID: CHANGE VALUE: THROWS ARGUMENT EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a topic using the factory method, and ensures that the ID cannot be modified. - /// - [Fact] - public void Id_ChangeValue_ThrowsArgumentException() { - - var topic = new ContentTypeDescriptor("Test", "ContentTypeDescriptor", null, 123); - - Assert.Throws(() => - topic.Id = 124 - ); - - } - - /*========================================================================================================================== - | TEST: KEY: CHANGE VALUE: UPDATES PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Changes a , and confirms that the 's - /// collection is updated to reflect the new . - /// - /// - /// By default, won't automatically update its key if the underlying changed. We have code that will handle that, however. - /// - [Fact] - public void Key_ChangeValue_UpdatesParent() { - - var parent = new ContentTypeDescriptor("Test", "ContentTypeDescriptor", null, 1); - var topic = new ContentTypeDescriptor("Original", "ContentTypeDescriptor", parent, 2) { - Key = "New" - }; - - Assert.Equal("New", topic.Key); - Assert.True(topic.IsDirty("Key")); - Assert.True(parent.Children.Contains("New")); - Assert.False(parent.Children.Contains("Original")); - - } - - /*========================================================================================================================== - | TEST: PARENT: SET VALUE: UPDATES PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets the parent of a topic and ensures it is correctly reflected in the object model. - /// - [Fact] - public void Parent_SetValue_UpdatesParent() { - - var parentTopic = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor"); - var childTopic = new ContentTypeDescriptor("Child", "ContentTypeDescriptor"); - - parentTopic.Id = 5; - childTopic.Parent = parentTopic; - - Assert.Equal(parentTopic.Children["Child"], childTopic); - Assert.Equal(5, childTopic.Parent.Id); - - } - - /*========================================================================================================================== - | TEST: PARENT: SET TO DESCENDANT: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets the to a that is a descendant, and ensure it throws an . - /// - [Fact] - public void Parent_SetToDescendant_ThrowsException() { - - var parentTopic = new ContentTypeDescriptor("Parent", "ContentTypeDescriptor"); - var childTopic = new ContentTypeDescriptor("Child", "ContentTypeDescriptor", parentTopic); - - Assert.Throws(() => - parentTopic.Parent = childTopic - ); - - } - - /*========================================================================================================================== - | TEST: PARENT: DUPLICATE KEY: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets the to a whose already exists in the new - /// and ensures that an is thrown. - /// - [Fact] - public void Parent_DuplicateKey_ThrowsException() { - - var parentTopic = new Topic("Parent", "ContentTypeDescriptor"); - _ = new Topic("Child", "ContentTypeDescriptor", parentTopic); - - Assert.Throws(() => - _ = new Topic("Child", "ContentTypeDescriptor", parentTopic) - ); - - } - - /*========================================================================================================================== - | TEST: PARENT: CHANGE VALUE: UPDATES PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Changes the parent of a topic and ensures it is correctly reflected in the object model. - /// - [Fact] - public void Parent_ChangeValue_UpdatesParent() { - - var sourceParent = new ContentTypeDescriptor("SourceParent", "ContentTypeDescriptor", null, 5); - var targetParent = new ContentTypeDescriptor("TargetParent", "ContentTypeDescriptor", null, 10); - var childTopic = new ContentTypeDescriptor("ChildTopic", "ContentTypeDescriptor", sourceParent) { - Parent = targetParent - }; - - Assert.Equal(targetParent.Children["ChildTopic"], childTopic); - Assert.True(targetParent.Children.Contains("ChildTopic")); - Assert.False(sourceParent.Children.Contains("ChildTopic")); - Assert.Equal(10, childTopic.Parent.Id); - - } - - /*========================================================================================================================== - | TEST: UNIQUE KEY: RETURNS UNIQUE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures the Unique Key is correct for a deeply nested child. - /// - [Fact] - public void UniqueKey_ReturnsUniqueKey() { - - var parentTopic = new Topic("ParentTopic", "Page"); - var childTopic = new Topic("ChildTopic", "Page"); - var grandChildTopic = new Topic("GrandChildTopic", "Page"); - - childTopic.Parent = parentTopic; - grandChildTopic.Parent = childTopic; - - Assert.Equal("ParentTopic:ChildTopic:GrandChildTopic", grandChildTopic.GetUniqueKey()); - Assert.Equal("/ParentTopic/ChildTopic/GrandChildTopic/", grandChildTopic.GetWebPath()); - - } - - /*========================================================================================================================== - | TEST: IS VISIBLE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that returns expected values based on and - /// . - /// - [Fact] - public void IsVisible_ReturnsExpectedValue() { - - var hiddenTopic = new Topic("HiddenTopic", "Page"); - var disabledTopic = new Topic("DisabledTopic", "Page"); - var visibleTopic = new Topic("VisibleTopic", "Page"); - - hiddenTopic.IsHidden = true; - disabledTopic.IsDisabled = true; - - Assert.False(hiddenTopic.IsVisible()); - Assert.False(hiddenTopic.IsVisible(true)); - Assert.False(disabledTopic.IsVisible()); - Assert.True(disabledTopic.IsVisible(true)); - Assert.True(visibleTopic.IsVisible()); - Assert.True(visibleTopic.IsVisible(true)); - - } - - /*========================================================================================================================== - | TEST: TITLE: NULL VALUE: RETURNS KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that the title falls back appropriately. - /// - [Fact] - public void Title_NullValue_ReturnsKey() { - - var titledTopic = new Topic("TitledTopic", "Page"); - var untitledTopic = new Topic("UntitledTopic", "Page"); - - titledTopic.Title = "Titled Topic"; - - Assert.Equal("UntitledTopic", untitledTopic.Title); - Assert.Equal("Titled Topic", titledTopic.Title); - - } - - /*========================================================================================================================== - | TEST: LAST MODIFIED: UPDATE VALUE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Returns the last modified date via , and ensures it's returned correctly. - /// - [Fact] - public void LastModified_UpdateLastModified_ReturnsExpectedValue() { - - var topic = new Topic("Topic1", "Page"); - var lastModified = new DateTime(1976, 10, 15); - - topic.LastModified = lastModified; - - Assert.Equal(lastModified, topic.LastModified); - - } - - /*========================================================================================================================== - | TEST: LAST MODIFIED: UPDATE VALUE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Returns the last modified date via , and ensures it's returned correctly. - /// - [Fact] - public void LastModified_UpdateVersionHistory_ReturnsExpectedValue() { + [Fact] + public void LastModified_UpdateVersionHistory_ReturnsExpectedValue() { - var topic = new Topic("Topic2", "Page"); - - var lastModified = new DateTime(1976, 10, 15); - - topic.VersionHistory.Add(lastModified); - - Assert.Equal(lastModified, topic.LastModified); - - } - - /*========================================================================================================================== - | TEST: LAST MODIFIED: UPDATE ATTRIBUTE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Returns the last modified date via , and ensures it's returned correctly. - /// - [Fact] - public void LastModified_UpdateValue_ReturnsExpectedValue() { - - var topic = new Topic("Topic3", "Page"); - - var lastModified = new DateTime(1976, 10, 15); - - topic.Attributes.SetValue("LastModified", lastModified.ToShortDateString()); - - Assert.Equal(lastModified, topic.LastModified); - - } - - /*========================================================================================================================== - | TEST: BASE TOPIC: UPDATE VALUE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a base topic to a topic entity, then replaces the references with a new topic entity. Ensures that both the - /// base topic as well as the underlying correctly reference the new value. - /// - [Fact] - public void BaseTopic_UpdateValue_ReturnsExpectedValue() { - - var topic = new Topic("Topic", "Page"); - var firstBaseTopic = new Topic("BaseTopic", "Page"); - var secondBaseTopic = new Topic("BaseTopic", "Page", null, 1); - var finalBaseTopic = new Topic("BaseTopic", "Page", null, 2); - - topic.BaseTopic = firstBaseTopic; - topic.BaseTopic = secondBaseTopic; - topic.BaseTopic = finalBaseTopic; - - Assert.Equal(topic.BaseTopic, finalBaseTopic); - Assert.Equal(2, topic.References.GetValue("BaseTopic")?.Id); - - } - - /*========================================================================================================================== - | TEST: BASE TOPIC: RESAVED VALUE: RETURNS EXPECTED VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a base topic to an unsaved topic entity, then saves the entity and reestablishes the reference. Ensures that the - /// base topic is correctly set as a entry. - /// - [Fact] - public void BaseTopic_ResavedValue_ReturnsExpectedValue() { - - var topic = new Topic("Topic", "Page"); - var baseTopic = new Topic("BaseTopic", "Page"); - - topic.BaseTopic = baseTopic; - baseTopic.Id = 5; - topic.BaseTopic = baseTopic; - - Assert.Equal(topic.BaseTopic, baseTopic); - Assert.Equal(5, topic.References.GetValue("BaseTopic")?.Id); - - } - - /*========================================================================================================================== - | TEST: BASE TOPIC: SET TO NULL: REMOVES VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a base topic to a topic entity, then updates it to a null value. Ensures that the base topic is correctly - /// removed. - /// - [Fact] - public void BaseTopic_SetToNull_RemovesValue() { - - var topic = new Topic("Topic", "Page"); - var baseTopic = new Topic("BaseTopic", "Page"); - - topic.BaseTopic = baseTopic; - topic.BaseTopic = null; - - Assert.Null(topic.BaseTopic); - - } - - /*========================================================================================================================== - | IS DIRTY: NEW TOPIC: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a new topic, and confirms that returns true. - /// - [Fact] - public void IsDirty_NewTopic_ReturnsTrue() => - Assert.True(new Topic("Topic", "Page").IsDirty()); - - /*========================================================================================================================== - | IS DIRTY: EXISTING TOPIC: RETURNS FALSE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates an existing topic, and confirms that returns false. - /// - [Fact] - public void IsDirty_ExistingTopic_ReturnsFalse() => - Assert.False(new Topic("Topic", "Page", null, 1).IsDirty()); - - /*========================================================================================================================== - | IS DIRTY: CHANGE KEY: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates an existing topic, changes the , and confirms that returns true. - /// - [Fact] - public void IsDirty_ChangeKey_ReturnsTrue() => - Assert.True( - new Topic("Topic", "Page", null, 1) { - Key = "NewTopic" - }.IsDirty() - ); - - /*========================================================================================================================== - | TEST: IS DIRTY: EXISTING VALUES: REMAINS CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates an existing topic, and updates the , , and to their existing values. Ensures that remains false. - /// - [Fact] - public void IsDirty_ExistingValue_RemainsClean() { - - var parent = new Topic("Parent", "Page", null, 1); - var topic = new Topic("Topic", "Page", parent, 2); - - topic.Key = topic.Key; - topic.ContentType = topic.ContentType; - topic.Parent = parent; - - Assert.False(topic.IsDirty()); - - } - - /*========================================================================================================================== - | IS DIRTY: CHANGE COLLECTIONS: RETURNS TRUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates an existing topic, changes the , , and collections, and confirms that returns - /// true. - /// - [Fact] - public void IsDirty_ChangeCollections_ReturnsTrue() { - - var topic = new Topic("Topic", "Page", null, 1); - var related = new Topic("Related", "Page", null, 2); - - topic.Attributes.SetValue("Related", related.Key); - topic.References.SetValue("Related", related); - topic.Relationships.SetValue("Related", related); - - Assert.True(topic.IsDirty(true)); - Assert.True(topic.IsDirty("Related", true)); - - } - - /*========================================================================================================================== - | MARK CLEAN: CHANGE COLLECTIONS: RESETS IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates an existing topic, changes the , , and collections, and confirms that resets the - /// value of . - /// - [Fact] - public void MarkClean_ChangeCollections_ResetIsDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var related = new Topic("Related", "Page", null, 2); - - topic.Attributes.SetValue("Related", related.Key); - topic.References.SetValue("Related", related); - topic.Relationships.SetValue("Related", related); - - topic.MarkClean(true); - - Assert.False(topic.IsDirty(true)); - - } - - /*========================================================================================================================== - | MARK CLEAN: INCLUDE COLLECTIONS: RESETS IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates an existing topic, changes the , , and collections, and confirms that resets the value - /// of . - /// - [Fact] - public void MarkClean_IncludeCollections_ResetsIsDirty() { - - var topic = new Topic("Topic", "Page", null, 1); - var related = new Topic("Related", "Page", null, 2); - - topic.Attributes.SetValue("Related", related.Key); - topic.References.SetValue("Related", related); - topic.Relationships.SetValue("Related", related); - - topic.MarkClean("Related", true); - - Assert.False(topic.IsDirty("Related", true)); - Assert.False(topic.IsDirty(true)); - - } - - - /*========================================================================================================================== - | MARK CLEAN: NEW TOPIC: REMAINS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Creates a new and confirms that does not reset the value of - /// . Topics that are marked as cannot be clean. - /// - [Fact] - public void MarkClean_NewTopic_RemainsDirty() { + var topic = new Topic("Topic2", "Page"); + + var lastModified = new DateTime(1976, 10, 15); + + topic.VersionHistory.Add(lastModified); + + Assert.Equal(lastModified, topic.LastModified); + + } + + /*============================================================================================================================ + | TEST: LAST MODIFIED: UPDATE ATTRIBUTE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Returns the last modified date via , and ensures it's returned correctly. + /// + [Fact] + public void LastModified_UpdateValue_ReturnsExpectedValue() { + + var topic = new Topic("Topic3", "Page"); + + var lastModified = new DateTime(1976, 10, 15); + + topic.Attributes.SetValue("LastModified", lastModified.ToShortDateString()); + + Assert.Equal(lastModified, topic.LastModified); + + } + + /*============================================================================================================================ + | TEST: BASE TOPIC: UPDATE VALUE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a base topic to a topic entity, then replaces the references with a new topic entity. Ensures that both the + /// base topic as well as the underlying correctly reference the new value. + /// + [Fact] + public void BaseTopic_UpdateValue_ReturnsExpectedValue() { + + var topic = new Topic("Topic", "Page"); + var firstBaseTopic = new Topic("BaseTopic", "Page"); + var secondBaseTopic = new Topic("BaseTopic", "Page", null, 1); + var finalBaseTopic = new Topic("BaseTopic", "Page", null, 2); + + topic.BaseTopic = firstBaseTopic; + topic.BaseTopic = secondBaseTopic; + topic.BaseTopic = finalBaseTopic; + + Assert.Equal(topic.BaseTopic, finalBaseTopic); + Assert.Equal(2, topic.References.GetValue("BaseTopic")?.Id); + + } + + /*============================================================================================================================ + | TEST: BASE TOPIC: RESAVED VALUE: RETURNS EXPECTED VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a base topic to an unsaved topic entity, then saves the entity and reestablishes the reference. Ensures that the + /// base topic is correctly set as a entry. + /// + [Fact] + public void BaseTopic_ResavedValue_ReturnsExpectedValue() { + + var topic = new Topic("Topic", "Page"); + var baseTopic = new Topic("BaseTopic", "Page"); + + topic.BaseTopic = baseTopic; + baseTopic.Id = 5; + topic.BaseTopic = baseTopic; + + Assert.Equal(topic.BaseTopic, baseTopic); + Assert.Equal(5, topic.References.GetValue("BaseTopic")?.Id); + + } + + /*============================================================================================================================ + | TEST: BASE TOPIC: SET TO NULL: REMOVES VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a base topic to a topic entity, then updates it to a null value. Ensures that the base topic is correctly + /// removed. + /// + [Fact] + public void BaseTopic_SetToNull_RemovesValue() { + + var topic = new Topic("Topic", "Page"); + var baseTopic = new Topic("BaseTopic", "Page"); + + topic.BaseTopic = baseTopic; + topic.BaseTopic = null; + + Assert.Null(topic.BaseTopic); + + } + + /*============================================================================================================================ + | IS DIRTY: NEW TOPIC: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a new topic, and confirms that returns true. + /// + [Fact] + public void IsDirty_NewTopic_ReturnsTrue() => + Assert.True(new Topic("Topic", "Page").IsDirty()); + + /*============================================================================================================================ + | IS DIRTY: EXISTING TOPIC: RETURNS FALSE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates an existing topic, and confirms that returns false. + /// + [Fact] + public void IsDirty_ExistingTopic_ReturnsFalse() => + Assert.False(new Topic("Topic", "Page", null, 1).IsDirty()); + + /*============================================================================================================================ + | IS DIRTY: CHANGE KEY: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates an existing topic, changes the , and confirms that returns true. + /// + [Fact] + public void IsDirty_ChangeKey_ReturnsTrue() => + Assert.True( + new Topic("Topic", "Page", null, 1) { + Key = "NewTopic" + }.IsDirty() + ); + + /*============================================================================================================================ + | TEST: IS DIRTY: EXISTING VALUES: REMAINS CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates an existing topic, and updates the , , and to their existing values. Ensures that remains false. + /// + [Fact] + public void IsDirty_ExistingValue_RemainsClean() { + + var parent = new Topic("Parent", "Page", null, 1); + var topic = new Topic("Topic", "Page", parent, 2); + + topic.Key = topic.Key; + topic.ContentType = topic.ContentType; + topic.Parent = parent; + + Assert.False(topic.IsDirty()); + + } + + /*============================================================================================================================ + | IS DIRTY: CHANGE COLLECTIONS: RETURNS TRUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates an existing topic, changes the , , and collections, and confirms that returns + /// true. + /// + [Fact] + public void IsDirty_ChangeCollections_ReturnsTrue() { + + var topic = new Topic("Topic", "Page", null, 1); + var related = new Topic("Related", "Page", null, 2); + + topic.Attributes.SetValue("Related", related.Key); + topic.References.SetValue("Related", related); + topic.Relationships.SetValue("Related", related); + + Assert.True(topic.IsDirty(true)); + Assert.True(topic.IsDirty("Related", true)); + + } + + /*============================================================================================================================ + | MARK CLEAN: CHANGE COLLECTIONS: RESETS IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates an existing topic, changes the , , and collections, and confirms that resets the + /// value of . + /// + [Fact] + public void MarkClean_ChangeCollections_ResetIsDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var related = new Topic("Related", "Page", null, 2); + + topic.Attributes.SetValue("Related", related.Key); + topic.References.SetValue("Related", related); + topic.Relationships.SetValue("Related", related); + + topic.MarkClean(true); + + Assert.False(topic.IsDirty(true)); + + } + + /*============================================================================================================================ + | MARK CLEAN: INCLUDE COLLECTIONS: RESETS IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates an existing topic, changes the , , and collections, and confirms that resets the value + /// of . + /// + [Fact] + public void MarkClean_IncludeCollections_ResetsIsDirty() { + + var topic = new Topic("Topic", "Page", null, 1); + var related = new Topic("Related", "Page", null, 2); + + topic.Attributes.SetValue("Related", related.Key); + topic.References.SetValue("Related", related); + topic.Relationships.SetValue("Related", related); + + topic.MarkClean("Related", true); + + Assert.False(topic.IsDirty("Related", true)); + Assert.False(topic.IsDirty(true)); + + } + + + /*============================================================================================================================ + | MARK CLEAN: NEW TOPIC: REMAINS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Creates a new and confirms that does not reset the value of + /// . Topics that are marked as cannot be clean. + /// + [Fact] + public void MarkClean_NewTopic_RemainsDirty() { - var topic = new Topic("Topic", "Page"); + var topic = new Topic("Topic", "Page"); - topic.Attributes.SetValue("Attribute", "Test"); + topic.Attributes.SetValue("Attribute", "Test"); - topic.MarkClean("Attribute", true); - topic.MarkClean(true); + topic.MarkClean("Attribute", true); + topic.MarkClean(true); - Assert.True(topic.IsDirty()); - Assert.True(topic.IsDirty("Attribute", true)); + Assert.True(topic.IsDirty()); + Assert.True(topic.IsDirty("Attribute", true)); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TypeAccessorTest.cs b/OnTopic.Tests/TypeAccessorTest.cs index 6653e097..dd1f3b8c 100644 --- a/OnTopic.Tests/TypeAccessorTest.cs +++ b/OnTopic.Tests/TypeAccessorTest.cs @@ -13,688 +13,687 @@ using OnTopic.Tests.ViewModels.Metadata; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TYPE ACCESSOR TESTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the classes. +/// +[ExcludeFromCodeCoverage] +public class TypeAccessorTest: IClassFixture> { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + internal readonly TypeAccessor _typeAccessor; /*============================================================================================================================ - | CLASS: TYPE ACCESSOR TESTS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the classes. + /// Initializes a new instance of the with shared resources. /// - [ExcludeFromCodeCoverage] - public class TypeAccessorTest: IClassFixture> { + /// + /// This establishes a shared based on the so that + /// members can be processed once, and then evaluated from a single instance. + /// + public TypeAccessorTest(TypeAccessorFixture fixture) { - /*========================================================================================================================== - | PRIVATE VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - internal readonly TypeAccessor _typeAccessor; + Contract.Requires(fixture, nameof(fixture)); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the with shared resources. - /// - /// - /// This establishes a shared based on the so that - /// members can be processed once, and then evaluated from a single instance. - /// - public TypeAccessorTest(TypeAccessorFixture fixture) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(fixture, nameof(fixture)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _typeAccessor = fixture.TypeAccessor; + _typeAccessor = fixture.TypeAccessor; - } + } - /*========================================================================================================================== - | TEST: GET MEMBERS: MIXED VALIDITY: RETURNS VALID MEMBERS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that contains both valid and invalid members. - /// Ensures that only the valid members are returned via . - /// - [Fact] - public void GetMembers_MixedValidity_ReturnsValidMembers() { + /*============================================================================================================================ + | TEST: GET MEMBERS: MIXED VALIDITY: RETURNS VALID MEMBERS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that contains both valid and invalid members. + /// Ensures that only the valid members are returned via . + /// + [Fact] + public void GetMembers_MixedValidity_ReturnsValidMembers() { - var members = _typeAccessor.GetMembers(); + var members = _typeAccessor.GetMembers(); - Assert.Equal(7, members.Count); + Assert.Equal(7, members.Count); - } + } - /*========================================================================================================================== - | TEST: GET MEMBERS: PROPERTIES: RETURNS PROPERTIES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assembles a new from a that contains both methods and properties. - /// Ensures that only the properties are returned when is called with - /// . - /// - [Fact] - public void GetMembers_Properties_ReturnsProperties() { + /*============================================================================================================================ + | TEST: GET MEMBERS: PROPERTIES: RETURNS PROPERTIES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assembles a new from a that contains both methods and properties. + /// Ensures that only the properties are returned when is called with + /// . + /// + [Fact] + public void GetMembers_Properties_ReturnsProperties() { - var memberAccessors = _typeAccessor.GetMembers(MemberTypes.Property); + var memberAccessors = _typeAccessor.GetMembers(MemberTypes.Property); - Assert.Equal(5, memberAccessors.Count); + Assert.Equal(5, memberAccessors.Count); - } + } - /*========================================================================================================================== - | TEST: GET MEMBERS: PROPERTY INFO: RETURNS PROPERTIES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that - /// functions. - /// - [Fact] - public void GetMembers_PropertyInfo_ReturnsProperties() { + /*============================================================================================================================ + | TEST: GET MEMBERS: PROPERTY INFO: RETURNS PROPERTIES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that + /// functions. + /// + [Fact] + public void GetMembers_PropertyInfo_ReturnsProperties() { - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var properties = typeAccessor.GetMembers(); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var properties = typeAccessor.GetMembers(); - Assert.Contains(properties, p => p.Name.Equals(nameof(ContentTypeDescriptor.Key), StringComparison.Ordinal)); - Assert.Contains(properties, p => p.Name.Equals(nameof(ContentTypeDescriptor.AttributeDescriptors), StringComparison.Ordinal)); - Assert.DoesNotContain(properties, p => p.Name.Equals(nameof(ContentTypeDescriptor.IsTypeOf), StringComparison.Ordinal)); - Assert.DoesNotContain(properties, p => p.Name.Equals("InvalidPropertyName", StringComparison.Ordinal)); + Assert.Contains(properties, p => p.Name.Equals(nameof(ContentTypeDescriptor.Key), StringComparison.Ordinal)); + Assert.Contains(properties, p => p.Name.Equals(nameof(ContentTypeDescriptor.AttributeDescriptors), StringComparison.Ordinal)); + Assert.DoesNotContain(properties, p => p.Name.Equals(nameof(ContentTypeDescriptor.IsTypeOf), StringComparison.Ordinal)); + Assert.DoesNotContain(properties, p => p.Name.Equals("InvalidPropertyName", StringComparison.Ordinal)); - } + } - /*========================================================================================================================== - | TEST: GET MEMBER: VALID MEMBER: RETURNS MEMBER ACCESSOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that returns the expected . - /// - [Fact] - public void GetMember_ValidMember_ReturnsMemberAccessor() { + /*============================================================================================================================ + | TEST: GET MEMBER: VALID MEMBER: RETURNS MEMBER ACCESSOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that returns the expected . + /// + [Fact] + public void GetMember_ValidMember_ReturnsMemberAccessor() { - var memberAccessor = _typeAccessor.GetMember(nameof(MemberAccessorViewModel.NonNullableProperty))!; + var memberAccessor = _typeAccessor.GetMember(nameof(MemberAccessorViewModel.NonNullableProperty))!; - Assert.NotNull(memberAccessor); - Assert.Equal(nameof(MemberAccessorViewModel.NonNullableProperty), memberAccessor.Name); - Assert.False(memberAccessor.IsNullable); + Assert.NotNull(memberAccessor); + Assert.Equal(nameof(MemberAccessorViewModel.NonNullableProperty), memberAccessor.Name); + Assert.False(memberAccessor.IsNullable); - } + } - /*========================================================================================================================== - | TEST: GET MEMBER: INVALID MEMBER: RETURNS NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that returns the null if an invalid member is requests. - /// - [Fact] - public void GetMember_InvalidMember_ReturnsNull() { + /*============================================================================================================================ + | TEST: GET MEMBER: INVALID MEMBER: RETURNS NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that returns the null if an invalid member is requests. + /// + [Fact] + public void GetMember_InvalidMember_ReturnsNull() { - var memberAccessor = _typeAccessor.GetMember(nameof(MemberAccessorViewModel.InvalidGetMethod)); + var memberAccessor = _typeAccessor.GetMember(nameof(MemberAccessorViewModel.InvalidGetMethod)); - Assert.Null(memberAccessor); + Assert.Null(memberAccessor); - } + } - /*========================================================================================================================== - | TEST: HAS GETTER: NAMES: RETURNS RESULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that returns true if the member is, in fact, gettable. - /// - [Theory] - [InlineData(nameof(MemberAccessorViewModel.GetMethod), true)] - [InlineData(nameof(MemberAccessorViewModel.InvalidGetMethod), false)] - [InlineData(nameof(MemberAccessorViewModel.SetMethod), false)] - [InlineData(nameof(MemberAccessorViewModel.NonNullableProperty), true)] - [InlineData(nameof(MemberAccessorViewModel.ReadOnlyProperty), true)] - [InlineData(nameof(MemberAccessorViewModel.WriteOnlyProperty), false)] - [InlineData("MissingProperty", false)] - public void HasGetter_Names_ReturnsResult(string name, bool result) { - Assert.Equal(result, _typeAccessor.HasGetter(name)); - } + /*============================================================================================================================ + | TEST: HAS GETTER: NAMES: RETURNS RESULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that returns true if the member is, in fact, gettable. + /// + [Theory] + [InlineData(nameof(MemberAccessorViewModel.GetMethod), true)] + [InlineData(nameof(MemberAccessorViewModel.InvalidGetMethod), false)] + [InlineData(nameof(MemberAccessorViewModel.SetMethod), false)] + [InlineData(nameof(MemberAccessorViewModel.NonNullableProperty), true)] + [InlineData(nameof(MemberAccessorViewModel.ReadOnlyProperty), true)] + [InlineData(nameof(MemberAccessorViewModel.WriteOnlyProperty), false)] + [InlineData("MissingProperty", false)] + public void HasGetter_Names_ReturnsResult(string name, bool result) { + Assert.Equal(result, _typeAccessor.HasGetter(name)); + } - /*========================================================================================================================== - | TEST: HAS GETTABLE PROPERTY: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that returns the expected value. - /// - [Fact] - public void HasGettableProperty_ReturnsExpected() { + /*============================================================================================================================ + | TEST: HAS GETTABLE PROPERTY: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that returns the expected value. + /// + [Fact] + public void HasGettableProperty_ReturnsExpected() { - var typeAccessor1 = TypeAccessorCache.GetTypeAccessor(); - var typeAccessor2 = TypeAccessorCache.GetTypeAccessor(); + var typeAccessor1 = TypeAccessorCache.GetTypeAccessor(); + var typeAccessor2 = TypeAccessorCache.GetTypeAccessor(); - Assert.True(typeAccessor1.HasGettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.Key))); - Assert.False(typeAccessor1.HasGettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.ContentTypes))); - Assert.False(typeAccessor1.HasGettableProperty("MissingProperty")); - Assert.True(typeAccessor2.HasGettableProperty(nameof(TopicReferenceTopicViewModel.TopicReference), typeof(TopicViewModel))); + Assert.True(typeAccessor1.HasGettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.Key))); + Assert.False(typeAccessor1.HasGettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.ContentTypes))); + Assert.False(typeAccessor1.HasGettableProperty("MissingProperty")); + Assert.True(typeAccessor2.HasGettableProperty(nameof(TopicReferenceTopicViewModel.TopicReference), typeof(TopicViewModel))); - } + } - /*========================================================================================================================== - | TEST: HAS GETTABLE PROPERTY: WITH ATTRIBUTE: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a required constraint and confirms that returns the expected value. - /// - [Fact] - public void HasGettableProperty_WithAttribute_ReturnsExpected() { + /*============================================================================================================================ + | TEST: HAS GETTABLE PROPERTY: WITH ATTRIBUTE: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a required constraint and confirms that returns the expected value. + /// + [Fact] + public void HasGettableProperty_WithAttribute_ReturnsExpected() { - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - Assert.False(typeAccessor.HasGettableProperty(nameof(Topic.Key))); - Assert.True(typeAccessor.HasGettableProperty(nameof(Topic.View))); + Assert.False(typeAccessor.HasGettableProperty(nameof(Topic.Key))); + Assert.True(typeAccessor.HasGettableProperty(nameof(Topic.View))); - } + } - /*========================================================================================================================== - | TEST: HAS GETTABLE METHOD: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that - /// returns the expected value. - /// - [Fact] - public void HasGettableMethod_ReturnsExpected() { + /*============================================================================================================================ + | TEST: HAS GETTABLE METHOD: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that + /// returns the expected value. + /// + [Fact] + public void HasGettableMethod_ReturnsExpected() { - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - Assert.True(typeAccessor.HasGettableMethod("GetMethod")); - Assert.False(typeAccessor.HasGettableMethod("SetMethod")); - Assert.False(typeAccessor.HasGettableMethod("MissingMethod")); - Assert.False(typeAccessor.HasGettableMethod("GetComplexMethod")); - Assert.True(typeAccessor.HasGettableMethod("GetComplexMethod", typeof(TopicViewModel))); + Assert.True(typeAccessor.HasGettableMethod("GetMethod")); + Assert.False(typeAccessor.HasGettableMethod("SetMethod")); + Assert.False(typeAccessor.HasGettableMethod("MissingMethod")); + Assert.False(typeAccessor.HasGettableMethod("GetComplexMethod")); + Assert.True(typeAccessor.HasGettableMethod("GetComplexMethod", typeof(TopicViewModel))); - } + } - /*========================================================================================================================== - | TEST: HAS GETTABLE METHOD: WITH ATTRIBUTE: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a required constraint and confirms that returns the expected value. - /// - /// - /// In practice, we haven't encountered a need for this yet and, thus, don't have any semantically relevant attributes to - /// use in this situation. As a result, this example is a bit contrived. - /// - [Fact] - public void HasGettableMethod_WithAttribute_ReturnsExpected() { - - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - - Assert.True(typeAccessor.HasGettableMethod(nameof(MethodBasedViewModel.GetAnnotatedMethod))); - Assert.False(typeAccessor.HasGettableMethod(nameof(MethodBasedViewModel.GetMethod))); + /*============================================================================================================================ + | TEST: HAS GETTABLE METHOD: WITH ATTRIBUTE: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a required constraint and confirms that returns the expected value. + /// + /// + /// In practice, we haven't encountered a need for this yet and, thus, don't have any semantically relevant attributes to + /// use in this situation. As a result, this example is a bit contrived. + /// + [Fact] + public void HasGettableMethod_WithAttribute_ReturnsExpected() { - } + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - /*========================================================================================================================== - | TEST: GET VALUE: NAMES: RETURNS RESULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that returns the expected default value. - /// - [Theory] - [InlineData(nameof(MemberAccessorViewModel.NonNullableProperty), 1)] - [InlineData(nameof(MemberAccessorViewModel.NullableProperty), 2)] - [InlineData(nameof(MemberAccessorViewModel.NonNullableReferenceGetter), typeof(MemberAccessorTest))] - [InlineData(nameof(MemberAccessorViewModel.GetMethod), 3)] - [InlineData(nameof(MemberAccessorViewModel.ReadOnlyProperty), null)] - public void GetValue_Names_ReturnsResult(string name, object result) { - - var sourceObject = new MemberAccessorViewModel() { - NonNullableProperty = 1, - NullableProperty = 2, - NonNullableReferenceGetter = typeof(MemberAccessorTest) - }; - - sourceObject.SetMethod(3); - - Assert.Equal(result, _typeAccessor.GetValue(sourceObject, name)); - } + Assert.True(typeAccessor.HasGettableMethod(nameof(MethodBasedViewModel.GetAnnotatedMethod))); + Assert.False(typeAccessor.HasGettableMethod(nameof(MethodBasedViewModel.GetMethod))); - /*========================================================================================================================== - | TEST: HAS SETTER: NAMES: RETURNS RESULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that returns true if the member is, in fact, settable. - /// - [Theory] - [InlineData(nameof(MemberAccessorViewModel.SetMethod), true)] - [InlineData(nameof(MemberAccessorViewModel.InvalidSetMethod), false)] - [InlineData(nameof(MemberAccessorViewModel.GetMethod), false)] - [InlineData(nameof(MemberAccessorViewModel.NonNullableProperty), true)] - [InlineData(nameof(MemberAccessorViewModel.WriteOnlyProperty), true)] - [InlineData(nameof(MemberAccessorViewModel.ReadOnlyProperty), false)] - [InlineData("MissingProperty", false)] - public void HasSetter_Names_ReturnsResult(string name, bool result) { - Assert.Equal(result, _typeAccessor.HasSetter(name)); - } + } - /*========================================================================================================================== - | TEST: HAS SETTABLE PROPERTY: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that returns the expected value. - /// - [Fact] - public void HasSettableProperty_ReturnsExpected() { + /*============================================================================================================================ + | TEST: GET VALUE: NAMES: RETURNS RESULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that returns the expected default value. + /// + [Theory] + [InlineData(nameof(MemberAccessorViewModel.NonNullableProperty), 1)] + [InlineData(nameof(MemberAccessorViewModel.NullableProperty), 2)] + [InlineData(nameof(MemberAccessorViewModel.NonNullableReferenceGetter), typeof(MemberAccessorTest))] + [InlineData(nameof(MemberAccessorViewModel.GetMethod), 3)] + [InlineData(nameof(MemberAccessorViewModel.ReadOnlyProperty), null)] + public void GetValue_Names_ReturnsResult(string name, object? result) { - var typeAccessor1 = TypeAccessorCache.GetTypeAccessor(); - var typeAccessor2 = TypeAccessorCache.GetTypeAccessor(); + var sourceObject = new MemberAccessorViewModel() { + NonNullableProperty = 1, + NullableProperty = 2, + NonNullableReferenceGetter = typeof(MemberAccessorTest) + }; - Assert.True(typeAccessor1.HasSettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.Key))); - Assert.False(typeAccessor1.HasSettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.ContentTypes))); - Assert.False(typeAccessor1.HasSettableProperty("MissingProperty")); - Assert.True(typeAccessor2.HasSettableProperty(nameof(TopicReferenceTopicViewModel.TopicReference), typeof(TopicViewModel))); + sourceObject.SetMethod(3); - } + Assert.Equal(result, _typeAccessor.GetValue(sourceObject, name)); + } - /*========================================================================================================================== - | TEST: HAS SETTABLE METHOD: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that - /// returns the expected value. - /// - [Fact] - public void HasSettableMethod_ReturnsExpected() { + /*============================================================================================================================ + | TEST: HAS SETTER: NAMES: RETURNS RESULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that returns true if the member is, in fact, settable. + /// + [Theory] + [InlineData(nameof(MemberAccessorViewModel.SetMethod), true)] + [InlineData(nameof(MemberAccessorViewModel.InvalidSetMethod), false)] + [InlineData(nameof(MemberAccessorViewModel.GetMethod), false)] + [InlineData(nameof(MemberAccessorViewModel.NonNullableProperty), true)] + [InlineData(nameof(MemberAccessorViewModel.WriteOnlyProperty), true)] + [InlineData(nameof(MemberAccessorViewModel.ReadOnlyProperty), false)] + [InlineData("MissingProperty", false)] + public void HasSetter_Names_ReturnsResult(string name, bool result) { + Assert.Equal(result, _typeAccessor.HasSetter(name)); + } - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + /*============================================================================================================================ + | TEST: HAS SETTABLE PROPERTY: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that returns the expected value. + /// + [Fact] + public void HasSettableProperty_ReturnsExpected() { - Assert.True(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.SetMethod))); - Assert.False(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.GetMethod))); - Assert.False(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.SetComplexMethod))); - Assert.False(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.SetParametersMethod))); - Assert.False(typeAccessor.HasSettableMethod("MissingMethod")); + var typeAccessor1 = TypeAccessorCache.GetTypeAccessor(); + var typeAccessor2 = TypeAccessorCache.GetTypeAccessor(); - } + Assert.True(typeAccessor1.HasSettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.Key))); + Assert.False(typeAccessor1.HasSettableProperty(nameof(ContentTypeDescriptorTopicBindingModel.ContentTypes))); + Assert.False(typeAccessor1.HasSettableProperty("MissingProperty")); + Assert.True(typeAccessor2.HasSettableProperty(nameof(TopicReferenceTopicViewModel.TopicReference), typeof(TopicViewModel))); - /*========================================================================================================================== - | TEST: SET VALUE: NAMES: SETS RESULTS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets a variety of values on a using and ensures that they are, in fact, set correctly. - /// - [Fact] - public void SetValue_Names_SetsResults() { - - var sourceObject = new MemberAccessorViewModel() { - NullableProperty = 5 - }; - - _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.NullableProperty), null); - _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.NonNullableProperty), 1); - _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.NonNullableReferenceGetter), typeof(MemberAccessorTest)); - _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.SetMethod), 5); - //_typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.WriteOnlyProperty), null); // Edge case is unsupported - - Assert.Null(sourceObject.NullableProperty); - Assert.Equal(1, sourceObject.NonNullableProperty); - Assert.Equal(typeof(MemberAccessorTest), sourceObject.NonNullableReferenceGetter); - Assert.Equal(5, sourceObject.GetMethod()); + } - } + /*============================================================================================================================ + | TEST: HAS SETTABLE METHOD: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that + /// returns the expected value. + /// + [Fact] + public void HasSettableMethod_ReturnsExpected() { - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: KEY: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a key value can be properly set using the method. - /// - [Fact] - public void SetPropertyValue_Key_SetsValue() { + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var topic = new Topic("Test", "ContentType"); + Assert.True(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.SetMethod))); + Assert.False(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.GetMethod))); + Assert.False(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.SetComplexMethod))); + Assert.False(typeAccessor.HasSettableMethod(nameof(MethodBasedViewModel.SetParametersMethod))); + Assert.False(typeAccessor.HasSettableMethod("MissingMethod")); - typeAccessor.SetPropertyValue(topic, "Key", "NewKey"); + } - var key = typeAccessor.GetPropertyValue(topic, "Key")?.ToString(); + /*============================================================================================================================ + | TEST: SET VALUE: NAMES: SETS RESULTS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets a variety of values on a using and ensures that they are, in fact, set correctly. + /// + [Fact] + public void SetValue_Names_SetsResults() { - Assert.Equal("NewKey", topic.Key); - Assert.Equal("NewKey", key); + var sourceObject = new MemberAccessorViewModel() { + NullableProperty = 5 + }; - } + _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.NullableProperty), null); + _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.NonNullableProperty), 1); + _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.NonNullableReferenceGetter), typeof(MemberAccessorTest)); + _typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.SetMethod), 5); + //_typeAccessor.SetValue(sourceObject, nameof(MemberAccessorViewModel.WriteOnlyProperty), null); // Edge case is unsupported - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: NULL VALUE: SETS TO NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that the method sets the property to null. - /// - [Fact] - public void SetPropertyValue_NullValue_SetsToNull() { + Assert.Null(sourceObject.NullableProperty); + Assert.Equal(1, sourceObject.NonNullableProperty); + Assert.Equal(typeof(MemberAccessorTest), sourceObject.NonNullableReferenceGetter); + Assert.Equal(5, sourceObject.GetMethod()); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var model = new NullablePropertyTopicViewModel() { - NullableInteger = 5 - }; + } - typeAccessor.SetPropertyValue(model, "NullableInteger", null); + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: KEY: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a key value can be properly set using the method. + /// + [Fact] + public void SetPropertyValue_Key_SetsValue() { - Assert.Null(model.NullableInteger); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var topic = new Topic("Test", "ContentType"); - } + typeAccessor.SetPropertyValue(topic, "Key", "NewKey"); - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: EMPTY VALUE: SETS TO NULL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that the sets the target property value to null if the value is set to . - /// - [Fact] - public void SetPropertyValue_EmptyValue_SetsToNull() { + var key = typeAccessor.GetPropertyValue(topic, "Key")?.ToString(); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var model = new NullablePropertyTopicViewModel() { - NullableInteger = 5 - }; + Assert.Equal("NewKey", topic.Key); + Assert.Equal("NewKey", key); - typeAccessor.SetPropertyValue(model, "NullableInteger", "", true); + } - Assert.Null(model.NullableInteger); + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: NULL VALUE: SETS TO NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that the method sets the property to null. + /// + [Fact] + public void SetPropertyValue_NullValue_SetsToNull() { - } + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var model = new NullablePropertyTopicViewModel() { + NullableInteger = 5 + }; - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: EMPTY VALUE: SETS DEFAULT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that the sets the value to its default if the value is set to and the - /// target property type is not nullable. - /// - [Fact] - public void SetPropertyValue_EmptyValue_SetsDefault() { + typeAccessor.SetPropertyValue(model, "NullableInteger", null); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var model = new NonNullablePropertyTopicViewModel(); + Assert.Null(model.NullableInteger); - typeAccessor.SetPropertyValue(model, "NonNullableInteger", "ABC", true); + } - Assert.Equal(0, model.NonNullableInteger); + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: EMPTY VALUE: SETS TO NULL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that the sets the target property value to null if the value is set to . + /// + [Fact] + public void SetPropertyValue_EmptyValue_SetsToNull() { - } + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var model = new NullablePropertyTopicViewModel() { + NullableInteger = 5 + }; - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: BOOLEAN: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a boolean value can be properly set using the method. - /// - [Fact] - public void SetPropertyValue_Boolean_SetsValue() { + typeAccessor.SetPropertyValue(model, "NullableInteger", "", true); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var topic = new Topic("Test", "ContentType"); + Assert.Null(model.NullableInteger); - typeAccessor.SetPropertyValue(topic, "IsHidden", "1", true); + } - Assert.True(topic.IsHidden); + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: EMPTY VALUE: SETS DEFAULT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that the sets the value to its default if the value is set to and the + /// target property type is not nullable. + /// + [Fact] + public void SetPropertyValue_EmptyValue_SetsDefault() { - } + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var model = new NonNullablePropertyTopicViewModel(); - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: DATE/TIME: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a date/time value can be properly set using the method. - /// - [Fact] - public void SetPropertyValue_DateTime_SetsValue() { + typeAccessor.SetPropertyValue(model, "NonNullableInteger", "ABC", true); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var topic = new Topic("Test", "ContentType"); + Assert.Equal(0, model.NonNullableInteger); - typeAccessor.SetPropertyValue(topic, "LastModified", "June 3, 2008", true); - Assert.Equal(new(2008, 6, 3), topic.LastModified); + } - typeAccessor.SetPropertyValue(topic, "LastModified", "2008-06-03", true); - Assert.Equal(new(2008, 6, 3), topic.LastModified); + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: BOOLEAN: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a boolean value can be properly set using the method. + /// + [Fact] + public void SetPropertyValue_Boolean_SetsValue() { - typeAccessor.SetPropertyValue(topic, "LastModified", "06/03/2008", true); - Assert.Equal(new(2008, 6, 3), topic.LastModified); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var topic = new Topic("Test", "ContentType"); - } + typeAccessor.SetPropertyValue(topic, "IsHidden", "1", true); - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: INVALID PROPERTY: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that an invalid property being set via the method throws an . - /// - [Fact] - public void SetPropertyValue_InvalidProperty_ReturnsFalse() { + Assert.True(topic.IsHidden); - var topic = new MemberAccessorViewModel(); + } - Assert.Throws(() => - _typeAccessor.SetPropertyValue(topic, "InvalidProperty", "Invalid") - ); + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: DATE/TIME: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a date/time value can be properly set using the method. + /// + [Fact] + public void SetPropertyValue_DateTime_SetsValue() { - } + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var topic = new Topic("Test", "ContentType"); - /*========================================================================================================================== - | TEST: SET METHOD VALUE: VALID VALUE: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a value can be properly set using the method. - /// - [Fact] - public void SetMethodValue_ValidValue_SetsValue() { + typeAccessor.SetPropertyValue(topic, "LastModified", "June 3, 2008", true); + Assert.Equal(new(2008, 6, 3), topic.LastModified); - var source = new MemberAccessorViewModel(); + typeAccessor.SetPropertyValue(topic, "LastModified", "2008-06-03", true); + Assert.Equal(new(2008, 6, 3), topic.LastModified); - _typeAccessor.SetMethodValue(source, nameof(MemberAccessorViewModel.SetMethod), "123", true); + typeAccessor.SetPropertyValue(topic, "LastModified", "06/03/2008", true); + Assert.Equal(new(2008, 6, 3), topic.LastModified); - Assert.Equal(123, source.GetMethod()); + } - } + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: INVALID PROPERTY: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that an invalid property being set via the method throws an . + /// + [Fact] + public void SetPropertyValue_InvalidProperty_ReturnsFalse() { - /*========================================================================================================================== - | TEST: SET METHOD VALUE: INVALID VALUE: DOESN'T SET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a value set with an invalid value using the method returns false. - /// - [Fact] - public void SetMethodValue_InvalidValue_DoesNotSetValue() { + var topic = new MemberAccessorViewModel(); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var source = new MethodBasedViewModel(); + Assert.Throws(() => + _typeAccessor.SetPropertyValue(topic, "InvalidProperty", "Invalid") + ); - typeAccessor.SetMethodValue(source, nameof(MethodBasedViewModel.SetMethod), "ABC", true); + } - Assert.Equal(0, source.GetMethod()); + /*============================================================================================================================ + | TEST: SET METHOD VALUE: VALID VALUE: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a value can be properly set using the method. + /// + [Fact] + public void SetMethodValue_ValidValue_SetsValue() { - } + var source = new MemberAccessorViewModel(); - /*========================================================================================================================== - | TEST: SET METHOD VALUE: INVALID MEMBER: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that setting an invalid method name using the method throws an exception. - /// - [Fact] - public void SetMethodValue_InvalidMember_ThrowsException() { + _typeAccessor.SetMethodValue(source, nameof(MemberAccessorViewModel.SetMethod), "123", true); - var source = new MemberAccessorViewModel(); + Assert.Equal(123, source.GetMethod()); - Assert.Throws(() => - _typeAccessor.SetMethodValue(source, "BogusMethod", "123") - ); + } - } + /*============================================================================================================================ + | TEST: SET METHOD VALUE: INVALID VALUE: DOESN'T SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a value set with an invalid value using the method returns false. + /// + [Fact] + public void SetMethodValue_InvalidValue_DoesNotSetValue() { - /*========================================================================================================================== - | TEST: SET METHOD VALUE: VALID REFENCE VALUE: SETS VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a reference value can be properly set using the method. - /// - [Fact] - public void SetMethodValue_ValidReferenceValue_SetsValue() { + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var source = new MethodBasedViewModel(); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var source = new MethodBasedReferenceViewModel(); - var reference = new TopicViewModel(); + typeAccessor.SetMethodValue(source, nameof(MethodBasedViewModel.SetMethod), "ABC", true); - typeAccessor.SetMethodValue(source, "SetMethod", reference); + Assert.Equal(0, source.GetMethod()); - Assert.Equal(reference, source.GetMethod()); + } - } + /*============================================================================================================================ + | TEST: SET METHOD VALUE: INVALID MEMBER: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that setting an invalid method name using the method throws an exception. + /// + [Fact] + public void SetMethodValue_InvalidMember_ThrowsException() { - /*========================================================================================================================== - | TEST: SET METHOD VALUE: INVALID REFERENCE VALUE: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a value set with an invalid value using the method throws an . - /// - [Fact] - public void SetMethodValue_InvalidReferenceValue_ThrowsException() { - - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var source = new MethodBasedReferenceViewModel(); - var reference = new EmptyViewModel(); - - Assert.Throws(() => - typeAccessor.SetMethodValue(source, "SetMethod", reference) - ); + var source = new MemberAccessorViewModel(); - } + Assert.Throws(() => + _typeAccessor.SetMethodValue(source, "BogusMethod", "123") + ); - /*========================================================================================================================== - | TEST: SET METHOD VALUE: INVALID REFERENCE MEMBER: THROWS EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that setting an invalid method name using the method returns false. - /// - [Fact] - public void SetMethodValue_InvalidReferenceMember_ThrowsException() { + } - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var source = new MethodBasedViewModel(); + /*============================================================================================================================ + | TEST: SET METHOD VALUE: VALID REFENCE VALUE: SETS VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a reference value can be properly set using the method. + /// + [Fact] + public void SetMethodValue_ValidReferenceValue_SetsValue() { - Assert.Throws(() => - typeAccessor.SetMethodValue(source, "BogusMethod", new object()) - ); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var source = new MethodBasedReferenceViewModel(); + var reference = new TopicViewModel(); - } + typeAccessor.SetMethodValue(source, "SetMethod", reference); - /*========================================================================================================================== - | TEST: SET METHOD VALUE: NULL REFERENCE VALUE: DOESN'T SET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and confirms that a value set with an null value using the method returns false. - /// - [Fact] - public void SetMethodValue_NullReferenceValue_DoesNotSetValue() { + Assert.Equal(reference, source.GetMethod()); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var source = new MethodBasedReferenceViewModel(); + } - typeAccessor.SetMethodValue(source, "SetMethod", (object?)null); + /*============================================================================================================================ + | TEST: SET METHOD VALUE: INVALID REFERENCE VALUE: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a value set with an invalid value using the method throws an . + /// + [Fact] + public void SetMethodValue_InvalidReferenceValue_ThrowsException() { - Assert.Null(source.GetMethod()); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var source = new MethodBasedReferenceViewModel(); + var reference = new EmptyViewModel(); - } + Assert.Throws(() => + typeAccessor.SetMethodValue(source, "SetMethod", reference) + ); - /*========================================================================================================================== - | TEST: MAYBE COMPATIBLE: CORRESPONDING TOPIC: CORRECTLY SET - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and based on the and - /// confirms that the underlying instances are correctly marked as based on the association with the . - /// - [Fact] - public void MaybeCompatible_CorrespondingTopic_CorrectlySet() { - - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - - Assert.Equal(9, typeAccessor.GetMembers(MemberTypes.Property).Count(m => m.MaybeCompatible)); - Assert.Equal(2, typeAccessor.GetMembers(MemberTypes.Property).Count(m => !m.MaybeCompatible)); - Assert.Equal(9, typeAccessor.ConstructorParameters.Count(m => m.MaybeCompatible)); - Assert.Equal(2, typeAccessor.ConstructorParameters.Count(m => !m.MaybeCompatible)); - Assert.True(typeAccessor.GetMember(nameof(CustomTopicTopicViewModel.TopicReference))?.MaybeCompatible); + } - } + /*============================================================================================================================ + | TEST: SET METHOD VALUE: INVALID REFERENCE MEMBER: THROWS EXCEPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that setting an invalid method name using the method returns false. + /// + [Fact] + public void SetMethodValue_InvalidReferenceMember_ThrowsException() { - /*========================================================================================================================== - | TEST: SET PROPERTY VALUE: REFLECTION PERFORMANCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets properties via reflection n number of times; quick way of evaluating the relative performance impact of changes. - /// - /// - /// Unit tests should run quickly, so this isn't an optimal place to test performance. As such, the counter should be set - /// to a small number when not being actively tested. Nevertheless, this provides a convenient test harness for quickly - /// evaluating the performance impact of changes or optimizations without setting up a fully performance test. To adjust - /// the number of iterations, simply increment the "totalIterations" variable. - /// - [Fact] - public void SetPropertyValue_ReflectionPerformance() { - - var totalIterations = 1; - var typeAccessor = TypeAccessorCache.GetTypeAccessor(); - var topic = new Topic("Test", "ContentType"); - - int i; - for (i = 0; i < totalIterations; i++) { - typeAccessor.SetPropertyValue(topic, "Key", "Key" + i); - } - - Assert.Equal("Key" + (i-1), topic.Key); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var source = new MethodBasedViewModel(); - } + Assert.Throws(() => + typeAccessor.SetMethodValue(source, "BogusMethod", new object()) + ); - /*========================================================================================================================== - | TEST: GET TYPE ACCESSOR: VALID TYPE: RETURNS TYPE ACCESSOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Calls the static to retrieve a given and ensures it is - /// correctly returned from the cache. - /// - /// - /// While the is separate from the class that this set of tests - /// is focused on, it is closely related, and the currently only - /// necessitates one unit test. As a result, it's being grouped in with the . - /// - [Fact] - public void GetTypeAccessor_ValidType_ReturnsTypeAccessor() { - - var typeAccessor = TypeAccessorCache.GetTypeAccessor(typeof(MemberAccessorViewModel)); - - Assert.NotNull(typeAccessor); - Assert.Equal(typeof(MemberAccessorViewModel), typeAccessor.Type); + } + + /*============================================================================================================================ + | TEST: SET METHOD VALUE: NULL REFERENCE VALUE: DOESN'T SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and confirms that a value set with an null value using the method returns false. + /// + [Fact] + public void SetMethodValue_NullReferenceValue_DoesNotSetValue() { + + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var source = new MethodBasedReferenceViewModel(); + + typeAccessor.SetMethodValue(source, "SetMethod", (object?)null); + Assert.Null(source.GetMethod()); + + } + + /*============================================================================================================================ + | TEST: MAYBE COMPATIBLE: CORRESPONDING TOPIC: CORRECTLY SET + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and based on the and + /// confirms that the underlying instances are correctly marked as based on the association with the . + /// + [Fact] + public void MaybeCompatible_CorrespondingTopic_CorrectlySet() { + + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + + Assert.Equal(9, typeAccessor.GetMembers(MemberTypes.Property).Count(m => m.MaybeCompatible)); + Assert.Equal(2, typeAccessor.GetMembers(MemberTypes.Property).Count(m => !m.MaybeCompatible)); + Assert.Equal(9, typeAccessor.ConstructorParameters.Count(m => m.MaybeCompatible)); + Assert.Equal(2, typeAccessor.ConstructorParameters.Count(m => !m.MaybeCompatible)); + Assert.True(typeAccessor.GetMember(nameof(CustomTopicTopicViewModel.TopicReference))?.MaybeCompatible); + + } + + /*============================================================================================================================ + | TEST: SET PROPERTY VALUE: REFLECTION PERFORMANCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets properties via reflection n number of times; quick way of evaluating the relative performance impact of changes. + /// + /// + /// Unit tests should run quickly, so this isn't an optimal place to test performance. As such, the counter should be set + /// to a small number when not being actively tested. Nevertheless, this provides a convenient test harness for quickly + /// evaluating the performance impact of changes or optimizations without setting up a fully performance test. To adjust + /// the number of iterations, simply increment the "totalIterations" variable. + /// + [Fact] + public void SetPropertyValue_ReflectionPerformance() { + + var totalIterations = 1; + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + var topic = new Topic("Test", "ContentType"); + + int i; + for (i = 0; i < totalIterations; i++) { + typeAccessor.SetPropertyValue(topic, "Key", "Key" + i); } - } //Class -} //Namespace \ No newline at end of file + Assert.Equal("Key" + (i-1), topic.Key); + + } + + /*============================================================================================================================ + | TEST: GET TYPE ACCESSOR: VALID TYPE: RETURNS TYPE ACCESSOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Calls the static to retrieve a given and ensures it is + /// correctly returned from the cache. + /// + /// + /// While the is separate from the class that this set of tests + /// is focused on, it is closely related, and the currently only + /// necessitates one unit test. As a result, it's being grouped in with the . + /// + [Fact] + public void GetTypeAccessor_ValidType_ReturnsTypeAccessor() { + + var typeAccessor = TypeAccessorCache.GetTypeAccessor(); + + Assert.NotNull(typeAccessor); + Assert.Equal(typeof(MemberAccessorViewModel), typeAccessor.Type); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/TypeLookupServiceTest.cs b/OnTopic.Tests/TypeLookupServiceTest.cs index 9428e0a8..2caba245 100644 --- a/OnTopic.Tests/TypeLookupServiceTest.cs +++ b/OnTopic.Tests/TypeLookupServiceTest.cs @@ -10,193 +10,192 @@ using OnTopic.Tests.ViewModels; using Xunit; -namespace OnTopic.Tests { +namespace OnTopic.Tests; + +/*============================================================================================================================== +| CLASS: TYPE LOOKUP SERVICE TEST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides unit tests for the interface and its implementations, such as the , , , +/// and the underlying . +/// +[ExcludeFromCodeCoverage] +public class TypeLookupServiceTest { /*============================================================================================================================ - | CLASS: TYPE LOOKUP SERVICE TEST + | TEST: TYPE COLLECTION: CONSTRUCTOR: CONTAINS UNIQUE TYPES \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides unit tests for the interface and its implementations, such as the , , , - /// and the underlying . + /// Initializes a new with a list of objects, including a duplicate. + /// Confirms that only the unique values are provided. /// - [ExcludeFromCodeCoverage] - public class TypeLookupServiceTest { - - /*========================================================================================================================== - | TEST: TYPE COLLECTION: CONSTRUCTOR: CONTAINS UNIQUE TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with a list of objects, including a duplicate. - /// Confirms that only the unique values are provided. - /// - [Fact] - public void TypeCollection_Constructor_ContainsUniqueTypes() { - - var topics = new List { - typeof(BasicTopicBindingModel), - typeof(CustomTopic), - typeof(CustomTopic) - }; - var typeCollection = new TypeCollection(topics); - - Assert.Equal(2, typeCollection.Count); - Assert.Contains(typeof(CustomTopic), typeCollection); - Assert.DoesNotContain(typeof(Topic), typeCollection); - - } - - /*========================================================================================================================== - | TEST: STATIC TYPE LOOKUP SERVICE: TRY ADD: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and calls to - /// ensure it correctly adds new items, but not duplicate items. - /// - [Fact] - public void StaticLookupService_TryAdd_ReturnsExpected() { - - var topics = new List { - typeof(CustomTopic) - }; - var lookupService = new DummyStaticTypeLookupService(topics); - - Assert.False(lookupService.TryAdd(typeof(CustomTopic))); - Assert.True(lookupService.TryAdd(typeof(Topic))); - - } - - /*========================================================================================================================== - | TEST: STATIC TYPE LOOKUP SERVICE: LOOKUP: RETURNS FALLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and calls - /// to ensure it correctly falls back to subsequent items. - /// - [Fact] - public void StaticLookupService_Lookup_ReturnsFallback() { - - var topics = new List { + [Fact] + public void TypeCollection_Constructor_ContainsUniqueTypes() { + + var topics = new List { + typeof(BasicTopicBindingModel), + typeof(CustomTopic), + typeof(CustomTopic) + }; + var typeCollection = new TypeCollection(topics); + + Assert.Equal(2, typeCollection.Count); + Assert.Contains(typeof(CustomTopic), typeCollection); + Assert.DoesNotContain(typeof(Topic), typeCollection); + + } + + /*============================================================================================================================ + | TEST: STATIC TYPE LOOKUP SERVICE: TRY ADD: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and calls to + /// ensure it correctly adds new items, but not duplicate items. + /// + [Fact] + public void StaticLookupService_TryAdd_ReturnsExpected() { + + var topics = new List { + typeof(CustomTopic) + }; + var lookupService = new DummyStaticTypeLookupService(topics); + + Assert.False(lookupService.TryAdd(typeof(CustomTopic))); + Assert.True(lookupService.TryAdd(typeof(Topic))); + + } + + /*============================================================================================================================ + | TEST: STATIC TYPE LOOKUP SERVICE: LOOKUP: RETURNS FALLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and calls + /// to ensure it correctly falls back to subsequent items. + /// + [Fact] + public void StaticLookupService_Lookup_ReturnsFallback() { + + var topics = new List { + typeof(AscendentTopicViewModel), + typeof(FallbackViewModel) + }; + var lookupService = new StaticTypeLookupService(topics); + + Assert.Equal(typeof(FallbackViewModel), lookupService.Lookup(nameof(EmptyViewModel), nameof(FallbackViewModel))); + + } + + /*============================================================================================================================ + | TEST: STATIC TYPE LOOKUP SERVICE: ADD OR REPLACE: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and calls + /// to ensure it correctly adds new items, but and replaces duplicate items. + /// + [Fact] + public void StaticLookupService_AddOrReplace_ReturnsExpected() { + + var lookupService = new DummyStaticTypeLookupService(); + + lookupService.AddOrReplace(typeof(System.Diagnostics.Contracts.Contract)); + lookupService.AddOrReplace(typeof(Internal.Diagnostics.Contract)); + + Assert.Equal(typeof(Internal.Diagnostics.Contract), lookupService.Lookup(nameof(Internal.Diagnostics.Contract))); + + } + + /*============================================================================================================================ + | TEST: DYNAMIC TYPE LOOKUP SERVICE: PREDICATE: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a with a custom predicate and calls the underlying to ensure it correctly adds the expected items. + /// + [Fact] + public void DynamicTypeLookupService_Predicate_ReturnsExpected() { + + var lookupService = new DynamicTypeLookupService(t => + t.Namespace == typeof(KeyOnlyTopicViewModel).Namespace && + typeof(KeyOnlyTopicViewModel).IsAssignableFrom(t) + ); + + Assert.NotNull(lookupService.Lookup(nameof(KeyOnlyTopicViewModel))); + Assert.NotNull(lookupService.Lookup(nameof(AmbiguousRelationTopicViewModel))); + Assert.Null(lookupService.Lookup(nameof(EmptyViewModel))); + + } + + /*============================================================================================================================ + | TEST: COMPOSITE TYPE LOOKUP SERVICE: LOOKUP: RETURNS FALLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a and calls to ensure it correctly falls back to each implementation. + /// + [Fact] + public void CompositeTypeLookupService_Lookup_ReturnsFallback() { + + var lookupService1 = new StaticTypeLookupService( + new List { + typeof(EmptyViewModel), + typeof(FallbackViewModel), + typeof(Internal.Diagnostics.Contract) + } + ); + + var lookupService2 = new StaticTypeLookupService( + new List { typeof(AscendentTopicViewModel), - typeof(FallbackViewModel) - }; - var lookupService = new StaticTypeLookupService(topics); - - Assert.Equal(typeof(FallbackViewModel), lookupService.Lookup(nameof(EmptyViewModel), nameof(FallbackViewModel))); - - } - - /*========================================================================================================================== - | TEST: STATIC TYPE LOOKUP SERVICE: ADD OR REPLACE: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and calls - /// to ensure it correctly adds new items, but and replaces duplicate items. - /// - [Fact] - public void StaticLookupService_AddOrReplace_ReturnsExpected() { - - var lookupService = new DummyStaticTypeLookupService(); - - lookupService.AddOrReplace(typeof(System.Diagnostics.Contracts.Contract)); - lookupService.AddOrReplace(typeof(Internal.Diagnostics.Contract)); - - Assert.Equal(typeof(Internal.Diagnostics.Contract), lookupService.Lookup(nameof(Internal.Diagnostics.Contract))); - - } - - /*========================================================================================================================== - | TEST: DYNAMIC TYPE LOOKUP SERVICE: PREDICATE: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a with a custom predicate and calls the underlying to ensure it correctly adds the expected items. - /// - [Fact] - public void DynamicTypeLookupService_Predicate_ReturnsExpected() { - - var lookupService = new DynamicTypeLookupService(t => - t.Namespace == typeof(KeyOnlyTopicViewModel).Namespace && - typeof(KeyOnlyTopicViewModel).IsAssignableFrom(t) - ); - - Assert.NotNull(lookupService.Lookup(nameof(KeyOnlyTopicViewModel))); - Assert.NotNull(lookupService.Lookup(nameof(AmbiguousRelationTopicViewModel))); - Assert.Null(lookupService.Lookup(nameof(EmptyViewModel))); - - } - - /*========================================================================================================================== - | TEST: COMPOSITE TYPE LOOKUP SERVICE: LOOKUP: RETURNS FALLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a and calls to ensure it correctly falls back to each implementation. - /// - [Fact] - public void CompositeTypeLookupService_Lookup_ReturnsFallback() { - - var lookupService1 = new StaticTypeLookupService( - new List { - typeof(EmptyViewModel), - typeof(FallbackViewModel), - typeof(Internal.Diagnostics.Contract) - } - ); - - var lookupService2 = new StaticTypeLookupService( - new List { - typeof(AscendentTopicViewModel), - typeof(FallbackViewModel), - typeof(System.Diagnostics.Contracts.Contract) - } - ); - - var lookupService = new CompositeTypeLookupService(lookupService1, lookupService2); - - Assert.Equal(typeof(System.Diagnostics.Contracts.Contract), lookupService.Lookup("Contract")); - Assert.Equal(typeof(FallbackViewModel), lookupService.Lookup("Missing", "FallbackViewModel")); - Assert.Equal(typeof(FallbackViewModel), lookupService.Lookup("Missing")?? typeof(FallbackViewModel)); - - } - - /*========================================================================================================================== - | TEST: DEFAULT TOPIC LOOKUP SERVICE: LOOKUP: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests the to ensure it correctly identifies not only the built-in models, but - /// also an additional model injected via the constructor. - /// - [Fact] - public void DefaultTopicLookupService_Lookup_ReturnsExpected() { - - var topics = new List { - typeof(CustomTopic) - }; - var lookupService = new DefaultTopicLookupService(topics); - - Assert.Equal(typeof(AttributeDescriptor), lookupService.Lookup(nameof(AttributeDescriptor))); - Assert.Equal(typeof(CustomTopic), lookupService.Lookup(nameof(CustomTopic))); - Assert.Null(lookupService.Lookup("TextAttributeDescriptor")); - - } - - /*========================================================================================================================== - | TEST: DYNAMIC TOPIC BINDING MODEL LOOKUP SERVICE: LOOKUP: RETURNS EXPECTED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Tests the to ensure it correctly identifies binding models that - /// are defined as part of the test project. - /// - [Fact] - public void DynamicTopicBindingModelLookupService_Lookup_ReturnsExpected() { - - var lookupService = new DynamicTopicBindingModelLookupService(); - - Assert.Equal(typeof(PageTopicBindingModel), lookupService.Lookup(nameof(PageTopicBindingModel))); - Assert.Null(lookupService.Lookup("MissingTopicBindingModel")); - - } - - } //Class -} //Namespace \ No newline at end of file + typeof(FallbackViewModel), + typeof(System.Diagnostics.Contracts.Contract) + } + ); + + var lookupService = new CompositeTypeLookupService(lookupService1, lookupService2); + + Assert.Equal(typeof(System.Diagnostics.Contracts.Contract), lookupService.Lookup("Contract")); + Assert.Equal(typeof(FallbackViewModel), lookupService.Lookup("Missing", "FallbackViewModel")); + Assert.Equal(typeof(FallbackViewModel), lookupService.Lookup("Missing")?? typeof(FallbackViewModel)); + + } + + /*============================================================================================================================ + | TEST: DEFAULT TOPIC LOOKUP SERVICE: LOOKUP: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests the to ensure it correctly identifies not only the built-in models, but + /// also an additional model injected via the constructor. + /// + [Fact] + public void DefaultTopicLookupService_Lookup_ReturnsExpected() { + + var topics = new List { + typeof(CustomTopic) + }; + var lookupService = new DefaultTopicLookupService(topics); + + Assert.Equal(typeof(AttributeDescriptor), lookupService.Lookup(nameof(AttributeDescriptor))); + Assert.Equal(typeof(CustomTopic), lookupService.Lookup(nameof(CustomTopic))); + Assert.Null(lookupService.Lookup("TextAttributeDescriptor")); + + } + + /*============================================================================================================================ + | TEST: DYNAMIC TOPIC BINDING MODEL LOOKUP SERVICE: LOOKUP: RETURNS EXPECTED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Tests the to ensure it correctly identifies binding models that + /// are defined as part of the test project. + /// + [Fact] + public void DynamicTopicBindingModelLookupService_Lookup_ReturnsExpected() { + + var lookupService = new DynamicTopicBindingModelLookupService(); + + Assert.Equal(typeof(PageTopicBindingModel), lookupService.Lookup(nameof(PageTopicBindingModel))); + Assert.Null(lookupService.Lookup("MissingTopicBindingModel")); + + } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/AmbiguousRelationTopicViewModel.cs b/OnTopic.Tests/ViewModels/AmbiguousRelationTopicViewModel.cs index 68c39f6e..07304cda 100644 --- a/OnTopic.Tests/ViewModels/AmbiguousRelationTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/AmbiguousRelationTopicViewModel.cs @@ -4,28 +4,27 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: AMBIGUOUS RELATION - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a an ambiguously mapped relationship (). - /// - /// - /// - /// The uses to set the relationship key to - /// AmbiguousRelationship and the to . - /// AmbiguousRelationship refers to a relationship that is both outgoing and incoming. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class AmbiguousRelationTopicViewModel: KeyOnlyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: AMBIGUOUS RELATION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a an ambiguously mapped relationship (). +/// +/// +/// +/// The uses to set the relationship key to +/// AmbiguousRelationship and the to . +/// AmbiguousRelationship refers to a relationship that is both outgoing and incoming. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class AmbiguousRelationTopicViewModel: KeyOnlyTopicViewModel { - [Collection("AmbiguousRelationship", Type= CollectionType.IncomingRelationship)] - public Collection RelationshipAlias { get; } = new(); + [Collection("AmbiguousRelationship", Type= CollectionType.IncomingRelationship)] + public Collection RelationshipAlias { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/AscendentSpecializedTopicViewModel.cs b/OnTopic.Tests/ViewModels/AscendentSpecializedTopicViewModel.cs index 1a2dee38..a2250e2b 100644 --- a/OnTopic.Tests/ViewModels/AscendentSpecializedTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/AscendentSpecializedTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: SPECIALIZED ASCENDENT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a derived version of with an additional property (), - /// thus allowing tests to confirm that specialized content types are correctly mapped. - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class AscendentSpecializedTopicViewModel: AscendentTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: SPECIALIZED ASCENDENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a derived version of with an additional property (), +/// thus allowing tests to confirm that specialized content types are correctly mapped. +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class AscendentSpecializedTopicViewModel: AscendentTopicViewModel { - public bool IsRoot { get; set; } + public bool IsRoot { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/AscendentTopicViewModel.cs b/OnTopic.Tests/ViewModels/AscendentTopicViewModel.cs index 364d2030..bdbaab39 100644 --- a/OnTopic.Tests/ViewModels/AscendentTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/AscendentTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: ASCENDENT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () for mapping ascendent associations. - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class AscendentTopicViewModel: KeyOnlyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: ASCENDENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () for mapping ascendent associations. +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class AscendentTopicViewModel: KeyOnlyTopicViewModel { - [Include(AssociationTypes.Parents)] - public AscendentTopicViewModel? Parent { get; set; } + [Include(AssociationTypes.Parents)] + public AscendentTopicViewModel? Parent { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/AttributeDictionaryConstructorTopicViewModel.cs b/OnTopic.Tests/ViewModels/AttributeDictionaryConstructorTopicViewModel.cs index b10b88cf..35c1ed3f 100644 --- a/OnTopic.Tests/ViewModels/AttributeDictionaryConstructorTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/AttributeDictionaryConstructorTopicViewModel.cs @@ -4,43 +4,42 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: ATTRIBUTE DICTIONARY CONSTRUCTOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing a constructor with a . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public record AttributeDictionaryConstructorTopicViewModel: PageTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: ATTRIBUTE DICTIONARY CONSTRUCTOR + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed data transfer object for testing a constructor with a . + /// Initializes a new with an dictionary. /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public record AttributeDictionaryConstructorTopicViewModel: PageTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public AttributeDictionaryConstructorTopicViewModel(AttributeDictionary attributes) : base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - MappedProperty = attributes.GetValue(nameof(MappedProperty)); - } + /// An of attribute values. + public AttributeDictionaryConstructorTopicViewModel(AttributeDictionary attributes) : base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + MappedProperty = attributes.GetValue(nameof(MappedProperty)); + } - /// - /// Initializes a new with no parameters. - /// - public AttributeDictionaryConstructorTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public AttributeDictionaryConstructorTopicViewModel() { } - /*========================================================================================================================== - | PROPERTIES - \-------------------------------------------------------------------------------------------------------------------------*/ - public string? MappedProperty { get; init; } - public string? UnmappedProperty { get; init; } + /*============================================================================================================================ + | PROPERTIES + \---------------------------------------------------------------------------------------------------------------------------*/ + public string? MappedProperty { get; init; } + public string? UnmappedProperty { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/CircularTopicViewModel.cs b/OnTopic.Tests/ViewModels/CircularTopicViewModel.cs index b0ffbaa5..19e35b3a 100644 --- a/OnTopic.Tests/ViewModels/CircularTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/CircularTopicViewModel.cs @@ -4,24 +4,23 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: CIRCULAR TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with a circular reference. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class CircularTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: CIRCULAR TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with a circular reference. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class CircularTopicViewModel { - [Include(AssociationTypes.Parents)] - public CircularTopicViewModel? Parent { get; set; } + [Include(AssociationTypes.Parents)] + public CircularTopicViewModel? Parent { get; set; } - [Include(AssociationTypes.Children | AssociationTypes.Parents)] - public Collection Children { get; } = new(); + [Include(AssociationTypes.Children | AssociationTypes.Parents)] + public Collection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/CompatiblePropertyTopicViewModel.cs b/OnTopic.Tests/ViewModels/CompatiblePropertyTopicViewModel.cs index 9bf36ae8..aa546a9f 100644 --- a/OnTopic.Tests/ViewModels/CompatiblePropertyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/CompatiblePropertyTopicViewModel.cs @@ -5,23 +5,22 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: COMPATIBLE PROPERTY TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with a property that maps to a source object, but isn't - /// otherwise mapped by any of the conversion functions. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class CompatiblePropertyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: COMPATIBLE PROPERTY TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with a property that maps to a source object, but isn't +/// otherwise mapped by any of the conversion functions. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class CompatiblePropertyTopicViewModel { - public ModelType ModelType { get; set; } + public ModelType ModelType { get; set; } - public Collection? VersionHistory { get; init; } + public Collection? VersionHistory { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/ConstructedTopicViewModel.cs b/OnTopic.Tests/ViewModels/ConstructedTopicViewModel.cs index f6371267..237932eb 100644 --- a/OnTopic.Tests/ViewModels/ConstructedTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/ConstructedTopicViewModel.cs @@ -4,37 +4,36 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: CONSTRUCTED - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a topic view model with a constructor containing a variety of parameters—including parameters with attributes, - /// and representing each of the main types of attribute (e.g., scalar values, relationships, references, etc.). - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ConstructedTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: CONSTRUCTED +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a topic view model with a constructor containing a variety of parameters—including parameters with attributes, +/// and representing each of the main types of attribute (e.g., scalar values, relationships, references, etc.). +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ConstructedTopicViewModel { - public ConstructedTopicViewModel( - [AttributeKey("Value")]string scalarValue, - [Include(AssociationTypes.All)] - ConstructedTopicViewModel? topicReference, - [Collection("Related")]Collection? relationships, - [DisableMapping]int optionalValue = 5 - ) { - ScalarValue = scalarValue; - TopicReference = topicReference; - Relationships = relationships; - OptionalValue = optionalValue; - } + public ConstructedTopicViewModel( + [AttributeKey("Value")]string scalarValue, + [Include(AssociationTypes.All)] + ConstructedTopicViewModel? topicReference, + [Collection("Related")]Collection? relationships, + [DisableMapping]int optionalValue = 5 + ) { + ScalarValue = scalarValue; + TopicReference = topicReference; + Relationships = relationships; + OptionalValue = optionalValue; + } - public string ScalarValue { get; } - public ConstructedTopicViewModel? TopicReference { get; } - public Collection? Relationships { get; } - public int OptionalValue { get; } = 1; + public string ScalarValue { get; } + public ConstructedTopicViewModel? TopicReference { get; } + public Collection? Relationships { get; } + public int OptionalValue { get; } = 1; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/ConvertPropertyViewModel.cs b/OnTopic.Tests/ViewModels/ConvertPropertyViewModel.cs index 8f67dddb..f49b7b75 100644 --- a/OnTopic.Tests/ViewModels/ConvertPropertyViewModel.cs +++ b/OnTopic.Tests/ViewModels/ConvertPropertyViewModel.cs @@ -5,25 +5,24 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: CONVERT PROPERTY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a data transfer object with two properties which are intended to map to source properties of data types which - /// are different, but where the is capable of converting between them. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ConvertPropertyViewModel { +/*============================================================================================================================== +| VIEW MODEL: CONVERT PROPERTY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a data transfer object with two properties which are intended to map to source properties of data types which +/// are different, but where the is capable of converting between them. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ConvertPropertyViewModel { - [AttributeKey("BooleanAsStringAttribute")] - public bool BooleanAttribute { get; set; } + [AttributeKey("BooleanAsStringAttribute")] + public bool BooleanAttribute { get; set; } - [AttributeKey("NumericAttribute")] - public string? NumericAsStringAttribute { get; set; } + [AttributeKey("NumericAttribute")] + public string? NumericAsStringAttribute { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/CustomTopicTopicViewModel.cs b/OnTopic.Tests/ViewModels/CustomTopicTopicViewModel.cs index 1e77b1ec..fb723b93 100644 --- a/OnTopic.Tests/ViewModels/CustomTopicTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/CustomTopicTopicViewModel.cs @@ -6,147 +6,146 @@ using OnTopic.Internal.Reflection; using OnTopic.Tests.Entities; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: CUSTOM TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a topic view model which maps to the . +/// +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +/// Typically, topics wouldn't end in "Topic" (outside of ). Because does, +/// the corresponding topic view model must be named (with two Topic). +/// Otherwise, when the attempts to match it to its implied content type, it will strip the +/// TopicViewModel, per conventions, and discover that there isn't a match for Custom. This is a peculiarity +/// of the test case, and not something we'd expect in real-life scenarios. +/// +/// +public record CustomTopicTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: CUSTOM TOPIC + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + public CustomTopicTopicViewModel( + string title, + string webPath, + string? textAttribute, + bool booleanAttribute, + string booleanAsStringAttribute, + int numericAttribute, + string nonNullableAttribute, + DateTime dateTimeAttribute, + Topic? topicReference, + string? unmatchedMember, + DateTime? isHidden + ) { + Title = title; + WebPath = webPath; + TextAttribute = textAttribute; + BooleanAttribute = booleanAttribute; + BooleanAsStringAttribute = booleanAsStringAttribute; + NumericAttribute = numericAttribute; + NonNullableAttribute = nonNullableAttribute; + DateTimeAttribute = dateTimeAttribute; + TopicReference = topicReference; + UnmatchedMember = unmatchedMember; + IsHidden = isHidden; + } + + /*============================================================================================================================ + | TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the property. + /// + public string Title { get; init; } + + /*============================================================================================================================ + | WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the root-relative web path of the Topic, based on an assumption that the root topic is bound to the root of + /// the site. + /// + public string WebPath { get; init; } + + /*============================================================================================================================ + | TEXT ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a text property which is intended to be mapped to a text attribute. + /// + public string? TextAttribute { get; init; } + + /*============================================================================================================================ + | BOOLEAN ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a Boolean property which is intended to be mapped to a Boolean attribute. + /// + public bool BooleanAttribute { get; init; } + + /*============================================================================================================================ + | BOOLEAN AS STRING ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a string property which is intended to be mapped to a Boolean attribute. + /// + public string BooleanAsStringAttribute { get; init; } + + /*============================================================================================================================ + | NUMERIC ATTRIBUTE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a topic view model which maps to the . + /// Provides a numeric property which is intended to be mapped to a numeric attribute. /// - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - /// Typically, topics wouldn't end in "Topic" (outside of ). Because does, - /// the corresponding topic view model must be named (with two Topic). - /// Otherwise, when the attempts to match it to its implied content type, it will strip the - /// TopicViewModel, per conventions, and discover that there isn't a match for Custom. This is a peculiarity - /// of the test case, and not something we'd expect in real-life scenarios. - /// - /// - public record CustomTopicTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - public CustomTopicTopicViewModel( - string title, - string webPath, - string? textAttribute, - bool booleanAttribute, - string booleanAsStringAttribute, - int numericAttribute, - string nonNullableAttribute, - DateTime dateTimeAttribute, - Topic? topicReference, - string? unmatchedMember, - DateTime? isHidden - ) { - Title = title; - WebPath = webPath; - TextAttribute = textAttribute; - BooleanAttribute = booleanAttribute; - BooleanAsStringAttribute = booleanAsStringAttribute; - NumericAttribute = numericAttribute; - NonNullableAttribute = nonNullableAttribute; - DateTimeAttribute = dateTimeAttribute; - TopicReference = topicReference; - UnmatchedMember = unmatchedMember; - IsHidden = isHidden; - } - - /*========================================================================================================================== - | TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the property. - /// - public string Title { get; init; } - - /*========================================================================================================================== - | WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the root-relative web path of the Topic, based on an assumption that the root topic is bound to the root of - /// the site. - /// - public string WebPath { get; init; } - - /*========================================================================================================================== - | TEXT ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a text property which is intended to be mapped to a text attribute. - /// - public string? TextAttribute { get; init; } - - /*========================================================================================================================== - | BOOLEAN ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a Boolean property which is intended to be mapped to a Boolean attribute. - /// - public bool BooleanAttribute { get; init; } - - /*========================================================================================================================== - | BOOLEAN AS STRING ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a string property which is intended to be mapped to a Boolean attribute. - /// - public string BooleanAsStringAttribute { get; init; } - - /*========================================================================================================================== - | NUMERIC ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a numeric property which is intended to be mapped to a numeric attribute. - /// - public int NumericAttribute { get; init; } - - /*========================================================================================================================== - | NON-NULLABLE ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a property which does not permit null values as a means of ensuring the business logic is enforced when - /// removing values. - /// - public string NonNullableAttribute { get; init; } - - /*========================================================================================================================== - | DATE/TIME ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a date/time property which is intended to be mapped to a date/time attribute. - /// - public DateTime DateTimeAttribute { get; init; } - - /*========================================================================================================================== - | TOPIC REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a topic reference property which is intended to be mapped to a topic reference. - /// - public Topic? TopicReference { get; init; } - - /*========================================================================================================================== - | UNMATCHED MEMBER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a member that doesn't match any members of either or . - /// - public string? UnmatchedMember { get; init; } - - /*========================================================================================================================== - | MISMATCHED MEMBER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a member that corresponds to a property on , but with an incompatible type. - /// - public DateTime? IsHidden { get; init; } - - - } //Class -} //Namespace \ No newline at end of file + public int NumericAttribute { get; init; } + + /*============================================================================================================================ + | NON-NULLABLE ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a property which does not permit null values as a means of ensuring the business logic is enforced when + /// removing values. + /// + public string NonNullableAttribute { get; init; } + + /*============================================================================================================================ + | DATE/TIME ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a date/time property which is intended to be mapped to a date/time attribute. + /// + public DateTime DateTimeAttribute { get; init; } + + /*============================================================================================================================ + | TOPIC REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a topic reference property which is intended to be mapped to a topic reference. + /// + public Topic? TopicReference { get; init; } + + /*============================================================================================================================ + | UNMATCHED MEMBER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a member that doesn't match any members of either or . + /// + public string? UnmatchedMember { get; init; } + + /*============================================================================================================================ + | MISMATCHED MEMBER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a member that corresponds to a property on , but with an incompatible type. + /// + public DateTime? IsHidden { get; init; } + + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/DefaultPropertyTopicViewModel.cs b/OnTopic.Tests/ViewModels/DefaultPropertyTopicViewModel.cs index 4c42ab7d..c87c0fc6 100644 --- a/OnTopic.Tests/ViewModels/DefaultPropertyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/DefaultPropertyTopicViewModel.cs @@ -5,27 +5,26 @@ \=============================================================================================================================*/ using System.ComponentModel; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: DEFAULT VALUE TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views properties annotated with default value attributes. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class DefaultValueTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: DEFAULT VALUE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views properties annotated with default value attributes. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class DefaultValueTopicViewModel { - [DefaultValue("Default")] - public string? DefaultString { get; set; } + [DefaultValue("Default")] + public string? DefaultString { get; set; } - [DefaultValue(10)] - public int DefaultInt { get; set; } + [DefaultValue(10)] + public int DefaultInt { get; set; } - [DefaultValue(true)] - public bool DefaultBool { get; set; } + [DefaultValue(true)] + public bool DefaultBool { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/DescendentSpecializedTopicViewModel.cs b/OnTopic.Tests/ViewModels/DescendentSpecializedTopicViewModel.cs index 0bf607ff..ce82d352 100644 --- a/OnTopic.Tests/ViewModels/DescendentSpecializedTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/DescendentSpecializedTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: DESCENDENT SPECIALIZED - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a derived version of with an additional property (), - /// thus allowing tests to confirm that specialized content types are correctly mapped. - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public record DescendentSpecializedTopicViewModel: DescendentTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: DESCENDENT SPECIALIZED +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a derived version of with an additional property (), +/// thus allowing tests to confirm that specialized content types are correctly mapped. +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public record DescendentSpecializedTopicViewModel: DescendentTopicViewModel { - public bool IsLeaf { get; set; } + public bool IsLeaf { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/DescendentTopicViewModel.cs b/OnTopic.Tests/ViewModels/DescendentTopicViewModel.cs index 58e0dd64..abc5ea3d 100644 --- a/OnTopic.Tests/ViewModels/DescendentTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/DescendentTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: DESCENDENT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () for mapping descending associations. - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public record DescendentTopicViewModel: TopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: DESCENDENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () for mapping descending associations. +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public record DescendentTopicViewModel: TopicViewModel { - [Include(AssociationTypes.Children)] - public TopicViewModelCollection Children { get; } = new(); + [Include(AssociationTypes.Children)] + public TopicViewModelCollection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/DisableMappingTopicViewModel.cs b/OnTopic.Tests/ViewModels/DisableMappingTopicViewModel.cs index 90612729..b0a21fa0 100644 --- a/OnTopic.Tests/ViewModels/DisableMappingTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/DisableMappingTopicViewModel.cs @@ -4,22 +4,21 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: DISABLE MAPPING - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () which is annotated with the . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class DisableMappingTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: DISABLE MAPPING +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () which is annotated with the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class DisableMappingTopicViewModel { - [DisableMapping] - public string? Key { get; set; } + [DisableMapping] + public string? Key { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/EmptyViewModel.cs b/OnTopic.Tests/ViewModels/EmptyViewModel.cs index 4636ec9c..a04e2f15 100644 --- a/OnTopic.Tests/ViewModels/EmptyViewModel.cs +++ b/OnTopic.Tests/ViewModels/EmptyViewModel.cs @@ -5,19 +5,18 @@ \=============================================================================================================================*/ using OnTopic.Models; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: EMPTY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A view model that does not implement any properties or interfaces. This will be invalid for mapping models that expect - /// e.g. or . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class EmptyViewModel { +/*============================================================================================================================== +| VIEW MODEL: EMPTY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// A view model that does not implement any properties or interfaces. This will be invalid for mapping models that expect +/// e.g. or . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class EmptyViewModel { - } } \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/FallbackViewModel.cs b/OnTopic.Tests/ViewModels/FallbackViewModel.cs index 3af9b753..c85699dd 100644 --- a/OnTopic.Tests/ViewModels/FallbackViewModel.cs +++ b/OnTopic.Tests/ViewModels/FallbackViewModel.cs @@ -5,19 +5,18 @@ \=============================================================================================================================*/ using OnTopic.Lookup; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: FALLBACK - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a view model with the ViewModel suffix instead of the TopicViewModel conventions to confirm that - /// the will correctly fall back. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class FallbackViewModel { +/*============================================================================================================================== +| VIEW MODEL: FALLBACK +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a view model with the ViewModel suffix instead of the TopicViewModel conventions to confirm that +/// the will correctly fall back. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class FallbackViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/FilteredContentTypeTopicViewModel.cs b/OnTopic.Tests/ViewModels/FilteredContentTypeTopicViewModel.cs index 72347cb2..04a85cd1 100644 --- a/OnTopic.Tests/ViewModels/FilteredContentTypeTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/FilteredContentTypeTopicViewModel.cs @@ -4,22 +4,21 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: FILTERED CONTENT TYPE TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views properties annotated with the . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class FilteredContentTypeTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: FILTERED CONTENT TYPE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views properties annotated with the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class FilteredContentTypeTopicViewModel { - [FilterByContentType("Page")] - public TopicViewModelCollection Children { get; } = new(); + [FilterByContentType("Page")] + public TopicViewModelCollection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/FilteredInvalidTopicViewModel.cs b/OnTopic.Tests/ViewModels/FilteredInvalidTopicViewModel.cs index 970ac750..5eebe086 100644 --- a/OnTopic.Tests/ViewModels/FilteredInvalidTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/FilteredInvalidTopicViewModel.cs @@ -4,22 +4,21 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: FILTERED TOPIC (INVALID) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views properties annotated with the . Includes an invalid . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class FilteredInvalidTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: FILTERED TOPIC (INVALID) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views properties annotated with the . Includes an invalid . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class FilteredInvalidTopicViewModel { - [FilterByAttribute("ContentType", "Page")] - public TopicViewModelCollection Children { get; } = new(); + [FilterByAttribute("ContentType", "Page")] + public TopicViewModelCollection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/FilteredTopicViewModel.cs b/OnTopic.Tests/ViewModels/FilteredTopicViewModel.cs index ce57e5f5..d64a83d1 100644 --- a/OnTopic.Tests/ViewModels/FilteredTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/FilteredTopicViewModel.cs @@ -4,23 +4,22 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: FILTERED TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views properties annotated with the . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class FilteredTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: FILTERED TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views properties annotated with the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class FilteredTopicViewModel { - [FilterByAttribute("SomeAttribute", "ValueA")] - [FilterByAttribute("SomeOtherAttribute", "ValueB")] - public TopicViewModelCollection Children { get; } = new(); + [FilterByAttribute("SomeAttribute", "ValueA")] + [FilterByAttribute("SomeOtherAttribute", "ValueB")] + public TopicViewModelCollection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/FlattenChildrenTopicViewModel.cs b/OnTopic.Tests/ViewModels/FlattenChildrenTopicViewModel.cs index 5dbfc6e6..c24363c1 100644 --- a/OnTopic.Tests/ViewModels/FlattenChildrenTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/FlattenChildrenTopicViewModel.cs @@ -4,22 +4,21 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: FLATTEN CHILDREN TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing view properties annotated with the . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class FlattenChildrenTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: FLATTEN CHILDREN TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing view properties annotated with the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class FlattenChildrenTopicViewModel { - [Flatten] - public Collection Children { get; } = new(); + [Flatten] + public Collection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/InheritedPropertyTopicViewModel.cs b/OnTopic.Tests/ViewModels/InheritedPropertyTopicViewModel.cs index 7730bb43..5dbd293f 100644 --- a/OnTopic.Tests/ViewModels/InheritedPropertyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/InheritedPropertyTopicViewModel.cs @@ -4,23 +4,22 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: INHERITED PROPERTY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with two properties—one annotated with , and the other - /// without. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InheritedPropertyTopicViewModel { - public string? Property { get; set; } +/*============================================================================================================================== +| VIEW MODEL: INHERITED PROPERTY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with two properties—one annotated with , and the other +/// without. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InheritedPropertyTopicViewModel { + public string? Property { get; set; } - [Inherit] - public string? InheritedProperty { get; set; } + [Inherit] + public string? InheritedProperty { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/InitializedTopicViewModel.cs b/OnTopic.Tests/ViewModels/InitializedTopicViewModel.cs index 14f23ea0..68d1b229 100644 --- a/OnTopic.Tests/ViewModels/InitializedTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/InitializedTopicViewModel.cs @@ -5,20 +5,19 @@ \=============================================================================================================================*/ using System.ComponentModel; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: INITIALIZED TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing properties with initialized values. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class InitializedTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: INITIALIZED TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing properties with initialized values. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class InitializedTopicViewModel { - public string? InitializedValue { get; set; } = "Original Value"; + public string? InitializedValue { get; set; } = "Original Value"; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/KeyOnlyTopicViewModel.cs b/OnTopic.Tests/ViewModels/KeyOnlyTopicViewModel.cs index 882565d3..4f911bd2 100644 --- a/OnTopic.Tests/ViewModels/KeyOnlyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/KeyOnlyTopicViewModel.cs @@ -4,26 +4,25 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: KEY ONLY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property (). - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class KeyOnlyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: KEY ONLY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property (). +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class KeyOnlyTopicViewModel { - public string? Key { get; set; } + public string? Key { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/LoadTestingViewModel.cs b/OnTopic.Tests/ViewModels/LoadTestingViewModel.cs index 59c1f226..2ee9c147 100644 --- a/OnTopic.Tests/ViewModels/LoadTestingViewModel.cs +++ b/OnTopic.Tests/ViewModels/LoadTestingViewModel.cs @@ -5,81 +5,80 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: LOAD TESTING +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a series of properties that can be used for load testing the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class LoadTestingViewModel: KeyOnlyTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: LOAD TESTING + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a simple view model with a series of properties that can be used for load testing the . + /// Initializes a new with an dictionary. /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class LoadTestingViewModel: KeyOnlyTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public LoadTestingViewModel(AttributeDictionary attributes) { - Contract.Requires(attributes); - Property0 = attributes.GetInteger("Property0"); - Property1 = attributes.GetInteger("Property1"); - Property2 = attributes.GetInteger("Property2"); - Property3 = attributes.GetInteger("Property3"); - Property4 = attributes.GetInteger("Property4"); - Property5 = attributes.GetInteger("Property5"); - Property6 = attributes.GetInteger("Property6"); - Property7 = attributes.GetInteger("Property7"); - Property8 = attributes.GetInteger("Property8"); - Property9 = attributes.GetInteger("Property9"); - Property10 = attributes.GetInteger("Property10"); - Property11 = attributes.GetInteger("Property11"); - Property12 = attributes.GetInteger("Property12"); - Property13 = attributes.GetInteger("Property13"); - Property14 = attributes.GetInteger("Property14"); - Property15 = attributes.GetInteger("Property15"); - Property16 = attributes.GetInteger("Property16"); - Property17 = attributes.GetInteger("Property17"); - Property18 = attributes.GetInteger("Property18"); - Property19 = attributes.GetInteger("Property19"); - Property20 = attributes.GetInteger("Property20"); - } + /// An of attribute values. + public LoadTestingViewModel(AttributeDictionary attributes) { + Contract.Requires(attributes); + Property0 = attributes.GetInteger("Property0"); + Property1 = attributes.GetInteger("Property1"); + Property2 = attributes.GetInteger("Property2"); + Property3 = attributes.GetInteger("Property3"); + Property4 = attributes.GetInteger("Property4"); + Property5 = attributes.GetInteger("Property5"); + Property6 = attributes.GetInteger("Property6"); + Property7 = attributes.GetInteger("Property7"); + Property8 = attributes.GetInteger("Property8"); + Property9 = attributes.GetInteger("Property9"); + Property10 = attributes.GetInteger("Property10"); + Property11 = attributes.GetInteger("Property11"); + Property12 = attributes.GetInteger("Property12"); + Property13 = attributes.GetInteger("Property13"); + Property14 = attributes.GetInteger("Property14"); + Property15 = attributes.GetInteger("Property15"); + Property16 = attributes.GetInteger("Property16"); + Property17 = attributes.GetInteger("Property17"); + Property18 = attributes.GetInteger("Property18"); + Property19 = attributes.GetInteger("Property19"); + Property20 = attributes.GetInteger("Property20"); + } - /// - /// Initializes a new with no parameters. - /// - public LoadTestingViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public LoadTestingViewModel() { } - /*========================================================================================================================== - | PROPERTIES - \-------------------------------------------------------------------------------------------------------------------------*/ - public int? Property0 { get; init; } - public int? Property1 { get; init; } - public int? Property2 { get; init; } - public int? Property3 { get; init; } - public int? Property4 { get; init; } - public int? Property5 { get; init; } - public int? Property6 { get; init; } - public int? Property7 { get; init; } - public int? Property8 { get; init; } - public int? Property9 { get; init; } - public int? Property10 { get; init; } - public int? Property11 { get; init; } - public int? Property12 { get; init; } - public int? Property13 { get; init; } - public int? Property14 { get; init; } - public int? Property15 { get; init; } - public int? Property16 { get; init; } - public int? Property17 { get; init; } - public int? Property18 { get; init; } - public int? Property19 { get; init; } - public int? Property20 { get; init; } + /*============================================================================================================================ + | PROPERTIES + \---------------------------------------------------------------------------------------------------------------------------*/ + public int? Property0 { get; init; } + public int? Property1 { get; init; } + public int? Property2 { get; init; } + public int? Property3 { get; init; } + public int? Property4 { get; init; } + public int? Property5 { get; init; } + public int? Property6 { get; init; } + public int? Property7 { get; init; } + public int? Property8 { get; init; } + public int? Property9 { get; init; } + public int? Property10 { get; init; } + public int? Property11 { get; init; } + public int? Property12 { get; init; } + public int? Property13 { get; init; } + public int? Property14 { get; init; } + public int? Property15 { get; init; } + public int? Property16 { get; init; } + public int? Property17 { get; init; } + public int? Property18 { get; init; } + public int? Property19 { get; init; } + public int? Property20 { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MapAsTopicViewModel.cs b/OnTopic.Tests/ViewModels/MapAsTopicViewModel.cs index 5a677a7a..dc4e5061 100644 --- a/OnTopic.Tests/ViewModels/MapAsTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/MapAsTopicViewModel.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: MAP AS - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with two associations—a relationship collection and a topic reference—annotated with the - /// . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MapAsTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: MAP AS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with two associations—a relationship collection and a topic reference—annotated with the +/// . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MapAsTopicViewModel { - [MapAs(typeof(AscendentTopicViewModel))] - public KeyOnlyTopicViewModel? TopicReference { get; set; } + [MapAs(typeof(AscendentTopicViewModel))] + public KeyOnlyTopicViewModel? TopicReference { get; set; } - [MapAs(typeof(AscendentTopicViewModel))] - public Collection Relationships { get; } = new(); + [MapAs(typeof(AscendentTopicViewModel))] + public Collection Relationships { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MapToParentTopicViewModel.cs b/OnTopic.Tests/ViewModels/MapToParentTopicViewModel.cs index ba024085..1d804d62 100644 --- a/OnTopic.Tests/ViewModels/MapToParentTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/MapToParentTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: MAP TO PARENT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with the . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MapToParentTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: MAP TO PARENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MapToParentTopicViewModel { - [MapToParent(AttributePrefix = "")] - public KeyOnlyTopicViewModel? Primary { get; set; } = new(); + [MapToParent(AttributePrefix = "")] + public KeyOnlyTopicViewModel? Primary { get; set; } = new(); - [MapToParent(AttributePrefix = "Aliased")] - public KeyOnlyTopicViewModel? Alternate { get; set; } = new(); + [MapToParent(AttributePrefix = "Aliased")] + public KeyOnlyTopicViewModel? Alternate { get; set; } = new(); - [MapToParent] - public KeyOnlyTopicViewModel? Ancillary { get; set; } = new(); + [MapToParent] + public KeyOnlyTopicViewModel? Ancillary { get; set; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MemberAccessorViewModel.cs b/OnTopic.Tests/ViewModels/MemberAccessorViewModel.cs index ac14985d..aa79cb96 100644 --- a/OnTopic.Tests/ViewModels/MemberAccessorViewModel.cs +++ b/OnTopic.Tests/ViewModels/MemberAccessorViewModel.cs @@ -4,36 +4,36 @@ | Project Topics Library \=============================================================================================================================*/ -#pragma warning disable CA1822 // Mark members as static +#pragma warning disable CA1822 // Mark members as static -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: MEMBER ACCESSOR - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing settable methods and gettable methods. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - [ExcludeFromCodeCoverage] - public class MemberAccessorViewModel { +/*============================================================================================================================== +| VIEW MODEL: MEMBER ACCESSOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing settable methods and gettable methods. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +[ExcludeFromCodeCoverage] +public class MemberAccessorViewModel { - private int? _methodValue; + private int? _methodValue; - public MemberAccessorViewModel() { } - public int? NullableProperty { get; set; } - public int NonNullableProperty { get; set; } - public Type NonNullableReferenceGetter { get; set; } = typeof(MemberAccessorViewModel); - public int? ReadOnlyProperty { get; } - public int WriteOnlyProperty { set { } } - public int? GetMethod() => _methodValue; - public int InvalidGetMethod(int value) => value; - public void SetMethod(int? value) => _methodValue = value; - public void InvalidSetMethod(int value, int newValue) => _ = value == newValue; + public MemberAccessorViewModel() { } + public int? NullableProperty { get; set; } + public int NonNullableProperty { get; set; } + public Type NonNullableReferenceGetter { get; set; } = typeof(MemberAccessorViewModel); + public int? ReadOnlyProperty { get; } + [SuppressMessage("Design", "CA1044:Properties should not be write only", Justification = "This is a test fixture used to verify mapping behavior against write-only properties.")] + public int WriteOnlyProperty { set { } } + public int? GetMethod() => _methodValue; + public int InvalidGetMethod(int value) => value; + public void SetMethod(int? value) => _methodValue = value; + public void InvalidSetMethod(int value, int newValue) => _ = value == newValue; - } //Class -} //Namespace +} //Class -#pragma warning restore CA1822 // Mark members as static \ No newline at end of file +#pragma warning restore CA1822 // Mark members as static \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/Metadata/AttributeDescriptorTopicViewModel.cs b/OnTopic.Tests/ViewModels/Metadata/AttributeDescriptorTopicViewModel.cs index 3c8803db..ca5bc1cd 100644 --- a/OnTopic.Tests/ViewModels/Metadata/AttributeDescriptorTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/Metadata/AttributeDescriptorTopicViewModel.cs @@ -4,19 +4,18 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels.Metadata { +namespace OnTopic.Tests.ViewModels.Metadata; - /*============================================================================================================================ - | VIEW MODEL: ATTRIBUTE DESCRIPTOR - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing view models with properties that map to custom collections - /// on the source . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class AttributeDescriptorTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: ATTRIBUTE DESCRIPTOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing view models with properties that map to custom collections +/// on the source . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class AttributeDescriptorTopicViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/Metadata/ContentTypeDescriptorTopicViewModel.cs b/OnTopic.Tests/ViewModels/Metadata/ContentTypeDescriptorTopicViewModel.cs index 3734a05d..a0144913 100644 --- a/OnTopic.Tests/ViewModels/Metadata/ContentTypeDescriptorTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/Metadata/ContentTypeDescriptorTopicViewModel.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels.Metadata { +namespace OnTopic.Tests.ViewModels.Metadata; - /*============================================================================================================================ - | VIEW MODEL: CONTENT TYPE DESCRIPTOR - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing view models with properties that map to custom collections - /// on the source . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ContentTypeDescriptorTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: CONTENT TYPE DESCRIPTOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing view models with properties that map to custom collections +/// on the source . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ContentTypeDescriptorTopicViewModel { - public Collection AttributeDescriptors { get; } = new(); + public Collection AttributeDescriptors { get; } = new(); - [Collection(CollectionType.MappedCollection)] - [Include(AssociationTypes.None)] - public Collection PermittedContentTypes { get; } = new(); + [Collection(CollectionType.MappedCollection)] + [Include(AssociationTypes.None)] + public Collection PermittedContentTypes { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/Metadata/TextAttributeDescriptorTopicViewModel.cs b/OnTopic.Tests/ViewModels/Metadata/TextAttributeDescriptorTopicViewModel.cs index 87c6542d..cc90d2f8 100644 --- a/OnTopic.Tests/ViewModels/Metadata/TextAttributeDescriptorTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/Metadata/TextAttributeDescriptorTopicViewModel.cs @@ -6,19 +6,18 @@ using OnTopic.Metadata; using OnTopic.TestDoubles.Metadata; -namespace OnTopic.Tests.ViewModels.Metadata { +namespace OnTopic.Tests.ViewModels.Metadata; - /*============================================================================================================================ - | VIEW MODEL: TEXT (ATTRIBUTE DESCRIPTOR) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a dummy implementation of a view model for an view model, in order to - /// allow the dynamic resolution of mapping topics to view models. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class TextAttributeDescriptorTopicViewModel : AttributeDescriptorTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: TEXT (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a dummy implementation of a view model for an view model, in order to +/// allow the dynamic resolution of mapping topics to view models. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class TextAttributeDescriptorTopicViewModel : AttributeDescriptorTopicViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/Metadata/TopicReferenceAttributeDescriptorTopicViewModel.cs b/OnTopic.Tests/ViewModels/Metadata/TopicReferenceAttributeDescriptorTopicViewModel.cs index c058b7b9..d8c98c79 100644 --- a/OnTopic.Tests/ViewModels/Metadata/TopicReferenceAttributeDescriptorTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/Metadata/TopicReferenceAttributeDescriptorTopicViewModel.cs @@ -6,19 +6,18 @@ using OnTopic.Metadata; using OnTopic.TestDoubles.Metadata; -namespace OnTopic.Tests.ViewModels.Metadata { +namespace OnTopic.Tests.ViewModels.Metadata; - /*============================================================================================================================ - | VIEW MODEL: TOPIC REFERENCE (ATTRIBUTE DESCRIPTOR) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a dummy implementation of a view model for an view model, in order to - /// allow the dynamic resolution of mapping topics to view models. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class TopicReferenceAttributeDescriptorTopicViewModel : AttributeDescriptorTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: TOPIC REFERENCE (ATTRIBUTE DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a dummy implementation of a view model for an view model, in order to +/// allow the dynamic resolution of mapping topics to view models. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class TopicReferenceAttributeDescriptorTopicViewModel : AttributeDescriptorTopicViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MetadataLookupTopicViewModel.cs b/OnTopic.Tests/ViewModels/MetadataLookupTopicViewModel.cs index 77c41b9b..c70af10b 100644 --- a/OnTopic.Tests/ViewModels/MetadataLookupTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/MetadataLookupTopicViewModel.cs @@ -4,21 +4,20 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: MINIMUM VALUE PROPERTY TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing view properties annotated with minimum value attributes. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MetadataLookupTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: MINIMUM VALUE PROPERTY TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing view properties annotated with minimum value attributes. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MetadataLookupTopicViewModel { - [Metadata("Categories")] - public TopicViewModelCollection Categories { get; } = new(); + [Metadata("Categories")] + public TopicViewModelCollection Categories { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MethodBasedReferenceViewModel.cs b/OnTopic.Tests/ViewModels/MethodBasedReferenceViewModel.cs index b2baaf58..02f791df 100644 --- a/OnTopic.Tests/ViewModels/MethodBasedReferenceViewModel.cs +++ b/OnTopic.Tests/ViewModels/MethodBasedReferenceViewModel.cs @@ -4,24 +4,23 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: METHOD BASED REFERENCE - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing settable methods and gettable methods. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MethodBasedReferenceViewModel { +/*============================================================================================================================== +| VIEW MODEL: METHOD BASED REFERENCE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing settable methods and gettable methods. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MethodBasedReferenceViewModel { - private TopicViewModel? _methodValue; + private TopicViewModel? _methodValue; - public void SetMethod(TopicViewModel? methodValue) => _methodValue = methodValue; + public void SetMethod(TopicViewModel? methodValue) => _methodValue = methodValue; - public TopicViewModel? GetMethod() => _methodValue; + public TopicViewModel? GetMethod() => _methodValue; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MethodBasedViewModel.cs b/OnTopic.Tests/ViewModels/MethodBasedViewModel.cs index 217eff18..c4e21b4b 100644 --- a/OnTopic.Tests/ViewModels/MethodBasedViewModel.cs +++ b/OnTopic.Tests/ViewModels/MethodBasedViewModel.cs @@ -5,33 +5,32 @@ \=============================================================================================================================*/ using System.ComponentModel; -#pragma warning disable CA1822 // Mark members as static +#pragma warning disable CA1822 // Mark members as static -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: METHOD BASED - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing settable methods and gettable methods. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - [ExcludeFromCodeCoverage] - public class MethodBasedViewModel { +/*============================================================================================================================== +| VIEW MODEL: METHOD BASED +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing settable methods and gettable methods. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +[ExcludeFromCodeCoverage] +public class MethodBasedViewModel { - private int _methodValue; + private int _methodValue; - public void SetMethod(int methodValue) => _methodValue = methodValue; - public int GetMethod() => _methodValue; - [DisplayName("Get Annotated Method")] - public int GetAnnotatedMethod() => _methodValue; - public TopicViewModel GetComplexMethod() => new(); - public void SetParametersMethod(int methodValue, int additionalValue) => _methodValue = methodValue + additionalValue; - public void SetComplexMethod(NavigationTopicViewModel model) => _methodValue = model?.Children.Count?? 0; + public void SetMethod(int methodValue) => _methodValue = methodValue; + public int GetMethod() => _methodValue; + [DisplayName("Get Annotated Method")] + public int GetAnnotatedMethod() => _methodValue; + public TopicViewModel GetComplexMethod() => new(); + public void SetParametersMethod(int methodValue, int additionalValue) => _methodValue = methodValue + additionalValue; + public void SetComplexMethod(NavigationTopicViewModel model) => _methodValue = model?.Children.Count?? 0; - } //Class -} //Namespace +} //Class -#pragma warning restore CA1822 // Mark members as static \ No newline at end of file +#pragma warning restore CA1822 // Mark members as static \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/MinimumLengthPropertyTopicViewModel.cs b/OnTopic.Tests/ViewModels/MinimumLengthPropertyTopicViewModel.cs index 2d6bcdb2..6aaa6bb8 100644 --- a/OnTopic.Tests/ViewModels/MinimumLengthPropertyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/MinimumLengthPropertyTopicViewModel.cs @@ -5,21 +5,20 @@ \=============================================================================================================================*/ using System.ComponentModel.DataAnnotations; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: MINIMUM VALUE PROPERTY TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing view properties annotated with minimum value attributes. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class MinimumLengthPropertyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: MINIMUM VALUE PROPERTY TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing view properties annotated with minimum value attributes. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class MinimumLengthPropertyTopicViewModel { - [MinLength(13)] - public string? MinimumLength { get; set; } + [MinLength(13)] + public string? MinimumLength { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/NestedTopicViewModel.cs b/OnTopic.Tests/ViewModels/NestedTopicViewModel.cs index 2181b738..19fb6e7f 100644 --- a/OnTopic.Tests/ViewModels/NestedTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/NestedTopicViewModel.cs @@ -4,20 +4,19 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: NESTED - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () for mapping nested topics. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class NestedTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: NESTED +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () for mapping nested topics. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class NestedTopicViewModel { - public Collection Categories { get; } = new(); + public Collection Categories { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/NonNullablePropertyTopicViewModel.cs b/OnTopic.Tests/ViewModels/NonNullablePropertyTopicViewModel.cs index 0333631a..a0fae81f 100644 --- a/OnTopic.Tests/ViewModels/NonNullablePropertyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/NonNullablePropertyTopicViewModel.cs @@ -4,30 +4,29 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: NON-NULLABLE PROPERTY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing the mapping of non-nullable properties. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class NonNullablePropertyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: NON-NULLABLE PROPERTY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing the mapping of non-nullable properties. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class NonNullablePropertyTopicViewModel { - public string NonNullableString { get; set; } = ""; + public string NonNullableString { get; set; } = ""; - public int NonNullableInteger { get; set; } + public int NonNullableInteger { get; set; } - public double NonNullableDouble { get; set; } + public double NonNullableDouble { get; set; } - public bool NonNullableBoolean { get; set; } + public bool NonNullableBoolean { get; set; } - public DateTime NonNullableDateTime { get; set; } + public DateTime NonNullableDateTime { get; set; } - public Uri NonNullableUrl { get; set; } = new("https://github.com/"); + public Uri NonNullableUrl { get; set; } = new("https://github.com/"); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/NullCollectionTopicViewModel.cs b/OnTopic.Tests/ViewModels/NullCollectionTopicViewModel.cs index 6b94bda3..100c77c0 100644 --- a/OnTopic.Tests/ViewModels/NullCollectionTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/NullCollectionTopicViewModel.cs @@ -5,42 +5,43 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Tests.ViewModels { - - /*============================================================================================================================ - | VIEW MODEL: NULL COLLECTION - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a view model with null collections to determine if they can be correctly mapped. - /// - /// - /// - /// As a best practice, view models—as with all classes—should have collection properties initialized during construction, - /// and non-settable. If this isn't possible, however, the optionally supports creating - /// collections based on a number of rules. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class NullCollectionTopicViewModel { - - [Collection("Collection")] - public Collection? NullCollection { get; set; } - - [Collection("Collection")] - public ICollection? NullICollection { get; set; } - - [Collection("Collection")] - public IList? NullIList { get; set; } - - [Collection("Collection")] - public IEnumerable? NullIEnumerable { get; set; } - - [Collection("Collection")] - public TypedTopicCollection? NullTypedCollection { get; set; } - - public class TypedTopicCollection: Collection { } - - } //Class -} //Namespace \ No newline at end of file +namespace OnTopic.Tests.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: NULL COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a view model with null collections to determine if they can be correctly mapped. +/// +/// +/// +/// As a best practice, view models—as with all classes—should have collection properties initialized during construction, +/// and non-settable. If this isn't possible, however, the optionally supports creating +/// collections based on a number of rules. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +[SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "This view model intentionally exposes settable, nullable collection properties to test the TopicMappingService's fallback collection-initialization behavior.")] +public class NullCollectionTopicViewModel { + + [Collection("Collection")] + public Collection? NullCollection { get; set; } + + [Collection("Collection")] + public ICollection? NullICollection { get; set; } + + [Collection("Collection")] + public IList? NullIList { get; set; } + + [Collection("Collection")] + public IEnumerable? NullIEnumerable { get; set; } + + [Collection("Collection")] + public TypedTopicCollection? NullTypedCollection { get; set; } + + [SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "This is a test fixture used solely to provide a concrete collection type for NullTypedCollection; it has no purpose outside this view model.")] + public class TypedTopicCollection: Collection { } + +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/NullablePropertyTopicViewModel.cs b/OnTopic.Tests/ViewModels/NullablePropertyTopicViewModel.cs index 745e38ee..839bf0c1 100644 --- a/OnTopic.Tests/ViewModels/NullablePropertyTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/NullablePropertyTopicViewModel.cs @@ -4,37 +4,36 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: NULLABLE PROPERTY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing the mapping of nullable properties. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class NullablePropertyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: NULLABLE PROPERTY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing the mapping of nullable properties. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class NullablePropertyTopicViewModel { - public string? NullableString { get; set; } + public string? NullableString { get; set; } - public int? NullableInteger { get; set; } + public int? NullableInteger { get; set; } - public double? NullableDouble { get; set; } + public double? NullableDouble { get; set; } - public bool? NullableBoolean { get; set; } + public bool? NullableBoolean { get; set; } - public DateTime? NullableDateTime { get; set; } + public DateTime? NullableDateTime { get; set; } - public Uri? NullableUrl { get; set; } + public Uri? NullableUrl { get; set; } - public string? Title { get; set; } + public string? Title { get; set; } - public bool? IsHidden { get; set; } + public bool? IsHidden { get; set; } - public DateTime? LastModified { get; set; } + public DateTime? LastModified { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/ProgressiveTopicViewModel.cs b/OnTopic.Tests/ViewModels/ProgressiveTopicViewModel.cs index 98036bf3..ee2984e2 100644 --- a/OnTopic.Tests/ViewModels/ProgressiveTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/ProgressiveTopicViewModel.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: REDUNDANT TOPIC (PROGRESSIVE) - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with a redundant topic references with differerent - /// inclusions, which is useful for evaluating progressive cache handling. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class ProgressiveTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: REDUNDANT TOPIC (PROGRESSIVE) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with a redundant topic references with differerent +/// inclusions, which is useful for evaluating progressive cache handling. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class ProgressiveTopicViewModel { - [Include(AssociationTypes.Parents)] - public TopicAssociationsViewModel? FirstItem { get; set; } + [Include(AssociationTypes.Parents)] + public TopicAssociationsViewModel? FirstItem { get; set; } - [Include(AssociationTypes.Parents)] - public TopicAssociationsViewModel? SecondItem { get; set; } + [Include(AssociationTypes.Parents)] + public TopicAssociationsViewModel? SecondItem { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/PropertyAliasTopicViewModel.cs b/OnTopic.Tests/ViewModels/PropertyAliasTopicViewModel.cs index c927e8ab..533f6a1a 100644 --- a/OnTopic.Tests/ViewModels/PropertyAliasTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/PropertyAliasTopicViewModel.cs @@ -4,22 +4,21 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: PROPERTY ALIAS - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () for mapping a property annotated with - /// a . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class PropertyAliasTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: PROPERTY ALIAS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () for mapping a property annotated with +/// a . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class PropertyAliasTopicViewModel { - [AttributeKey("Property")] - public string? PropertyAlias { get; set; } + [AttributeKey("Property")] + public string? PropertyAlias { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RecordTopicViewModel.cs b/OnTopic.Tests/ViewModels/RecordTopicViewModel.cs index 50285f5e..82ba18d9 100644 --- a/OnTopic.Tests/ViewModels/RecordTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RecordTopicViewModel.cs @@ -5,26 +5,25 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: RECORD - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property (), implemented as a record instead of a - /// class. - /// - /// - /// - /// Intended to validate that a record can be mapped using the . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public record RecordTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: RECORD +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property (), implemented as a record instead of a +/// class. +/// +/// +/// +/// Intended to validate that a record can be mapped using the . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public record RecordTopicViewModel { - public string? Key { get; init; } + public string? Key { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RedundantTopicViewModel.cs b/OnTopic.Tests/ViewModels/RedundantTopicViewModel.cs index 33469337..01db1802 100644 --- a/OnTopic.Tests/ViewModels/RedundantTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RedundantTopicViewModel.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: REDUNDANT TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with a redundant topic references, which are useful for - /// evaluating cache handling. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class RedundantTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: REDUNDANT TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with a redundant topic references, which are useful for +/// evaluating cache handling. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class RedundantTopicViewModel { - [Include(AssociationTypes.Parents)] - public TopicAssociationsViewModel? FirstItem { get; set; } + [Include(AssociationTypes.Parents)] + public TopicAssociationsViewModel? FirstItem { get; set; } - [Include(AssociationTypes.References)] - public TopicAssociationsViewModel? SecondItem { get; set; } + [Include(AssociationTypes.References)] + public TopicAssociationsViewModel? SecondItem { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RelatedEntityTopicViewModel.cs b/OnTopic.Tests/ViewModels/RelatedEntityTopicViewModel.cs index 7f49f2a1..1cf29f81 100644 --- a/OnTopic.Tests/ViewModels/RelatedEntityTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RelatedEntityTopicViewModel.cs @@ -5,27 +5,26 @@ \=============================================================================================================================*/ using OnTopic.Collections; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: RELATED ENTITY - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a relationship mapping to actual entities. - /// - /// - /// - /// View models should only reference collections and basic value objects. That said, for edge cases, the provides support for mapping actual entities. This is not a - /// best practice, and should be discouraged when creating view models. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class RelatedEntityTopicViewModel: KeyOnlyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: RELATED ENTITY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a relationship mapping to actual entities. +/// +/// +/// +/// View models should only reference collections and basic value objects. That said, for edge cases, the provides support for mapping actual entities. This is not a +/// best practice, and should be discouraged when creating view models. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class RelatedEntityTopicViewModel: KeyOnlyTopicViewModel { - public TopicCollection RelatedTopics { get; } = new(); + public TopicCollection RelatedTopics { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RelationTopicViewModel.cs b/OnTopic.Tests/ViewModels/RelationTopicViewModel.cs index 8836825e..0c270d7f 100644 --- a/OnTopic.Tests/ViewModels/RelationTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RelationTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: RELATION - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () for mapping relationships. - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class RelationTopicViewModel: KeyOnlyTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: RELATION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () for mapping relationships. +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class RelationTopicViewModel: KeyOnlyTopicViewModel { - [Include(AssociationTypes.Children)] - public Collection Cousins { get; } = new(); + [Include(AssociationTypes.Children)] + public Collection Cousins { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RelationWithChildrenTopicViewModel.cs b/OnTopic.Tests/ViewModels/RelationWithChildrenTopicViewModel.cs index f97076b4..2ef4701d 100644 --- a/OnTopic.Tests/ViewModels/RelationWithChildrenTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RelationWithChildrenTopicViewModel.cs @@ -4,27 +4,26 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: RELATION WITH CHILDREN - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a specialized version of for a relation with . - /// - /// - /// - /// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing - /// other mapping scenarios that might introduce errors, even though they've not part of the test. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - /// - public class RelationWithChildrenTopicViewModel: RelationTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: RELATION WITH CHILDREN +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a specialized version of for a relation with . +/// +/// +/// +/// Intended as a stand-in for cases where a very simple view model is required for test purposes, without introducing +/// other mapping scenarios that might introduce errors, even though they've not part of the test. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +/// +public class RelationWithChildrenTopicViewModel: RelationTopicViewModel { - [Include(AssociationTypes.Relationships)] - public Collection Children { get; } = new(); + [Include(AssociationTypes.Relationships)] + public Collection Children { get; } = new(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RequiredObjectTopicViewModel.cs b/OnTopic.Tests/ViewModels/RequiredObjectTopicViewModel.cs index fd13fc22..ee6f9503 100644 --- a/OnTopic.Tests/ViewModels/RequiredObjectTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RequiredObjectTopicViewModel.cs @@ -5,21 +5,20 @@ \=============================================================================================================================*/ using System.ComponentModel.DataAnnotations; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: REQUIRED OBJECT TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with required object (non-scalar) property types. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class RequiredObjectTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: REQUIRED OBJECT TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with required object (non-scalar) property types. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class RequiredObjectTopicViewModel { - [Required] - public Topic? RequiredObject { get; set; } + [Required] + public Topic? RequiredObject { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/RequiredTopicViewModel.cs b/OnTopic.Tests/ViewModels/RequiredTopicViewModel.cs index 702fa626..cc2a7c59 100644 --- a/OnTopic.Tests/ViewModels/RequiredTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/RequiredTopicViewModel.cs @@ -5,21 +5,20 @@ \=============================================================================================================================*/ using System.ComponentModel.DataAnnotations; -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: REQUIRED TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed data transfer object for testing views with required (scalar) property types. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class RequiredTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: REQUIRED TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed data transfer object for testing views with required (scalar) property types. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class RequiredTopicViewModel { - [Required] - public string? RequiredAttribute { get; set; } + [Required] + public string? RequiredAttribute { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/TopicAssociationsTopicViewModel.cs b/OnTopic.Tests/ViewModels/TopicAssociationsTopicViewModel.cs index 91fd72e0..d0b285cd 100644 --- a/OnTopic.Tests/ViewModels/TopicAssociationsTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/TopicAssociationsTopicViewModel.cs @@ -4,22 +4,21 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: TOPIC ASSOCIATIONS - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with two associations. Useful for testing the as well as - /// caching via e.g. and . - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class TopicAssociationsViewModel { +/*============================================================================================================================== +| VIEW MODEL: TOPIC ASSOCIATIONS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with two associations. Useful for testing the as well as +/// caching via e.g. and . +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class TopicAssociationsViewModel { - public TopicViewModel? Parent { get; init; } - public TopicViewModel? Reference { get; init; } + public TopicViewModel? Parent { get; init; } + public TopicViewModel? Reference { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.Tests/ViewModels/TopicReferenceTopicViewModel.cs b/OnTopic.Tests/ViewModels/TopicReferenceTopicViewModel.cs index 49f66c16..eb38adb8 100644 --- a/OnTopic.Tests/ViewModels/TopicReferenceTopicViewModel.cs +++ b/OnTopic.Tests/ViewModels/TopicReferenceTopicViewModel.cs @@ -4,20 +4,19 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Tests.ViewModels { +namespace OnTopic.Tests.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: TOPIC REFERENCE - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a simple view model with a single property () for mapping a topic reference. - /// - /// - /// This is a sample class intended for test purposes only; it is not designed for use in a production environment. - /// - public class TopicReferenceTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: TOPIC REFERENCE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple view model with a single property () for mapping a topic reference. +/// +/// +/// This is a sample class intended for test purposes only; it is not designed for use in a production environment. +/// +public class TopicReferenceTopicViewModel { - public TopicViewModel? TopicReference { get; set; } + public TopicViewModel? TopicReference { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/BindingModels/AssociatedTopicBindingModel.cs b/OnTopic.ViewModels/BindingModels/AssociatedTopicBindingModel.cs index d9905ffa..c82d8411 100644 --- a/OnTopic.ViewModels/BindingModels/AssociatedTopicBindingModel.cs +++ b/OnTopic.ViewModels/BindingModels/AssociatedTopicBindingModel.cs @@ -5,33 +5,32 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Reverse; -namespace OnTopic.ViewModels.BindingModels { +namespace OnTopic.ViewModels.BindingModels; + +/*============================================================================================================================== +| BINDING MODEL: ASSOCIATED TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a model for binding an association of a to another . +/// +/// +/// While implementors may choose to create a custom implementation, the out-of- +/// the-box implementation satisfies all of the requirements of the . The only reason to implement a custom definition is if the caller needs additional +/// metadata for separate validation or processing. +/// +public record AssociatedTopicBindingModel : IAssociatedTopicBindingModel { /*============================================================================================================================ - | BINDING MODEL: ASSOCIATED TOPIC + | PROPERTY: UNIQUE KEY \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a model for binding an association of a to another . + /// Gets the topic's attribute, the unique text identifier for the topic. /// - /// - /// While implementors may choose to create a custom implementation, the out-of- - /// the-box implementation satisfies all of the requirements of the . The only reason to implement a custom definition is if the caller needs additional - /// metadata for separate validation or processing. - /// - public record AssociatedTopicBindingModel : IAssociatedTopicBindingModel { - - /*========================================================================================================================== - | PROPERTY: UNIQUE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the topic's attribute, the unique text identifier for the topic. - /// - /// - /// value is not null - /// - [Required] - public string UniqueKey { get; init; } = default!; + /// + /// value is not null + /// + [Required] + public string UniqueKey { get; init; } = default!; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/BindingModels/RelatedTopicBindingModel.cs b/OnTopic.ViewModels/BindingModels/RelatedTopicBindingModel.cs index 224de9f7..6e0dca5a 100644 --- a/OnTopic.ViewModels/BindingModels/RelatedTopicBindingModel.cs +++ b/OnTopic.ViewModels/BindingModels/RelatedTopicBindingModel.cs @@ -5,26 +5,26 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Reverse; -namespace OnTopic.ViewModels.BindingModels { +namespace OnTopic.ViewModels.BindingModels; - /*============================================================================================================================ - | BINDING MODEL: RELATED TOPIC - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a model for binding a relationship of a to an existing . - /// - /// - /// While implementors may choose to create a custom implementation, the out-of- - /// the-box implementation satisfies all of the requirements of the . The only reason to implement a custom definition is if the caller needs additional - /// metadata for separate validation or processing. - /// - [ExcludeFromCodeCoverage] - [Obsolete( - "The RelatedTopicBindingModel has been replaced by the AssociatedTopicBindingModel. Please update references.", - true - )] - public record RelatedTopicBindingModel: AssociatedTopicBindingModel { +/*============================================================================================================================== +| BINDING MODEL: RELATED TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a model for binding a relationship of a to an existing . +/// +/// +/// While implementors may choose to create a custom implementation, the out-of- +/// the-box implementation satisfies all of the requirements of the . The only reason to implement a custom definition is if the caller needs additional +/// metadata for separate validation or processing. +/// +[ExcludeFromCodeCoverage] +[Obsolete( + "The RelatedTopicBindingModel has been replaced by the AssociatedTopicBindingModel. Please update references.", + true +)] +public record RelatedTopicBindingModel: AssociatedTopicBindingModel { - } //Class -} //Namespaces \ No newline at end of file +} //Class +//Namespaces \ No newline at end of file diff --git a/OnTopic.ViewModels/Internal/IsExternalInit.cs b/OnTopic.ViewModels/Internal/IsExternalInit.cs index 2bd828ad..adbc401b 100644 --- a/OnTopic.ViewModels/Internal/IsExternalInit.cs +++ b/OnTopic.ViewModels/Internal/IsExternalInit.cs @@ -4,16 +4,15 @@ | Project Topics Library \=============================================================================================================================*/ -namespace System.Runtime.CompilerServices { +namespace System.Runtime.CompilerServices; - /*============================================================================================================================ - | CLASS: IS EXTERNAL INIT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The class is made available as part of the .NET 5.0 CLR in order to enable init accessors. - /// As this is not available in .NET Standard, however, we must maintain this separate copy until we migrate to .NET 5.0. - /// - internal static class IsExternalInit { +/*============================================================================================================================== +| CLASS: IS EXTERNAL INIT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The class is made available as part of the .NET 5.0 CLR in order to enable init accessors. +/// As this is not available in .NET Standard, however, we must maintain this separate copy until we migrate to .NET 5.0. +/// +internal static class IsExternalInit { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/NavigationTopicViewModel.cs b/OnTopic.ViewModels/NavigationTopicViewModel.cs index a5fbb718..14c04786 100644 --- a/OnTopic.ViewModels/NavigationTopicViewModel.cs +++ b/OnTopic.ViewModels/NavigationTopicViewModel.cs @@ -5,68 +5,67 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: NAVIGATION TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a node in the navigation. +/// +/// +/// +/// No topics are expected to have a Navigation content type. Instead, this view model is expected to be manually +/// constructed by e.g. a MenuViewComponent. +/// +/// +/// Since .NET Standard doesn't support return-type covariance, this class can't be derived in a meaningful way (i.e., if +/// it were to be, the property would still return a of instances). Instead, the preferred way to extend the functionality is +/// to create a new implementation of . To help communicate this, the class is marked as sealed. +/// +/// +public sealed record NavigationTopicViewModel : INavigationTopicViewModel { + + /*============================================================================================================================ + | TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string Title { get; init; } = default!; /*============================================================================================================================ - | VIEW MODEL: NAVIGATION TOPIC + | SHORT TITLE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a node in the navigation. + /// Provides a short title to be used in the navigation, for cases where the normal title is too long. /// - /// - /// - /// No topics are expected to have a Navigation content type. Instead, this view model is expected to be manually - /// constructed by e.g. a MenuViewComponent. - /// - /// - /// Since .NET Standard doesn't support return-type covariance, this class can't be derived in a meaningful way (i.e., if - /// it were to be, the property would still return a of instances). Instead, the preferred way to extend the functionality is - /// to create a new implementation of . To help communicate this, the class is marked as sealed. - /// - /// - public sealed record NavigationTopicViewModel : INavigationTopicViewModel { + public string? ShortTitle { get; init; } - /*========================================================================================================================== - | TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string Title { get; init; } = default!; - - /*========================================================================================================================== - | SHORT TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a short title to be used in the navigation, for cases where the normal title is too long. - /// - public string? ShortTitle { get; init; } - - /*========================================================================================================================== - | WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string WebPath { get; init; } = default!; + /*============================================================================================================================ + | WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string WebPath { get; init; } = default!; - /*========================================================================================================================== - | CHILDREN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a list of nested objects, for handling hierarchical navigation. - /// - public Collection Children { get; } = new(); + /*============================================================================================================================ + | CHILDREN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a list of nested objects, for handling hierarchical navigation. + /// + public Collection Children { get; } = new(); - /*========================================================================================================================== - | IS SELECTED? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not the node represented by this is currently selected, - /// typically meaning the user is on the page this object is pointing to. - /// - public bool IsSelected(string webPath) => - $"{webPath}/".StartsWith($"{WebPath}", StringComparison.OrdinalIgnoreCase); + /*============================================================================================================================ + | IS SELECTED? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not the node represented by this is currently selected, + /// typically meaning the user is on the page this object is pointing to. + /// + public bool IsSelected(string webPath) => + $"{webPath}/".StartsWith($"{WebPath}", StringComparison.OrdinalIgnoreCase); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/TopicViewModel.cs b/OnTopic.ViewModels/TopicViewModel.cs index 97291a72..c6904458 100644 --- a/OnTopic.ViewModels/TopicViewModel.cs +++ b/OnTopic.ViewModels/TopicViewModel.cs @@ -5,117 +5,116 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Annotations; -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a model for feeding views general information about a . +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record TopicViewModel: ITopicViewModel, ICoreTopicViewModel, IAssociatedTopicBindingModel, ITopicBindingModel { /*============================================================================================================================ - | VIEW MODEL: TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a model for feeding views general information about a . + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record TopicViewModel: ITopicViewModel, ICoreTopicViewModel, IAssociatedTopicBindingModel, ITopicBindingModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public TopicViewModel(AttributeDictionary attributes) { - Contract.Requires(attributes, nameof(attributes)); - View = attributes.GetValue("View"); - } + /// An of attribute values. + public TopicViewModel(AttributeDictionary attributes) { + Contract.Requires(attributes, nameof(attributes)); + View = attributes.GetValue("View"); + } - /// - /// Initializes a new with no parameters. - /// - public TopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public TopicViewModel() { } - /*========================================================================================================================== - | ID - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public int Id { get; init; } + /*============================================================================================================================ + | ID + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public int Id { get; init; } - /*========================================================================================================================== - | KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string Key { get; init; } = default!; + /*============================================================================================================================ + | KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string Key { get; init; } = default!; - /*========================================================================================================================== - | CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string ContentType { get; init; } = default!; + /*============================================================================================================================ + | CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string ContentType { get; init; } = default!; - /*========================================================================================================================== - | UNIQUE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string UniqueKey { get; init; } = default!; + /*============================================================================================================================ + | UNIQUE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string UniqueKey { get; init; } = default!; - /*========================================================================================================================== - | WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string WebPath { get; init; } = default!; + /*============================================================================================================================ + | WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string WebPath { get; init; } = default!; - /*========================================================================================================================== - | VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public string? View { get; init; } + /*============================================================================================================================ + | VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public string? View { get; init; } - /*========================================================================================================================== - | TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required] - public string Title { get; init; } = default!; + /*============================================================================================================================ + | TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required] + public string Title { get; init; } = default!; - /*========================================================================================================================== - | IS HIDDEN? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The IsHidden property is no longer supported by {nameof(TopicViewModel)}.", true)] - [DisableMapping] - public bool IsHidden { get; init; } + /*============================================================================================================================ + | IS HIDDEN? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The IsHidden property is no longer supported by {nameof(TopicViewModel)}.", true)] + [DisableMapping] + public bool IsHidden { get; init; } - /*========================================================================================================================== - | LAST MODIFIED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The date that the topic was last modified on. - /// - public DateTime LastModified { get; init; } + /*============================================================================================================================ + | LAST MODIFIED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The date that the topic was last modified on. + /// + public DateTime LastModified { get; init; } - /*========================================================================================================================== - | PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the parent in the topic hierarchy. - /// - /// - /// If the current is being mapped as part of another , then the - /// property will only be mapped if that association includes a with a - /// value including . If it does, all topics will be mapped up - /// to the root of the site. No other associations on the view models will be mapped, even if they - /// are annotated with a . - /// - [Include(AssociationTypes.Parents)] - public TopicViewModel? Parent { get; init; } + /*============================================================================================================================ + | PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the parent in the topic hierarchy. + /// + /// + /// If the current is being mapped as part of another , then the + /// property will only be mapped if that association includes a with a + /// value including . If it does, all topics will be mapped up + /// to the root of the site. No other associations on the view models will be mapped, even if they + /// are annotated with a . + /// + [Include(AssociationTypes.Parents)] + public TopicViewModel? Parent { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/TopicViewModelLookupService.cs b/OnTopic.ViewModels/TopicViewModelLookupService.cs index c30b6714..7789bdaa 100644 --- a/OnTopic.ViewModels/TopicViewModelLookupService.cs +++ b/OnTopic.ViewModels/TopicViewModelLookupService.cs @@ -6,64 +6,65 @@ using System.Reflection; using OnTopic.Lookup; -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| CLASS: TYPE INDEX +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The can be configured to provide a lookup of . +/// +public class TopicViewModelLookupService : StaticTypeLookupService { /*============================================================================================================================ - | CLASS: TYPE INDEX + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The can be configured to provide a lookup of . + /// Establishes a new instance of a . Optionally accepts a list of instances and a default value. /// - public class TopicViewModelLookupService : StaticTypeLookupService { + /// + /// Any instances submitted via should be unique by ; if they are not, they will be removed. + /// + /// The list of instances to expose as part of this service. + public TopicViewModelLookupService(IEnumerable? types = null) : base(types) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure local view models are accounted for \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . Optionally accepts a list of instances and a default value. - /// - /// - /// Any instances submitted via should be unique by ; if they are not, they will be removed. - /// - /// The list of instances to expose as part of this service. - public TopicViewModelLookupService(IEnumerable? types = null) : base(types) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure local view models are accounted for - \-----------------------------------------------------------------------------------------------------------------------*/ - TryAdd(typeof(ContentListTopicViewModel)); - TryAdd(typeof(IndexTopicViewModel)); - TryAdd(typeof(NavigationTopicViewModel)); - TryAdd(typeof(PageGroupTopicViewModel)); - TryAdd(typeof(PageTopicViewModel)); - TryAdd(typeof(SectionTopicViewModel)); - TryAdd(typeof(SlideshowTopicViewModel)); - TryAdd(typeof(TopicViewModel)); - TryAdd(typeof(VideoTopicViewModel)); + TryAdd(typeof(ContentListTopicViewModel)); + TryAdd(typeof(IndexTopicViewModel)); + TryAdd(typeof(NavigationTopicViewModel)); + TryAdd(typeof(PageGroupTopicViewModel)); + TryAdd(typeof(PageTopicViewModel)); + TryAdd(typeof(SectionTopicViewModel)); + TryAdd(typeof(SlideshowTopicViewModel)); + TryAdd(typeof(TopicViewModel)); + TryAdd(typeof(VideoTopicViewModel)); - /*------------------------------------------------------------------------------------------------------------------------ - | Add item types - \-----------------------------------------------------------------------------------------------------------------------*/ - TryAdd(typeof(ItemTopicViewModel)); - TryAdd(typeof(ContentItemTopicViewModel)); - TryAdd(typeof(CacheProfileTopicViewModel)); - TryAdd(typeof(LookupListItemTopicViewModel)); - TryAdd(typeof(SlideTopicViewModel)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add item types + \-------------------------------------------------------------------------------------------------------------------------*/ + TryAdd(typeof(ItemTopicViewModel)); + TryAdd(typeof(ContentItemTopicViewModel)); + TryAdd(typeof(CacheProfileTopicViewModel)); + TryAdd(typeof(LookupListItemTopicViewModel)); + TryAdd(typeof(SlideTopicViewModel)); - /*------------------------------------------------------------------------------------------------------------------------ - | Add obsolete types - >------------------------------------------------------------------------------------------------------------------------- - | These will be removed in the next major version of OnTopic. - \-----------------------------------------------------------------------------------------------------------------------*/ - TryAdd(typeof(ListTopicViewModel)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add obsolete types + >------------------------------------------------------------------------------------------------------------------------- + | These will be removed in the next major version of OnTopic. + \-------------------------------------------------------------------------------------------------------------------------*/ + #pragma warning disable CS0618 // Type is obsolete; retained for backward compatibility until the next major version + TryAdd(typeof(ListTopicViewModel)); + #pragma warning restore CS0618 - /*------------------------------------------------------------------------------------------------------------------------ - | Add support types - \-----------------------------------------------------------------------------------------------------------------------*/ + /*-------------------------------------------------------------------------------------------------------------------------- + | Add support types + \-------------------------------------------------------------------------------------------------------------------------*/ - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_collections/TopicViewModelCollection{TItem}.cs b/OnTopic.ViewModels/_collections/TopicViewModelCollection{TItem}.cs index e95d9bb9..d7c39d5d 100644 --- a/OnTopic.ViewModels/_collections/TopicViewModelCollection{TItem}.cs +++ b/OnTopic.ViewModels/_collections/TopicViewModelCollection{TItem}.cs @@ -6,69 +6,68 @@ using System.Collections.ObjectModel; using OnTopic.Internal.Diagnostics; -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a basic collection interface for use with models implementing , including and derivatives. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public class TopicViewModelCollection: KeyedCollection where TItem: ICoreTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a basic collection interface for use with models implementing , including and derivatives. + /// Initializes a new instance of the . /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public class TopicViewModelCollection: KeyedCollection where TItem: ICoreTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - public TopicViewModelCollection() : base(StringComparer.OrdinalIgnoreCase) { - } + public TopicViewModelCollection() : base(StringComparer.OrdinalIgnoreCase) { + } - /// - /// Initializes a new instance of the . - /// - /// Seeds the collection with an optional list of topic references. - public TopicViewModelCollection(IEnumerable? topics = null) : base(StringComparer.OrdinalIgnoreCase) { - if (topics is not null) { - foreach (var item in topics) { - Add(item); - } + /// + /// Initializes a new instance of the . + /// + /// Seeds the collection with an optional list of topic references. + public TopicViewModelCollection(IEnumerable? topics = null) : base(StringComparer.OrdinalIgnoreCase) { + if (topics is not null) { + foreach (var item in topics) { + Add(item); } } + } - /*========================================================================================================================== - | METHOD: GET BY CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieve a filtered list of topics from this collection based on their content type. - /// - /// The name of the content type to filter by. - /// The filtered list of view models associated with the content type. - public TopicViewModelCollection GetByContentType(string contentType) { - Contract.Requires(!String.IsNullOrWhiteSpace(contentType), nameof(contentType)); - return new(Items.Where(t => t.ContentType?.Equals(contentType, StringComparison.OrdinalIgnoreCase)?? false)); - } - - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Method must be overridden for the EntityCollection to extract the keys from the items. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - [ExcludeFromCodeCoverage] - protected override sealed string GetKeyForItem(TItem item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Key?? ""; - } + /*============================================================================================================================ + | METHOD: GET BY CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieve a filtered list of topics from this collection based on their content type. + /// + /// The name of the content type to filter by. + /// The filtered list of view models associated with the content type. + public TopicViewModelCollection GetByContentType(string contentType) { + Contract.Requires(!String.IsNullOrWhiteSpace(contentType), nameof(contentType)); + return new(Items.Where(t => t.ContentType?.Equals(contentType, StringComparison.OrdinalIgnoreCase)?? false)); + } + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Method must be overridden for the EntityCollection to extract the keys from the items. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + [ExcludeFromCodeCoverage] + protected override sealed string GetKeyForItem(TItem item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Key?? ""; } + } \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/ContentListTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/ContentListTopicViewModel.cs index f9102c81..29c1f65d 100644 --- a/OnTopic.ViewModels/_contentTypes/ContentListTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/ContentListTopicViewModel.cs @@ -4,86 +4,85 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: CONTENT LIST TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a ContentList topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record ContentListTopicViewModel: PageTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: CONTENT LIST TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a ContentList topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record ContentListTopicViewModel: PageTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public ContentListTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - IsIndexed = attributes.GetBoolean(nameof(IsIndexed))?? IsIndexed; - IndexLabel = attributes.GetValue(nameof(IndexLabel))?? IndexLabel; - } + /// An of attribute values. + public ContentListTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + IsIndexed = attributes.GetBoolean(nameof(IsIndexed))?? IsIndexed; + IndexLabel = attributes.GetValue(nameof(IndexLabel))?? IndexLabel; + } - /// - /// Initializes a new with no parameters. - /// - public ContentListTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public ContentListTopicViewModel() { } - /*========================================================================================================================== - | CONTENT ITEMS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a list of , representing the contents of the . - /// - public TopicViewModelCollection ContentItems { get; } = new(); + /*============================================================================================================================ + | CONTENT ITEMS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a list of , representing the contents of the . + /// + public TopicViewModelCollection ContentItems { get; } = new(); - /*========================================================================================================================== - | CATEGORIES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a list of valid categories that each of the may optionally be associated with. - /// - public TopicViewModelCollection Categories { get; } = new(); + /*============================================================================================================================ + | CATEGORIES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a list of valid categories that each of the may optionally be associated with. + /// + public TopicViewModelCollection Categories { get; } = new(); - /*========================================================================================================================== - | IS INDEXED? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a flag determining whether or not the content list should be indexed. - /// - /// - /// The property, if set, requests that the view provides a list of or - /// at the top, with links to each one. This is entirely up to the discretion of the view as to - /// how to implement—or even whether it's appropriate. For instance, it might not make sense on views rendering as an - /// accordion or a searchable list. Nevertheless, it's a common enough feature that having it exposed as a first-party - /// option helps implementors account for common scenarios. As with other properties, it won't be set if there isn't a - /// corresponding attribute, and so this can easily be hidden or disabled globally via the editor. - /// - /// True if the content list should be indexed; false otherwise. - public bool IsIndexed { get; init; } + /*============================================================================================================================ + | IS INDEXED? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a flag determining whether or not the content list should be indexed. + /// + /// + /// The property, if set, requests that the view provides a list of or + /// at the top, with links to each one. This is entirely up to the discretion of the view as to + /// how to implement—or even whether it's appropriate. For instance, it might not make sense on views rendering as an + /// accordion or a searchable list. Nevertheless, it's a common enough feature that having it exposed as a first-party + /// option helps implementors account for common scenarios. As with other properties, it won't be set if there isn't a + /// corresponding attribute, and so this can easily be hidden or disabled globally via the editor. + /// + /// True if the content list should be indexed; false otherwise. + public bool IsIndexed { get; init; } - /*========================================================================================================================== - | INDEX LABEL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assuming , determines the label to display. Defaults to Contents. - /// - /// - /// Often, if an indexed list of links is provided on a view, it will be preceded with a lable. The allows that to be optionally set on a per topic basis. The default value is "Contents", though it is up - /// to view implementors and editor configurations as to whether this option is exposed or honored. - /// - /// Returns the value init; defaults to "Contents". - public string IndexLabel { get; init; } = "Contents"; + /*============================================================================================================================ + | INDEX LABEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assuming , determines the label to display. Defaults to Contents. + /// + /// + /// Often, if an indexed list of links is provided on a view, it will be preceded with a lable. The allows that to be optionally set on a per topic basis. The default value is "Contents", though it is up + /// to view implementors and editor configurations as to whether this option is exposed or honored. + /// + /// Returns the value init; defaults to "Contents". + public string IndexLabel { get; init; } = "Contents"; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/IndexTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/IndexTopicViewModel.cs index 21d701b1..ff5e963c 100644 --- a/OnTopic.ViewModels/_contentTypes/IndexTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/IndexTopicViewModel.cs @@ -4,35 +4,34 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: INDEX TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about an Index topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record IndexTopicViewModel: PageTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: INDEX TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about an Index topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record IndexTopicViewModel: PageTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public IndexTopicViewModel(AttributeDictionary attributes): base(attributes) { } + /// An of attribute values. + public IndexTopicViewModel(AttributeDictionary attributes): base(attributes) { } - /// - /// Initializes a new with no parameters. - /// - public IndexTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public IndexTopicViewModel() { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/PageGroupTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/PageGroupTopicViewModel.cs index e2d53f2f..ec2a479d 100644 --- a/OnTopic.ViewModels/_contentTypes/PageGroupTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/PageGroupTopicViewModel.cs @@ -4,35 +4,34 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: PAGE GROUP TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a PageGroup topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record PageGroupTopicViewModel : SectionTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: PAGE GROUP TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a PageGroup topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record PageGroupTopicViewModel : SectionTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public PageGroupTopicViewModel(AttributeDictionary attributes): base(attributes) { } + /// An of attribute values. + public PageGroupTopicViewModel(AttributeDictionary attributes): base(attributes) { } - /// - /// Initializes a new with no parameters. - /// - public PageGroupTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public PageGroupTopicViewModel() { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/PageTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/PageTopicViewModel.cs index 1d25a950..5807f61a 100644 --- a/OnTopic.ViewModels/_contentTypes/PageTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/PageTopicViewModel.cs @@ -4,95 +4,94 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: PAGE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a Page topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record PageTopicViewModel: TopicViewModel, INavigableTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: PAGE TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a Page topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record PageTopicViewModel: TopicViewModel, INavigableTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public PageTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - ShortTitle = attributes.GetValue(nameof(ShortTitle)); - Subtitle = attributes.GetValue(nameof(Subtitle)); - MetaTitle = attributes.GetValue(nameof(MetaTitle)); - MetaDescription = attributes.GetValue(nameof(MetaDescription)); - MetaKeywords = attributes.GetValue(nameof(MetaKeywords)); - NoIndex = attributes.GetBoolean(nameof(NoIndex))?? NoIndex; - Body = attributes.GetValue(nameof(Body)); - } + /// An of attribute values. + public PageTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + ShortTitle = attributes.GetValue(nameof(ShortTitle)); + Subtitle = attributes.GetValue(nameof(Subtitle)); + MetaTitle = attributes.GetValue(nameof(MetaTitle)); + MetaDescription = attributes.GetValue(nameof(MetaDescription)); + MetaKeywords = attributes.GetValue(nameof(MetaKeywords)); + NoIndex = attributes.GetBoolean(nameof(NoIndex))?? NoIndex; + Body = attributes.GetValue(nameof(Body)); + } - /// - /// Initializes a new with no parameters. - /// - public PageTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public PageTopicViewModel() { } - /*========================================================================================================================== - | SHORT TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a short title to be used in the navigation, for cases where the normal title is too long. - /// - public string? ShortTitle { get; init; } + /*============================================================================================================================ + | SHORT TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a short title to be used in the navigation, for cases where the normal title is too long. + /// + public string? ShortTitle { get; init; } - /*========================================================================================================================== - | SUBTITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides an optional subtitle which will typically be displayed under the title. - /// - public string? Subtitle { get; init; } + /*============================================================================================================================ + | SUBTITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides an optional subtitle which will typically be displayed under the title. + /// + public string? Subtitle { get; init; } - /*========================================================================================================================== - | META TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides an optional title to be used in page's metadata, if it differs from the . - /// - public string? MetaTitle { get; init; } + /*============================================================================================================================ + | META TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides an optional title to be used in page's metadata, if it differs from the . + /// + public string? MetaTitle { get; init; } - /*========================================================================================================================== - | META DESCRIPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public string? MetaDescription { get; init; } + /*============================================================================================================================ + | META DESCRIPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public string? MetaDescription { get; init; } - /*========================================================================================================================== - | META KEYWORDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public string? MetaKeywords { get; init; } + /*============================================================================================================================ + | META KEYWORDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public string? MetaKeywords { get; init; } - /*========================================================================================================================== - | META KEYWORDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not search engines are expected to index the page. - /// - public bool? NoIndex { get; init; } + /*============================================================================================================================ + | META KEYWORDS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not search engines are expected to index the page. + /// + public bool? NoIndex { get; init; } - /*========================================================================================================================== - | BODY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the primary content for the page, which is typically in HTML format. - /// - public string? Body { get; init; } + /*============================================================================================================================ + | BODY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the primary content for the page, which is typically in HTML format. + /// + public string? Body { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/SectionTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/SectionTopicViewModel.cs index ddd96c81..34d2c03e 100644 --- a/OnTopic.ViewModels/_contentTypes/SectionTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/SectionTopicViewModel.cs @@ -4,45 +4,44 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: SECTION TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a Section topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record SectionTopicViewModel : TopicViewModel { /*============================================================================================================================ - | VIEW MODEL: SECTION TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a Section topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record SectionTopicViewModel : TopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public SectionTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - HeaderImageUrl = attributes.GetUri(nameof(HeaderImageUrl)); - } + /// An of attribute values. + public SectionTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + HeaderImageUrl = attributes.GetUri(nameof(HeaderImageUrl)); + } - /// - /// Initializes a new with no parameters. - /// - public SectionTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public SectionTopicViewModel() { } - /*========================================================================================================================== - | HEADER IMAGE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a header image which may be displayed at the top of a section. - /// - public Uri? HeaderImageUrl { get; init; } + /*============================================================================================================================ + | HEADER IMAGE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a header image which may be displayed at the top of a section. + /// + public Uri? HeaderImageUrl { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/SlideshowTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/SlideshowTopicViewModel.cs index 9991e555..73cdac4b 100644 --- a/OnTopic.ViewModels/_contentTypes/SlideshowTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/SlideshowTopicViewModel.cs @@ -4,50 +4,49 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: SLIDESHOW TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a Slideshow item. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record SlideshowTopicViewModel: ContentListTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: SLIDESHOW TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a Slideshow item. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record SlideshowTopicViewModel: ContentListTopicViewModel { + /// An of attribute values. + public SlideshowTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + TransitionEffect = attributes.GetValue(nameof(TransitionEffect)); + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public SlideshowTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - TransitionEffect = attributes.GetValue(nameof(TransitionEffect)); - } - - /// - /// Initializes a new with no parameters. - /// - public SlideshowTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public SlideshowTopicViewModel() { } - /*========================================================================================================================== - | TRANSITION EFFECT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides the transition effect to use when flipping between slides. - /// - /// - /// The effective values for are dependent on the library used for presenting the - /// slideshow. Typically, they will map to standard HTML5/CSS3 transition effects, but they could differ depending on the - /// implementation. - /// - public string? TransitionEffect { get; init; } + /*============================================================================================================================ + | TRANSITION EFFECT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides the transition effect to use when flipping between slides. + /// + /// + /// The effective values for are dependent on the library used for presenting the + /// slideshow. Typically, they will map to standard HTML5/CSS3 transition effects, but they could differ depending on the + /// implementation. + /// + public string? TransitionEffect { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_contentTypes/VideoTopicViewModel.cs b/OnTopic.ViewModels/_contentTypes/VideoTopicViewModel.cs index c88fc669..69de5d17 100644 --- a/OnTopic.ViewModels/_contentTypes/VideoTopicViewModel.cs +++ b/OnTopic.ViewModels/_contentTypes/VideoTopicViewModel.cs @@ -4,55 +4,54 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: VIDEO TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a Video topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record VideoTopicViewModel: PageTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: VIDEO TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a Video topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record VideoTopicViewModel: PageTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public VideoTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - VideoUrl = attributes.GetUri(nameof(VideoUrl))!; - PosterUrl = attributes.GetUri(nameof(PosterUrl)); - } + /// An of attribute values. + public VideoTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + VideoUrl = attributes.GetUri(nameof(VideoUrl))!; + PosterUrl = attributes.GetUri(nameof(PosterUrl)); + } - /// - /// Initializes a new with no parameters. - /// - public VideoTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public VideoTopicViewModel() { } - /*========================================================================================================================== - | VIDEO URL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a URL reference to a video to display on the page. - /// - [Required] - public Uri VideoUrl { get; init; } = default!; + /*============================================================================================================================ + | VIDEO URL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a URL reference to a video to display on the page. + /// + [Required] + public Uri VideoUrl { get; init; } = default!; - /*========================================================================================================================== - | POSTER URL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a URL reference to an image to display prior to playing the video. - /// - public Uri? PosterUrl { get; init; } + /*============================================================================================================================ + | POSTER URL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a URL reference to an image to display prior to playing the video. + /// + public Uri? PosterUrl { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_items/CacheProfileTopicViewModel.cs b/OnTopic.ViewModels/_items/CacheProfileTopicViewModel.cs index e4d78421..94d8b51a 100644 --- a/OnTopic.ViewModels/_items/CacheProfileTopicViewModel.cs +++ b/OnTopic.ViewModels/_items/CacheProfileTopicViewModel.cs @@ -4,86 +4,85 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: CACHE PROFILE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a CacheProfile topic, as referenced by +/// the and its derivatives. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record CacheProfileTopicViewModel: ItemTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: CACHE PROFILE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a CacheProfile topic, as referenced by - /// the and its derivatives. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record CacheProfileTopicViewModel: ItemTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public CacheProfileTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - Duration = attributes.GetInteger(nameof(Duration)); - Location = attributes.GetValue(nameof(Location)); - NoStore = attributes.GetBoolean(nameof(NoStore)); - VaryByHeader = attributes.GetValue(nameof(VaryByHeader)); - VaryByQueryKeys = attributes.GetValue(nameof(VaryByQueryKeys)); - } + /// An of attribute values. + public CacheProfileTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + Duration = attributes.GetInteger(nameof(Duration)); + Location = attributes.GetValue(nameof(Location)); + NoStore = attributes.GetBoolean(nameof(NoStore)); + VaryByHeader = attributes.GetValue(nameof(VaryByHeader)); + VaryByQueryKeys = attributes.GetValue(nameof(VaryByQueryKeys)); + } - /// - /// Initializes a new with no parameters. - /// - public CacheProfileTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public CacheProfileTopicViewModel() { } - /*========================================================================================================================== - | DURATION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the duration in seconds for which the response is cached. If this property is set, the "max-age" in the - /// "Cache-control" header is set in the response. - /// - public int? Duration { get; init; } + /*============================================================================================================================ + | DURATION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the duration in seconds for which the response is cached. If this property is set, the "max-age" in the + /// "Cache-control" header is set in the response. + /// + public int? Duration { get; init; } - /*========================================================================================================================== - | LOCATION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the location where the data from a particular URL must be cached. If this property is set, the - /// "Cache-control" header is set in the response. - /// - public string? Location { get; init; } + /*============================================================================================================================ + | LOCATION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the location where the data from a particular URL must be cached. If this property is set, the + /// "Cache-control" header is set in the response. + /// + public string? Location { get; init; } - /*========================================================================================================================== - | NO STORE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the value which determines whether the data should be stored or not. When set to true, it sets the - /// "Cache-control" header in the response to "no-store". Ignores the "Location" parameter for values other than "None". - /// Ignores the "Duration" parameter. - /// - public bool? NoStore { get; init; } + /*============================================================================================================================ + | NO STORE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the value which determines whether the data should be stored or not. When set to true, it sets the + /// "Cache-control" header in the response to "no-store". Ignores the "Location" parameter for values other than "None". + /// Ignores the "Duration" parameter. + /// + public bool? NoStore { get; init; } - /*========================================================================================================================== - | VARY BY HEADER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets which header the cache should vary by, if appropriate. - /// - public string? VaryByHeader { get; init; } + /*============================================================================================================================ + | VARY BY HEADER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets which header the cache should vary by, if appropriate. + /// + public string? VaryByHeader { get; init; } - /*========================================================================================================================== - | VARY BY QUERY KEYS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets which query string parameter keys the cache should vary by, if appropriate. Should be comma delimited. - /// - public string? VaryByQueryKeys { get; init; } + /*============================================================================================================================ + | VARY BY QUERY KEYS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets which query string parameter keys the cache should vary by, if appropriate. Should be comma delimited. + /// + public string? VaryByQueryKeys { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_items/ContentItemTopicViewModel.cs b/OnTopic.ViewModels/_items/ContentItemTopicViewModel.cs index 2c8d7b3d..f3858ceb 100644 --- a/OnTopic.ViewModels/_items/ContentItemTopicViewModel.cs +++ b/OnTopic.ViewModels/_items/ContentItemTopicViewModel.cs @@ -4,73 +4,72 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: CONTENT ITEM TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a ContentItem topic, as used in the model, and its derivatives. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record ContentItemTopicViewModel: ItemTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: CONTENT ITEM TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a ContentItem topic, as used in the model, and its derivatives. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record ContentItemTopicViewModel: ItemTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public ContentItemTopicViewModel(AttributeDictionary attributes): base(attributes) { - Contract.Requires(attributes, nameof(attributes)); - Description = attributes.GetValue(nameof(Description))!; - LearnMoreUrl = attributes.GetUri(nameof(LearnMoreUrl)); - ThumbnailImage = attributes.GetUri(nameof(ThumbnailImage)); - Category = attributes.GetValue(nameof(Category)); - } + /// An of attribute values. + public ContentItemTopicViewModel(AttributeDictionary attributes): base(attributes) { + Contract.Requires(attributes, nameof(attributes)); + Description = attributes.GetValue(nameof(Description))!; + LearnMoreUrl = attributes.GetUri(nameof(LearnMoreUrl)); + ThumbnailImage = attributes.GetUri(nameof(ThumbnailImage)); + Category = attributes.GetValue(nameof(Category)); + } - /// - /// Initializes a new with no parameters. - /// - public ContentItemTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public ContentItemTopicViewModel() { } - /*========================================================================================================================== - | DESCRIPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the description; for Content Items, this is effectively the body. - /// - public string Description { get; init; } = default!; + /*============================================================================================================================ + | DESCRIPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the description; for Content Items, this is effectively the body. + /// + public string Description { get; init; } = default!; - /*========================================================================================================================== - | LEARN MORE URL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an optional URL for additional information that should be linked to. - /// - public Uri? LearnMoreUrl { get; init; } + /*============================================================================================================================ + | LEARN MORE URL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an optional URL for additional information that should be linked to. + /// + public Uri? LearnMoreUrl { get; init; } - /*========================================================================================================================== - | THUMBNAIL IMAGE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an optional path to a thumbnail image that should accompany the content item. - /// - public Uri? ThumbnailImage { get; init; } + /*============================================================================================================================ + | THUMBNAIL IMAGE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an optional path to a thumbnail image that should accompany the content item. + /// + public Uri? ThumbnailImage { get; init; } - /*========================================================================================================================== - | CATEGORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the category that the content item should be grouped under. - /// - public string? Category { get; init; } + /*============================================================================================================================ + | CATEGORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the category that the content item should be grouped under. + /// + public string? Category { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_items/ItemTopicViewModel.cs b/OnTopic.ViewModels/_items/ItemTopicViewModel.cs index 51c04ab7..1fac8d63 100644 --- a/OnTopic.ViewModels/_items/ItemTopicViewModel.cs +++ b/OnTopic.ViewModels/_items/ItemTopicViewModel.cs @@ -4,34 +4,33 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: ITEM TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about an Item topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record ItemTopicViewModel : TopicViewModel { /*============================================================================================================================ - | VIEW MODEL: ITEM TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about an Item topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record ItemTopicViewModel : TopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public ItemTopicViewModel(AttributeDictionary attributes): base(attributes) { } + /// An of attribute values. + public ItemTopicViewModel(AttributeDictionary attributes): base(attributes) { } - /// - /// Initializes a new with no parameters. - /// - public ItemTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public ItemTopicViewModel() { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_items/ListTopicViewModel.cs b/OnTopic.ViewModels/_items/ListTopicViewModel.cs index 24cbe106..a88f6999 100644 --- a/OnTopic.ViewModels/_items/ListTopicViewModel.cs +++ b/OnTopic.ViewModels/_items/ListTopicViewModel.cs @@ -6,33 +6,32 @@ using System.Collections; using OnTopic.Mapping.Annotations; -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; - /*============================================================================================================================ - | VIEW MODEL: LIST - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly-typed model for modeling a List topic, as used for nested topics. - /// - /// - /// - /// Generally, the preferred way to model a nested topic list is to map it to an . In fact, when - /// mapping children, any topics of type List will be skipped. That said, there remain a couple of scenarios where - /// mapping a List may be necessary or appropriate, such as when cross-referencing nested topic located on another - /// topic. - /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - /// - [Obsolete( - $"There should not be a need for a LookupListItem view model. If these must be referenced, prefer using e.g. " + - $"{nameof(MapAsAttribute)} to specify a common view model.", - false - )] - public record ListTopicViewModel: ContentItemTopicViewModel { +/*============================================================================================================================== +| VIEW MODEL: LIST +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for modeling a List topic, as used for nested topics. +/// +/// +/// +/// Generally, the preferred way to model a nested topic list is to map it to an . In fact, when +/// mapping children, any topics of type List will be skipped. That said, there remain a couple of scenarios where +/// mapping a List may be necessary or appropriate, such as when cross-referencing nested topic located on another +/// topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +/// +[Obsolete( + $"There should not be a need for a LookupListItem view model. If these must be referenced, prefer using e.g. " + + $"{nameof(MapAsAttribute)} to specify a common view model.", + false +)] +public record ListTopicViewModel: ContentItemTopicViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_items/LookupListItemTopicViewModel.cs b/OnTopic.ViewModels/_items/LookupListItemTopicViewModel.cs index 79c92fb7..a8062bb8 100644 --- a/OnTopic.ViewModels/_items/LookupListItemTopicViewModel.cs +++ b/OnTopic.ViewModels/_items/LookupListItemTopicViewModel.cs @@ -4,34 +4,33 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: LOOKUP LIST ITEM TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about LookupListItem topic. +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record LookupListItemTopicViewModel: ItemTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: LOOKUP LIST ITEM TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about LookupListItem topic. + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record LookupListItemTopicViewModel: ItemTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public LookupListItemTopicViewModel(AttributeDictionary attributes): base(attributes) { } + /// An of attribute values. + public LookupListItemTopicViewModel(AttributeDictionary attributes): base(attributes) { } - /// - /// Initializes a new with no parameters. - /// - public LookupListItemTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public LookupListItemTopicViewModel() { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic.ViewModels/_items/SlideTopicViewModel.cs b/OnTopic.ViewModels/_items/SlideTopicViewModel.cs index a81ae307..cfb27f76 100644 --- a/OnTopic.ViewModels/_items/SlideTopicViewModel.cs +++ b/OnTopic.ViewModels/_items/SlideTopicViewModel.cs @@ -4,35 +4,34 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.ViewModels { +namespace OnTopic.ViewModels; + +/*============================================================================================================================== +| VIEW MODEL: SLIDE TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed model for feeding views with information about a Slide topic, as used in e.g. . +/// +/// +/// Typically, view models should be created as part of the presentation layer. The namespace contains +/// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They +/// are supplied for convenience to model factory default settings for out-of-the-box content types. +/// +public record SlideTopicViewModel: ContentItemTopicViewModel { /*============================================================================================================================ - | VIEW MODEL: SLIDE TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed model for feeding views with information about a Slide topic, as used in e.g. . + /// Initializes a new with an dictionary. /// - /// - /// Typically, view models should be created as part of the presentation layer. The namespace contains - /// default implementations that can be used directly, used as base classes, or overwritten at the presentation level. They - /// are supplied for convenience to model factory default settings for out-of-the-box content types. - /// - public record SlideTopicViewModel: ContentItemTopicViewModel { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new with an dictionary. - /// - /// An of attribute values. - public SlideTopicViewModel(AttributeDictionary attributes): base(attributes) { } + /// An of attribute values. + public SlideTopicViewModel(AttributeDictionary attributes): base(attributes) { } - /// - /// Initializes a new with no parameters. - /// - public SlideTopicViewModel() { } + /// + /// Initializes a new with no parameters. + /// + public SlideTopicViewModel() { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Associations/ReferenceSetterAttribute.cs b/OnTopic/Associations/ReferenceSetterAttribute.cs index e7fe15db..86610253 100644 --- a/OnTopic/Associations/ReferenceSetterAttribute.cs +++ b/OnTopic/Associations/ReferenceSetterAttribute.cs @@ -5,39 +5,38 @@ \=============================================================================================================================*/ using OnTopic.Collections.Specialized; -namespace OnTopic.Associations { +namespace OnTopic.Associations; - /*============================================================================================================================ - | CLASS: REFERENCE SETTER [ATTRIBUTE] - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Flags that a property should be used when setting a reference via . - /// - /// - /// - /// When a call is made to the code will check to see if a property with the same name as the reference key exists, and - /// whether that property is decorated with the (i.e., [ReferenceSetter]). - /// If is, then the update will be routed through that property. This ensures that business logic is enforced by local - /// properties, instead of allowing business logic to be potentially bypassed by writing directly to the collection. - /// - /// - /// As an example, the property is adorned with the . - /// As a result, if a client calls topic.References.SetValue("BaseTopic", topic), then that update will be routed - /// through , thus enforcing any validation. - /// - /// - /// To ensure this logic, it is critical that implementers of ensure that the - /// property setters call the overload with the final parameter set to false to disable the enforcement of business - /// logic. Otherwise, an infinite loop will occur. Calling that overload tells that - /// the business logic has already been enforced by the caller. - /// - /// - [AttributeUsage(AttributeTargets.Property)] - public sealed class ReferenceSetterAttribute : Attribute { +/*============================================================================================================================== +| CLASS: REFERENCE SETTER [ATTRIBUTE] +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a property should be used when setting a reference via . +/// +/// +/// +/// When a call is made to the code will check to see if a property with the same name as the reference key exists, and +/// whether that property is decorated with the (i.e., [ReferenceSetter]). +/// If is, then the update will be routed through that property. This ensures that business logic is enforced by local +/// properties, instead of allowing business logic to be potentially bypassed by writing directly to the collection. +/// +/// +/// As an example, the property is adorned with the . +/// As a result, if a client calls topic.References.SetValue("BaseTopic", topic), then that update will be routed +/// through , thus enforcing any validation. +/// +/// +/// To ensure this logic, it is critical that implementers of ensure that the +/// property setters call the overload with the final parameter set to false to disable the enforcement of business +/// logic. Otherwise, an infinite loop will occur. Calling that overload tells that +/// the business logic has already been enforced by the caller. +/// +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class ReferenceSetterAttribute : Attribute { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Associations/TopicReferenceCollection.cs b/OnTopic/Associations/TopicReferenceCollection.cs index 8b967256..f196dabb 100644 --- a/OnTopic/Associations/TopicReferenceCollection.cs +++ b/OnTopic/Associations/TopicReferenceCollection.cs @@ -6,132 +6,131 @@ using OnTopic.Collections.Specialized; using OnTopic.Repositories; -namespace OnTopic.Associations { +namespace OnTopic.Associations; + +/*============================================================================================================================== +| CLASS: TOPIC REFERENCE COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects associated with particular reference keys. +/// +public class TopicReferenceCollection : TrackedRecordCollection { /*============================================================================================================================ - | CLASS: TOPIC REFERENCE COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects associated with particular reference keys. + /// Initializes a new instance of the . /// - public class TopicReferenceCollection : TrackedRecordCollection { + /// A reference to the topic that the current collection is bound to. + public TopicReferenceCollection(Topic parentTopic) : base(parentTopic) { } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - /// A reference to the topic that the current collection is bound to. - public TopicReferenceCollection(Topic parentTopic) : base(parentTopic) { } - - /*========================================================================================================================== - | PROPERTY: PARENT COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override TrackedRecordCollection? ParentCollection => - AssociatedTopic.Parent?.References; + /*============================================================================================================================ + | PROPERTY: PARENT COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override TrackedRecordCollection? ParentCollection => + AssociatedTopic.Parent?.References; + + /*============================================================================================================================ + | PROPERTY: BASE COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override TrackedRecordCollection? BaseCollection => + AssociatedTopic.BaseTopic?.References; + + /*============================================================================================================================ + | IS FULLY LOADED? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not the collection was fully loaded from the persistence store. + /// + /// + /// + /// When loading an individual or branch from the persistence store, it is possible that topic + /// references may not be fully available. In this scenario, updating topic references while e.g. deleting unmatched + /// relationships can result in unintended data loss. To account for this, the property ' + /// tracks whether a collection was fully loaded from the persistence store; if it wasn't, the should not deleted unmatched topic references. + /// + /// + /// The property defaults to true. It should be set to false during the method if any members of the collection cannot be mapped + /// back to a valid reference in memory. + /// + /// + public bool IsFullyLoaded { get; set; } = true; + + /*============================================================================================================================ + | INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void InsertItem(int index, TopicReferenceRecord item) { - /*========================================================================================================================== - | PROPERTY: BASE COLLECTION + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override TrackedRecordCollection? BaseCollection => - AssociatedTopic.BaseTopic?.References; + Contract.Requires(item, nameof(item)); - /*========================================================================================================================== - | IS FULLY LOADED? + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide base logic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not the collection was fully loaded from the persistence store. - /// - /// - /// - /// When loading an individual or branch from the persistence store, it is possible that topic - /// references may not be fully available. In this scenario, updating topic references while e.g. deleting unmatched - /// relationships can result in unintended data loss. To account for this, the property ' - /// tracks whether a collection was fully loaded from the persistence store; if it wasn't, the should not deleted unmatched topic references. - /// - /// - /// The property defaults to true. It should be set to false during the method if any members of the collection cannot be mapped - /// back to a valid reference in memory. - /// - /// - public bool IsFullyLoaded { get; set; } = true; - - /*========================================================================================================================== - | INSERT ITEM + base.InsertItem(index, item); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle recipricol references \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void InsertItem(int index, TopicReferenceRecord item) { + item.Value?.IncomingRelationships.SetValue(item.Key, AssociatedTopic, null, true); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(item, nameof(item)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Provide base logic - \-----------------------------------------------------------------------------------------------------------------------*/ - base.InsertItem(index, item); + /*============================================================================================================================ + | OVERRIDE: SET ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override void SetItem(int index, TopicReferenceRecord item) { - /*------------------------------------------------------------------------------------------------------------------------ - | Handle recipricol references - \-----------------------------------------------------------------------------------------------------------------------*/ - item.Value?.IncomingRelationships.SetValue(item.Key, AssociatedTopic, null, true); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(item, nameof(item)); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Get existing reference + \-------------------------------------------------------------------------------------------------------------------------*/ + var existingItem = this[index]; - /*========================================================================================================================== - | OVERRIDE: SET ITEM + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide base logic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override void SetItem(int index, TopicReferenceRecord item) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(item, nameof(item)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Get existing reference - \-----------------------------------------------------------------------------------------------------------------------*/ - var existingItem = this[index]; - - /*------------------------------------------------------------------------------------------------------------------------ - | Provide base logic - \-----------------------------------------------------------------------------------------------------------------------*/ - base.SetItem(index, item); - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle recipricol references - \-----------------------------------------------------------------------------------------------------------------------*/ - existingItem.Value?.IncomingRelationships.Remove(existingItem.Key, AssociatedTopic, true); - item?.Value?.IncomingRelationships.SetValue(item.Key, AssociatedTopic, null, true); - - } - - /*========================================================================================================================== - | OVERRIDE: REMOVE ITEM + base.SetItem(index, item); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle recipricol references \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override sealed void RemoveItem(int index) { + existingItem.Value?.IncomingRelationships.Remove(existingItem.Key, AssociatedTopic, true); + item?.Value?.IncomingRelationships.SetValue(item.Key, AssociatedTopic, null, true); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle recipricol references - \-----------------------------------------------------------------------------------------------------------------------*/ - var existing = this[index]; + } - existing.Value?.IncomingRelationships.Remove(existing.Key, AssociatedTopic, true); + /*============================================================================================================================ + | OVERRIDE: REMOVE ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override sealed void RemoveItem(int index) { - /*------------------------------------------------------------------------------------------------------------------------ - | Provide base logic - \-----------------------------------------------------------------------------------------------------------------------*/ - base.RemoveItem(index); + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle recipricol references + \-------------------------------------------------------------------------------------------------------------------------*/ + var existing = this[index]; + + existing.Value?.IncomingRelationships.Remove(existing.Key, AssociatedTopic, true); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide base logic + \-------------------------------------------------------------------------------------------------------------------------*/ + base.RemoveItem(index); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Associations/TopicReferenceRecord.cs b/OnTopic/Associations/TopicReferenceRecord.cs index 994f4ce6..37c41d50 100644 --- a/OnTopic/Associations/TopicReferenceRecord.cs +++ b/OnTopic/Associations/TopicReferenceRecord.cs @@ -7,74 +7,73 @@ using OnTopic.Metadata; using OnTopic.Repositories; -namespace OnTopic.Associations { +namespace OnTopic.Associations; + +/*============================================================================================================================== +| CLASS: TOPIC REFERENCE RECORD +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents the immutable value of a particular topic reference on a . +/// +/// +/// +/// Provides values and metadata specific to individual attribute values, such as state (e.g., the property signifies whether the attribute value has changed) and its date. +/// +/// +/// Typically, the will be exposed as part of a +/// via the collection. +/// +/// +/// Be aware that while represents the value of a specific topic reference, the +/// metadata for describing the purpose, constraints, and usage of that particular attribute is described by the class. +/// +/// +/// This class is immutable: once it is constructed, the values cannot be changed. To change a value, callers must either +/// create a new instance of the class or, preferably, call the 's method. +/// +/// +public record TopicReferenceRecord: TrackedRecord { /*============================================================================================================================ - | CLASS: TOPIC REFERENCE RECORD + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public TopicReferenceRecord(): base() { } + /// - /// Represents the immutable value of a particular topic reference on a . + /// Initializes a new instance of the class, using the specified key/value pair. /// - /// - /// - /// Provides values and metadata specific to individual attribute values, such as state (e.g., the property signifies whether the attribute value has changed) and its date. - /// - /// - /// Typically, the will be exposed as part of a - /// via the collection. - /// - /// - /// Be aware that while represents the value of a specific topic reference, the - /// metadata for describing the purpose, constraints, and usage of that particular attribute is described by the class. - /// - /// - /// This class is immutable: once it is constructed, the values cannot be changed. To change a value, callers must either - /// create a new instance of the class or, preferably, call the 's method. - /// - /// - public record TopicReferenceRecord: TrackedRecord { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public TopicReferenceRecord(): base() { } - - /// - /// Initializes a new instance of the class, using the specified key/value pair. - /// - /// - /// The string identifier for the collection item key/value pair. - /// - /// - /// The string value text for the collection item key/value pair. - /// - /// - /// An optional boolean indicator noting whether the collection item is a new value, - /// and should thus be saved to the database when is next called. - /// - /// - /// The value that the attribute was last modified. This is intended primarily for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - public TopicReferenceRecord( - string key, - Topic? value, - bool isDirty = true, - DateTime? lastModified = null - ): base(key, value, isDirty, lastModified) { + /// + /// The string identifier for the collection item key/value pair. + /// + /// + /// The string value text for the collection item key/value pair. + /// + /// + /// An optional boolean indicator noting whether the collection item is a new value, + /// and should thus be saved to the database when is next called. + /// + /// + /// The value that the attribute was last modified. This is intended primarily for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + public TopicReferenceRecord( + string key, + Topic? value, + bool isDirty = true, + DateTime? lastModified = null + ): base(key, value, isDirty, lastModified) { - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Associations/TopicRelationshipMultiMap.cs b/OnTopic/Associations/TopicRelationshipMultiMap.cs index 19965744..9d05c67b 100644 --- a/OnTopic/Associations/TopicRelationshipMultiMap.cs +++ b/OnTopic/Associations/TopicRelationshipMultiMap.cs @@ -7,292 +7,291 @@ using OnTopic.Querying; using OnTopic.Repositories; -namespace OnTopic.Associations { +namespace OnTopic.Associations; + +/*============================================================================================================================== +| CLASS: TOPIC RELATIONSHIP MULTIMAP +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple interface for accessing collections of topic collections. +/// +/// +/// The derives from to provide read-only access +/// to the underlying collection, then acts as a façade for the write operations, thus not only +/// simplifying access to the , but also ensuring that business logic is enforced, such as local +/// state tracking and handling of reciprocal relationships. +/// +public class TopicRelationshipMultiMap : ReadOnlyTopicMultiMap, ITrackDirtyKeys { /*============================================================================================================================ - | CLASS: TOPIC RELATIONSHIP MULTIMAP + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly Topic _parent; + readonly bool _isIncoming; + readonly DirtyKeyCollection _dirtyKeys = new(); + readonly TopicMultiMap _storage; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a simple interface for accessing collections of topic collections. + /// Initializes a new instance of the . /// /// - /// The derives from to provide read-only access - /// to the underlying collection, then acts as a façade for the write operations, thus not only - /// simplifying access to the , but also ensuring that business logic is enforced, such as local - /// state tracking and handling of reciprocal relationships. + /// The constructor requires a reference to a instance, which the related topics are to be associated + /// with. This will be used when setting incoming relationships. In addition, a + /// may be set as if it is specifically intended to track incoming relationships; if this is + /// not set, then it will not allow incoming relationships to be set via the internal overload. /// - public class TopicRelationshipMultiMap : ReadOnlyTopicMultiMap, ITrackDirtyKeys { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly Topic _parent; - readonly bool _isIncoming; - readonly DirtyKeyCollection _dirtyKeys = new(); - readonly TopicMultiMap _storage; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - /// - /// The constructor requires a reference to a instance, which the related topics are to be associated - /// with. This will be used when setting incoming relationships. In addition, a - /// may be set as if it is specifically intended to track incoming relationships; if this is - /// not set, then it will not allow incoming relationships to be set via the internal overload. - /// - public TopicRelationshipMultiMap(Topic parent, bool isIncoming = false): base(new()) { - _parent = parent; - _isIncoming = isIncoming; - _storage = base.Source; - } + public TopicRelationshipMultiMap(Topic parent, bool isIncoming = false): base(new()) { + _parent = parent; + _isIncoming = isIncoming; + _storage = base.Source; + } - /*========================================================================================================================== - | METHOD: CLEAR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes all objects grouped by a specific . - /// - /// - /// If there are any objects in the specified , then the will be marked as . - /// - /// The key of the relationship to be cleared. - public void Clear(string relationshipKey) { - Contract.Requires(!String.IsNullOrWhiteSpace(relationshipKey), nameof(relationshipKey)); - if (_storage.Contains(relationshipKey)) { - var relationship = _storage.GetValues(relationshipKey); - if (relationship.Count > 0) { - _dirtyKeys.MarkAs(relationshipKey, markDirty: !_parent.IsNew); - } - _storage.Clear(relationshipKey); + /*============================================================================================================================ + | METHOD: CLEAR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes all objects grouped by a specific . + /// + /// + /// If there are any objects in the specified , then the will be marked as . + /// + /// The key of the relationship to be cleared. + public void Clear(string relationshipKey) { + Contract.Requires(!String.IsNullOrWhiteSpace(relationshipKey), nameof(relationshipKey)); + if (_storage.Contains(relationshipKey)) { + var relationship = _storage.GetValues(relationshipKey); + if (relationship.Count > 0) { + _dirtyKeys.MarkAs(relationshipKey, markDirty: !_parent.IsNew); } + _storage.Clear(relationshipKey); } + } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(ClearTopics)} method has been renamed to {nameof(Clear)}.", true)] - public void ClearTopics(string relationshipKey) => Clear(relationshipKey); + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(ClearTopics)} method has been renamed to {nameof(Clear)}.", true)] + public void ClearTopics(string relationshipKey) => Clear(relationshipKey); - /*========================================================================================================================== - | METHOD: REMOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes a specific object associated with a specific . - /// - /// The key of the relationship. - /// The to be removed. - /// - /// Returns true if the is removed; returns false if either the specified or the cannot be found. - /// - public bool Remove(string relationshipKey, Topic topic) => Remove(relationshipKey, topic, false); + /*============================================================================================================================ + | METHOD: REMOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes a specific object associated with a specific . + /// + /// The key of the relationship. + /// The to be removed. + /// + /// Returns true if the is removed; returns false if either the specified or the cannot be found. + /// + public bool Remove(string relationshipKey, Topic topic) => Remove(relationshipKey, topic, false); - /// - /// Removes a specific object associated with a specific relationship key. - /// - /// The key of the relationship. - /// The topic to be removed. - /// - /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. - /// - /// - /// Returns true if the is removed; returns false if either the relationship key or the - /// cannot be found. - /// - internal bool Remove(string relationshipKey, Topic topic, bool isIncoming) { + /// + /// Removes a specific object associated with a specific relationship key. + /// + /// The key of the relationship. + /// The topic to be removed. + /// + /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. + /// + /// + /// Returns true if the is removed; returns false if either the relationship key or the + /// cannot be found. + /// + internal bool Remove(string relationshipKey, Topic topic, bool isIncoming) { - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(!String.IsNullOrWhiteSpace(relationshipKey), nameof(relationshipKey)); - Contract.Requires(topic); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(!String.IsNullOrWhiteSpace(relationshipKey), nameof(relationshipKey)); + Contract.Requires(topic); - /*------------------------------------------------------------------------------------------------------------------------ - | Remove reciprocal relationship, if appropriate - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!isIncoming) { - if (_isIncoming) { - throw new InvalidOperationException( - "You are attempting to remove an incoming relationship on a TopicRelationshipMultiMap that is not flagged as " + - nameof(isIncoming) - ); - } - topic.IncomingRelationships.Remove(relationshipKey, _parent, true); + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove reciprocal relationship, if appropriate + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!isIncoming) { + if (_isIncoming) { + throw new InvalidOperationException( + "You are attempting to remove an incoming relationship on a TopicRelationshipMultiMap that is not flagged as " + + nameof(isIncoming) + ); } + topic.IncomingRelationships.Remove(relationshipKey, _parent, true); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate relationshipKey - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!_storage.Contains(relationshipKey, topic)) { - return false; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate relationshipKey + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!_storage.Contains(relationshipKey, topic)) { + return false; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Remove relationship - \-----------------------------------------------------------------------------------------------------------------------*/ - _dirtyKeys.MarkAs(relationshipKey, markDirty: !_parent.IsNew); - _storage.Remove(relationshipKey, topic); + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove relationship + \-------------------------------------------------------------------------------------------------------------------------*/ + _dirtyKeys.MarkAs(relationshipKey, markDirty: !_parent.IsNew); + _storage.Remove(relationshipKey, topic); - /*------------------------------------------------------------------------------------------------------------------------ - | Remove true - \-----------------------------------------------------------------------------------------------------------------------*/ - return true; + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove true + \-------------------------------------------------------------------------------------------------------------------------*/ + return true; - } + } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(RemoveTopic)} method has been renamed to {nameof(Remove)}.", true)] - public bool RemoveTopic(string relationshipKey, Topic topic) => Remove(relationshipKey, topic); + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(RemoveTopic)} method has been renamed to {nameof(Remove)}.", true)] + public bool RemoveTopic(string relationshipKey, Topic topic) => Remove(relationshipKey, topic); - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(RemoveTopic)} method has been renamed to {nameof(Remove)}.", true)] - public bool RemoveTopic(string relationshipKey, Topic topic, bool isIncoming) => - Remove(relationshipKey, topic, isIncoming); + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(RemoveTopic)} method has been renamed to {nameof(Remove)}.", true)] + public bool RemoveTopic(string relationshipKey, Topic topic, bool isIncoming) => + Remove(relationshipKey, topic, isIncoming); - /*========================================================================================================================== - | METHOD: SET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is associated with the specified . - /// - /// - /// If a relationship by a given is not currently established, it will automatically be - /// created. - /// - /// The key of the relationship. - /// The topic to be added, if it doesn't already exist. - /// - /// Optionally forces the collection to an state, assuming the topic was set. - /// - public void SetValue(string relationshipKey, Topic topic, bool? markDirty = null) - => SetValue(relationshipKey, topic, markDirty, false); + /*============================================================================================================================ + | METHOD: SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is associated with the specified . + /// + /// + /// If a relationship by a given is not currently established, it will automatically be + /// created. + /// + /// The key of the relationship. + /// The topic to be added, if it doesn't already exist. + /// + /// Optionally forces the collection to an state, assuming the topic was set. + /// + public void SetValue(string relationshipKey, Topic topic, bool? markDirty = null) + => SetValue(relationshipKey, topic, markDirty, false); - /// - /// Ensures that an incoming is associated with the specified . - /// - /// - /// If a relationship by a given is not currently established, it will automatically be - /// created. - /// - /// The key of the relationship. - /// The topic to be added, if it doesn't already exist. - /// - /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. - /// - /// - /// Optionally forces the collection to an state, assuming the topic was set. - /// - internal void SetValue(string relationshipKey, Topic topic, bool? markDirty, bool isIncoming) { + /// + /// Ensures that an incoming is associated with the specified . + /// + /// + /// If a relationship by a given is not currently established, it will automatically be + /// created. + /// + /// The key of the relationship. + /// The topic to be added, if it doesn't already exist. + /// + /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. + /// + /// + /// Optionally forces the collection to an state, assuming the topic was set. + /// + internal void SetValue(string relationshipKey, Topic topic, bool? markDirty, bool isIncoming) { - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(!String.IsNullOrWhiteSpace(relationshipKey), nameof(relationshipKey)); - Contract.Requires(topic); - TopicFactory.ValidateKey(relationshipKey); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(!String.IsNullOrWhiteSpace(relationshipKey), nameof(relationshipKey)); + Contract.Requires(topic); + TopicFactory.ValidateKey(relationshipKey); - /*------------------------------------------------------------------------------------------------------------------------ - | Add relationship - \-----------------------------------------------------------------------------------------------------------------------*/ - var topics = _storage.GetValues(relationshipKey); - var wasDirty = _dirtyKeys.IsDirty(relationshipKey); - if (!topics.Contains(topic)) { - _storage.Add(relationshipKey, topic); - if (!_parent.IsNew && !topic.IsNew && markDirty.HasValue && !markDirty.Value && !wasDirty) { - MarkClean(relationshipKey); - } - else { - _dirtyKeys.MarkDirty(relationshipKey); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Add relationship + \-------------------------------------------------------------------------------------------------------------------------*/ + var topics = _storage.GetValues(relationshipKey); + var wasDirty = _dirtyKeys.IsDirty(relationshipKey); + if (!topics.Contains(topic)) { + _storage.Add(relationshipKey, topic); + if (!_parent.IsNew && !topic.IsNew && markDirty.HasValue && !markDirty.Value && !wasDirty) { + MarkClean(relationshipKey); } - - /*------------------------------------------------------------------------------------------------------------------------ - | Create reciprocal relationship, if appropriate - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!isIncoming) { - if (_isIncoming) { - throw new InvalidOperationException( - "You are attempting to set an incoming relationship on a TopicRelationshipMultiMap that is not flagged as " + - nameof(isIncoming) - ); - } - topic.IncomingRelationships.SetValue(relationshipKey, _parent, markDirty, true); + else { + _dirtyKeys.MarkDirty(relationshipKey); } + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Create reciprocal relationship, if appropriate + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!isIncoming) { + if (_isIncoming) { + throw new InvalidOperationException( + "You are attempting to set an incoming relationship on a TopicRelationshipMultiMap that is not flagged as " + + nameof(isIncoming) + ); + } + topic.IncomingRelationships.SetValue(relationshipKey, _parent, markDirty, true); } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(SetTopic)} method has been renamed to {nameof(SetValue)}.", true)] - public void SetTopic(string relationshipKey, Topic topic, bool? isDirty = null) => SetValue(relationshipKey, topic, isDirty); + } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(SetTopic)} method has been renamed to {nameof(SetValue)}.", true)] - public void SetTopic(string relationshipKey, Topic topic, bool? isDirty, bool isIncoming) => - SetValue(relationshipKey, topic, isDirty, isIncoming); + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(SetTopic)} method has been renamed to {nameof(SetValue)}.", true)] + public void SetTopic(string relationshipKey, Topic topic, bool? isDirty = null) => SetValue(relationshipKey, topic, isDirty); - /*========================================================================================================================== - | IS FULLY LOADED? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not the collection was fully loaded from the persistence store. - /// - /// - /// - /// When loading an individual or branch from the persistence store, it is possible that the - /// relationships may not be fully available. In this scenario, updating relationships while e.g. deleting unmatched - /// relationships can result in unintended data loss. To account for this, the property - /// tracks whether a collection was fully loaded from the persistence store; if it wasn't, the should not deleted unmatched relationships. - /// - /// - /// The property defaults to true. It should be set to false during the method if any members of the collection cannot be mapped back to - /// a valid reference in memory. - /// - /// - public bool IsFullyLoaded { get; set; } = true; + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(SetTopic)} method has been renamed to {nameof(SetValue)}.", true)] + public void SetTopic(string relationshipKey, Topic topic, bool? isDirty, bool isIncoming) => + SetValue(relationshipKey, topic, isDirty, isIncoming); - /*========================================================================================================================== - | METHOD: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public bool IsDirty() => _dirtyKeys.IsDirty(); + /*============================================================================================================================ + | IS FULLY LOADED? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not the collection was fully loaded from the persistence store. + /// + /// + /// + /// When loading an individual or branch from the persistence store, it is possible that the + /// relationships may not be fully available. In this scenario, updating relationships while e.g. deleting unmatched + /// relationships can result in unintended data loss. To account for this, the property + /// tracks whether a collection was fully loaded from the persistence store; if it wasn't, the should not deleted unmatched relationships. + /// + /// + /// The property defaults to true. It should be set to false during the method if any members of the collection cannot be mapped back to + /// a valid reference in memory. + /// + /// + public bool IsFullyLoaded { get; set; } = true; - /// - public bool IsDirty(string key) => _dirtyKeys.IsDirty(key); + /*============================================================================================================================ + | METHOD: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public bool IsDirty() => _dirtyKeys.IsDirty(); - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public void MarkClean() { - if (_parent.IsNew) { - return; - } - foreach (var relationship in _storage) { - if (!relationship.Values.AnyNew()) { - _dirtyKeys.MarkClean(relationship.Key); - } + /// + public bool IsDirty(string key) => _dirtyKeys.IsDirty(key); + + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public void MarkClean() { + if (_parent.IsNew) { + return; + } + foreach (var relationship in _storage) { + if (!relationship.Values.AnyNew()) { + _dirtyKeys.MarkClean(relationship.Key); } } + } - /// - public void MarkClean(string key) { - if (_parent.IsNew) { - return; - } - if (Contains(key) && !_storage[key].Values.AnyNew()) { - _dirtyKeys.MarkClean(key); - } + /// + public void MarkClean(string key) { + if (_parent.IsNew) { + return; + } + if (Contains(key) && !_storage[key].Values.AnyNew()) { + _dirtyKeys.MarkClean(key); } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Attributes/AttributeCollection.cs b/OnTopic/Attributes/AttributeCollection.cs index 1678f111..627a3f99 100644 --- a/OnTopic/Attributes/AttributeCollection.cs +++ b/OnTopic/Attributes/AttributeCollection.cs @@ -6,174 +6,173 @@ using OnTopic.Collections.Specialized; using OnTopic.Repositories; -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +/// +/// objects represent individual instances of attributes associated with particular topics. +/// The class tracks these through its property, which is an instance of +/// the class. +/// +public class AttributeCollection : TrackedRecordCollection { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private static readonly List _excludedAttributes = new() { + nameof(Topic.Title), + nameof(Topic.LastModified) + }; /*============================================================================================================================ - | CLASS: ATTRIBUTE COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Initializes a new instance of the class. /// /// - /// objects represent individual instances of attributes associated with particular topics. - /// The class tracks these through its property, which is an instance of - /// the class. + /// The is intended exclusively for providing access to attributes via the property. For this reason, the constructor is marked as internal. /// - public class AttributeCollection : TrackedRecordCollection { + /// A reference to the topic that the current attribute collection is bound to. + internal AttributeCollection(Topic parentTopic) : base(parentTopic) { + } - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private static readonly List _excludedAttributes = new() { - nameof(Topic.Title), - nameof(Topic.LastModified) - }; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// - /// The is intended exclusively for providing access to attributes via the property. For this reason, the constructor is marked as internal. - /// - /// A reference to the topic that the current attribute collection is bound to. - internal AttributeCollection(Topic parentTopic) : base(parentTopic) { - } - - /*========================================================================================================================== - | PROPERTY: PARENT COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override TrackedRecordCollection? ParentCollection => - AssociatedTopic.Parent?.Attributes; + /*============================================================================================================================ + | PROPERTY: PARENT COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override TrackedRecordCollection? ParentCollection => + AssociatedTopic.Parent?.Attributes; - /*========================================================================================================================== - | PROPERTY: BASE COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected override TrackedRecordCollection? BaseCollection => - AssociatedTopic.BaseTopic?.Attributes; + /*============================================================================================================================ + | PROPERTY: BASE COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + protected override TrackedRecordCollection? BaseCollection => + AssociatedTopic.BaseTopic?.Attributes; - /*========================================================================================================================== - | METHOD: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if any attributes in the are dirty. - /// - /// - /// This method is intended primarily for data storage providers, such as , which may need - /// to determine if any attributes are dirty prior to saving them to the data storage medium. Be aware that this does - /// not track whether any have been modified; as such, it may still be necessary - /// to persist changes to the storage medium. - /// - /// - /// Optionally excludes s whose keys start with LastModified. This is useful for - /// excluding the byline (LastModifiedBy) and dateline (LastModified) since these values are automatically - /// generated by e.g. the OnTopic Editor and, thus, may be irrelevant updates if no other attribute values have changed. - /// - /// True if the attribute value is marked as dirty; otherwise false. - public bool IsDirty(bool excludeLastModified) - => DeletedItems.Count > 0 || Items.Any(a => - a.IsDirty && - (!excludeLastModified || !a.Key.StartsWith("LastModified", StringComparison.OrdinalIgnoreCase)) - ); + /*============================================================================================================================ + | METHOD: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if any attributes in the are dirty. + /// + /// + /// This method is intended primarily for data storage providers, such as , which may need + /// to determine if any attributes are dirty prior to saving them to the data storage medium. Be aware that this does + /// not track whether any have been modified; as such, it may still be necessary + /// to persist changes to the storage medium. + /// + /// + /// Optionally excludes s whose keys start with LastModified. This is useful for + /// excluding the byline (LastModifiedBy) and dateline (LastModified) since these values are automatically + /// generated by e.g. the OnTopic Editor and, thus, may be irrelevant updates if no other attribute values have changed. + /// + /// True if the attribute value is marked as dirty; otherwise false. + public bool IsDirty(bool excludeLastModified) + => DeletedItems.Count > 0 || Items.Any(a => + a.IsDirty && + (!excludeLastModified || !a.Key.StartsWith("LastModified", StringComparison.OrdinalIgnoreCase)) + ); - /*========================================================================================================================== - | METHOD: SET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// - /// Minimizes the need for defensive conditions throughout the library. - /// - /// The string identifier for the . - /// The text value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// The value that the attribute was last modified. This is intended exclusively for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// Determines if the attribute originated from an extended attributes data store. - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public void SetValue( - string key, - string? value, - bool? markDirty = null, - DateTime? version = null, - bool? isExtendedAttribute = null - ) { - base.SetValue(key, value, markDirty, version); - if (Contains(key)) { - var attributeValue = this[key]; - var attributeIndex = IndexOf(attributeValue); - if (isExtendedAttribute is not null && isExtendedAttribute != attributeValue.IsExtendedAttribute) { - attributeValue = attributeValue with { - IsExtendedAttribute = isExtendedAttribute - }; - base[attributeIndex] = attributeValue; - } + /*============================================================================================================================ + | METHOD: SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// + /// Minimizes the need for defensive conditions throughout the library. + /// + /// The string identifier for the . + /// The text value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// The value that the attribute was last modified. This is intended exclusively for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// Determines if the attribute originated from an extended attributes data store. + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public void SetValue( + string key, + string? value, + bool? markDirty = null, + DateTime? version = null, + bool? isExtendedAttribute = null + ) { + base.SetValue(key, value, markDirty, version); + if (Contains(key)) { + var attributeValue = this[key]; + var attributeIndex = IndexOf(attributeValue); + if (isExtendedAttribute is not null && isExtendedAttribute != attributeValue.IsExtendedAttribute) { + attributeValue = attributeValue with { + IsExtendedAttribute = isExtendedAttribute + }; + base[attributeIndex] = attributeValue; } } + } - /*========================================================================================================================== - | METHOD: AS ATTRIBUTE DICTIONARY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an based on the of the current . Optionall includes attributes from any s that the derives from. - /// - /// - /// The method will exclude attributes which correspond to properties on - /// which contain specialized getter logic, such as and . - /// - /// - /// Determines if attributes from the should be included. Defaults to false. - /// - /// A new containing attributes - public AttributeDictionary AsAttributeDictionary(bool inheritFromBase = false) { - var sourceAttributes = (AttributeCollection?)this; - var attributes = new AttributeDictionary(); - var count = 0; - while (sourceAttributes is not null && ++count < 5) { - foreach (var attribute in sourceAttributes) { - if (count is 1 || !attributes.ContainsKey(attribute.Key)) { - attributes.TryAdd(attribute.Key, attribute.Value); - } + /*============================================================================================================================ + | METHOD: AS ATTRIBUTE DICTIONARY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an based on the of the current . Optionall includes attributes from any s that the derives from. + /// + /// + /// The method will exclude attributes which correspond to properties on + /// which contain specialized getter logic, such as and . + /// + /// + /// Determines if attributes from the should be included. Defaults to false. + /// + /// A new containing attributes + public AttributeDictionary AsAttributeDictionary(bool inheritFromBase = false) { + var sourceAttributes = (AttributeCollection?)this; + var attributes = new AttributeDictionary(); + var count = 0; + while (sourceAttributes is not null && ++count < 5) { + foreach (var attribute in sourceAttributes) { + if (count is 1 || !attributes.ContainsKey(attribute.Key)) { + attributes.TryAdd(attribute.Key, attribute.Value); } - sourceAttributes = inheritFromBase? sourceAttributes.AssociatedTopic.BaseTopic?.Attributes : null; } - foreach (var attribute in _excludedAttributes) { - attributes.Remove(attribute); - } - return attributes; + sourceAttributes = inheritFromBase? sourceAttributes.AssociatedTopic.BaseTopic?.Attributes : null; + } + foreach (var attribute in _excludedAttributes) { + attributes.Remove(attribute); } + return attributes; + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Attributes/AttributeCollectionExtensions.cs b/OnTopic/Attributes/AttributeCollectionExtensions.cs index ffbc9975..b0343358 100644 --- a/OnTopic/Attributes/AttributeCollectionExtensions.cs +++ b/OnTopic/Attributes/AttributeCollectionExtensions.cs @@ -7,407 +7,406 @@ using OnTopic.Collections.Specialized; using OnTopic.Repositories; -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE COLLECTION (EXTENSIONS) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides extensions for setting and retrieving values from the using strongly typed +/// values. +/// +public static class AttributeCollectionExtensions { /*============================================================================================================================ - | CLASS: ATTRIBUTE COLLECTION (EXTENSIONS) + | METHOD: GET BOOLEAN VALUE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides extensions for setting and retrieving values from the using strongly typed - /// values. + /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling + /// of inheritance, and an optional setting for searching through base topics for values. Return as a boolean. /// - public static class AttributeCollectionExtensions { - - /*========================================================================================================================== - | METHOD: GET BOOLEAN VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling - /// of inheritance, and an optional setting for searching through base topics for values. Return as a boolean. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's s in order to get - /// the value. - /// - /// The value for the attribute as a boolean. - public static bool GetBoolean( - this AttributeCollection attributes, - string name, - bool defaultValue = default, - bool inheritFromParent = false, - bool inheritFromBase = true - ) { - Contract.Requires(attributes); - Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); - return AttributeValueConverter.Convert( - attributes.GetValue( - name, - defaultValue ? "1" : "0", - inheritFromParent, - inheritFromBase ? 5 : 0 - ) - )?? defaultValue; - } + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's s in order to get + /// the value. + /// + /// The value for the attribute as a boolean. + public static bool GetBoolean( + this AttributeCollection attributes, + string name, + bool defaultValue = default, + bool inheritFromParent = false, + bool inheritFromBase = true + ) { + Contract.Requires(attributes); + Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); + return AttributeValueConverter.Convert( + attributes.GetValue( + name, + defaultValue ? "1" : "0", + inheritFromParent, + inheritFromBase ? 5 : 0 + ) + )?? defaultValue; + } - /*========================================================================================================================== - | METHOD: GET INTEGER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling - /// of inheritance, and an optional setting for searching through base topics for values. Return as a integer. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's s in order to get - /// the value. - /// - /// The value for the attribute as an integer. - public static int GetInteger( - this AttributeCollection attributes, - string name, - int defaultValue = default, - bool inheritFromParent = false, - bool inheritFromBase = true - ) { - Contract.Requires(attributes); - Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); - return AttributeValueConverter.Convert( - attributes.GetValue( - name, - defaultValue.ToString(CultureInfo.InvariantCulture), - inheritFromParent, - inheritFromBase? 5 : 0 - ) - )?? defaultValue; - } + /*============================================================================================================================ + | METHOD: GET INTEGER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling + /// of inheritance, and an optional setting for searching through base topics for values. Return as a integer. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's s in order to get + /// the value. + /// + /// The value for the attribute as an integer. + public static int GetInteger( + this AttributeCollection attributes, + string name, + int defaultValue = default, + bool inheritFromParent = false, + bool inheritFromBase = true + ) { + Contract.Requires(attributes); + Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); + return AttributeValueConverter.Convert( + attributes.GetValue( + name, + defaultValue.ToString(CultureInfo.InvariantCulture), + inheritFromParent, + inheritFromBase? 5 : 0 + ) + )?? defaultValue; + } - /*========================================================================================================================== - | METHOD: GET DOUBLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling - /// of inheritance, and an optional setting for searching through base topics for values. Return as a double. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's s in order to get - /// the value. - /// - /// The value for the attribute as a double. - public static double GetDouble( - this AttributeCollection attributes, - string name, - double defaultValue = default, - bool inheritFromParent = false, - bool inheritFromBase = true - ) { - Contract.Requires(attributes); - Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); - return AttributeValueConverter.Convert( - attributes.GetValue( - name, - defaultValue.ToString(CultureInfo.InvariantCulture), - inheritFromParent, - inheritFromBase? 5 : 0 - ) - )?? defaultValue; - } + /*============================================================================================================================ + | METHOD: GET DOUBLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling + /// of inheritance, and an optional setting for searching through base topics for values. Return as a double. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's s in order to get + /// the value. + /// + /// The value for the attribute as a double. + public static double GetDouble( + this AttributeCollection attributes, + string name, + double defaultValue = default, + bool inheritFromParent = false, + bool inheritFromBase = true + ) { + Contract.Requires(attributes); + Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); + return AttributeValueConverter.Convert( + attributes.GetValue( + name, + defaultValue.ToString(CultureInfo.InvariantCulture), + inheritFromParent, + inheritFromBase? 5 : 0 + ) + )?? defaultValue; + } - /*========================================================================================================================== - | METHOD: GET DATETIME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling - /// of inheritance, and an optional setting for searching through base topics for values. Return as a DateTime. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's s in order to get - /// the value. - /// - /// The value for the attribute as a DateTime object. - public static DateTime GetDateTime( - this AttributeCollection attributes, - string name, - DateTime defaultValue = default, - bool inheritFromParent = false, - bool inheritFromBase = true - ) { - Contract.Requires(attributes); - Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); - return AttributeValueConverter.Convert( - attributes.GetValue( - name, - defaultValue.ToString(CultureInfo.InvariantCulture), - inheritFromParent, - inheritFromBase ? 5 : 0 - ) - )?? defaultValue; - } + /*============================================================================================================================ + | METHOD: GET DATETIME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling + /// of inheritance, and an optional setting for searching through base topics for values. Return as a DateTime. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's s in order to get + /// the value. + /// + /// The value for the attribute as a DateTime object. + public static DateTime GetDateTime( + this AttributeCollection attributes, + string name, + DateTime defaultValue = default, + bool inheritFromParent = false, + bool inheritFromBase = true + ) { + Contract.Requires(attributes); + Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); + return AttributeValueConverter.Convert( + attributes.GetValue( + name, + defaultValue.ToString(CultureInfo.InvariantCulture), + inheritFromParent, + inheritFromBase ? 5 : 0 + ) + )?? defaultValue; + } - /*========================================================================================================================== - | METHOD: GET URI - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling - /// of inheritance, and an optional setting for searching through base topics for values. Return as a URI. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's s in order to get - /// the value. - /// - /// The value for the attribute as a DateTime object. - public static Uri? GetUri( - this AttributeCollection attributes, - string name, - Uri? defaultValue = default, - bool inheritFromParent = false, - bool inheritFromBase = true - ) { - Contract.Requires(attributes); - Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); - return AttributeValueConverter.Convert( - attributes.GetValue( - name, - null, - inheritFromParent, - inheritFromBase ? 5 : 0 - ) - )?? defaultValue; - } + /*============================================================================================================================ + | METHOD: GET URI + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling + /// of inheritance, and an optional setting for searching through base topics for values. Return as a URI. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's s in order to get + /// the value. + /// + /// The value for the attribute as a DateTime object. + public static Uri? GetUri( + this AttributeCollection attributes, + string name, + Uri? defaultValue = default, + bool inheritFromParent = false, + bool inheritFromBase = true + ) { + Contract.Requires(attributes); + Contract.Requires(!String.IsNullOrWhiteSpace(name), nameof(name)); + return AttributeValueConverter.Convert( + attributes.GetValue( + name, + null, + inheritFromParent, + inheritFromBase ? 5 : 0 + ) + )?? defaultValue; + } - /*========================================================================================================================== - | METHOD: SET BOOLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// The boolean value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public static void SetBoolean( - this AttributeCollection attributes, - string key, - bool value, - bool? isDirty = null - ) => attributes?.SetValue(key, value ? "1" : "0", isDirty); + /*============================================================================================================================ + | METHOD: SET BOOLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// The boolean value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public static void SetBoolean( + this AttributeCollection attributes, + string key, + bool value, + bool? isDirty = null + ) => attributes?.SetValue(key, value ? "1" : "0", isDirty); - /*========================================================================================================================== - | METHOD: SET INTEGER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// The integer value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public static void SetInteger( - this AttributeCollection attributes, - string key, - int value, - bool? isDirty = null - ) => attributes?.SetValue( - key, - value.ToString(CultureInfo.InvariantCulture), - isDirty - ); + /*============================================================================================================================ + | METHOD: SET INTEGER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// The integer value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public static void SetInteger( + this AttributeCollection attributes, + string key, + int value, + bool? isDirty = null + ) => attributes?.SetValue( + key, + value.ToString(CultureInfo.InvariantCulture), + isDirty + ); - /*========================================================================================================================== - | METHOD: SET DOUBLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// The double value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public static void SetDouble( - this AttributeCollection attributes, - string key, - double value, - bool? isDirty = null - ) => attributes?.SetValue( - key, - value.ToString(CultureInfo.InvariantCulture), - isDirty - ); + /*============================================================================================================================ + | METHOD: SET DOUBLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// The double value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public static void SetDouble( + this AttributeCollection attributes, + string key, + double value, + bool? isDirty = null + ) => attributes?.SetValue( + key, + value.ToString(CultureInfo.InvariantCulture), + isDirty + ); - /*========================================================================================================================== - | METHOD: SET DATETIME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// The value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public static void SetDateTime( - this AttributeCollection attributes, - string key, - DateTime value, - bool? isDirty = null - ) => attributes?.SetValue( - key, - value.ToString(CultureInfo.InvariantCulture), - isDirty - ); + /*============================================================================================================================ + | METHOD: SET DATETIME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// The value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public static void SetDateTime( + this AttributeCollection attributes, + string key, + DateTime value, + bool? isDirty = null + ) => attributes?.SetValue( + key, + value.ToString(CultureInfo.InvariantCulture), + isDirty + ); - /*========================================================================================================================== - | METHOD: SET URI - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// The instance of the this extension is bound to. - /// The string identifier for the . - /// The value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public static void SetUri( - this AttributeCollection attributes, - string key, - Uri value, - bool? isDirty = null - ) => attributes?.SetValue( - key, - value?.ToString(), - isDirty - ); + /*============================================================================================================================ + | METHOD: SET URI + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// The instance of the this extension is bound to. + /// The string identifier for the . + /// The value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public static void SetUri( + this AttributeCollection attributes, + string key, + Uri value, + bool? isDirty = null + ) => attributes?.SetValue( + key, + value?.ToString(), + isDirty + ); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Attributes/AttributeDictionary.cs b/OnTopic/Attributes/AttributeDictionary.cs index e2b98918..cd4b302d 100644 --- a/OnTopic/Attributes/AttributeDictionary.cs +++ b/OnTopic/Attributes/AttributeDictionary.cs @@ -5,98 +5,97 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE DICTIONARY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a light-weight dictionary of attribute values. +/// +/// +/// The is used by the to support self-constructed +/// models that don't require the use of the to set the values of scalar properties. Any +/// model that has a primary constructor accepting a single will be initialized using +/// a containing all attributes from not only the current , but also +/// any s it references. +/// +public class AttributeDictionary: Dictionary { /*============================================================================================================================ - | CLASS: ATTRIBUTE DICTIONARY + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public AttributeDictionary(): base(StringComparer.OrdinalIgnoreCase) { } + + /*============================================================================================================================ + | METHOD: GET VALUE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a light-weight dictionary of attribute values. + /// Gets an attribute value as a string from the based on the . /// - /// - /// The is used by the to support self-constructed - /// models that don't require the use of the to set the values of scalar properties. Any - /// model that has a primary constructor accepting a single will be initialized using - /// a containing all attributes from not only the current , but also - /// any s it references. - /// - public class AttributeDictionary: Dictionary { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public AttributeDictionary(): base(StringComparer.OrdinalIgnoreCase) { } - - /*========================================================================================================================== - | METHOD: GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an attribute value as a string from the based on the . - /// - /// The key of the attribute to retrieve. - /// - public string? GetValue(string attributeKey) { - Contract.Requires(!String.IsNullOrWhiteSpace(attributeKey), nameof(attributeKey)); - TryGetValue(attributeKey, out var value); - return String.IsNullOrWhiteSpace(value)? null : value; - } + /// The key of the attribute to retrieve. + /// + public string? GetValue(string attributeKey) { + Contract.Requires(!String.IsNullOrWhiteSpace(attributeKey), nameof(attributeKey)); + TryGetValue(attributeKey, out var value); + return String.IsNullOrWhiteSpace(value)? null : value; + } - /*========================================================================================================================== - | METHOD: GET BOOLEAN VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an attribute value as a Boolean from the based on the . - /// - /// The string identifier for the . - /// The value for the attribute as a boolean. - public bool? GetBoolean(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); + /*============================================================================================================================ + | METHOD: GET BOOLEAN VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an attribute value as a Boolean from the based on the . + /// + /// The string identifier for the . + /// The value for the attribute as a boolean. + public bool? GetBoolean(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); - /*========================================================================================================================== - | METHOD: GET INTEGER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an attribute value as an integer from the based on the . - /// - /// The string identifier for the . - /// The value for the attribute as an integer. - public int? GetInteger(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); + /*============================================================================================================================ + | METHOD: GET INTEGER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an attribute value as an integer from the based on the . + /// + /// The string identifier for the . + /// The value for the attribute as an integer. + public int? GetInteger(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); - /*========================================================================================================================== - | METHOD: GET DOUBLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an attribute value as a double from the based on the . - /// - /// The string identifier for the . - /// The value for the attribute as a double. - public double? GetDouble(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); + /*============================================================================================================================ + | METHOD: GET DOUBLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an attribute value as a double from the based on the . + /// + /// The string identifier for the . + /// The value for the attribute as a double. + public double? GetDouble(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); - /*========================================================================================================================== - | METHOD: GET DATETIME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an attribute value as a date/time from the based on the . - /// - /// The string identifier for the . - /// The value for the attribute as a DateTime object. - public DateTime? GetDateTime(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); + /*============================================================================================================================ + | METHOD: GET DATETIME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an attribute value as a date/time from the based on the . + /// + /// The string identifier for the . + /// The value for the attribute as a DateTime object. + public DateTime? GetDateTime(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); - /*========================================================================================================================== - | METHOD: GET URI - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an attribute value as a URI from the based on the . - /// - /// The string identifier for the . - /// The value for the attribute as a Uri object. - public Uri? GetUri(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); + /*============================================================================================================================ + | METHOD: GET URI + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an attribute value as a URI from the based on the . + /// + /// The string identifier for the . + /// The value for the attribute as a Uri object. + public Uri? GetUri(string attributeKey) => AttributeValueConverter.Convert(GetValue(attributeKey)); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Attributes/AttributeRecord.cs b/OnTopic/Attributes/AttributeRecord.cs index 1b911c8e..d0a26151 100644 --- a/OnTopic/Attributes/AttributeRecord.cs +++ b/OnTopic/Attributes/AttributeRecord.cs @@ -7,111 +7,110 @@ using OnTopic.Metadata; using OnTopic.Repositories; -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE RECORD +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents the immutable value of a particular attribute on a . +/// +/// +/// +/// Provides values and metadata specific to individual attribute values, such as state (e.g., the property signifies whether the attribute value has changed) and its date. +/// +/// +/// Typically, the will be exposed as part of a via the +/// collection. +/// +/// +/// Be aware that while represents the value of a specific attribute, the metadata for +/// describing the purpose, constraints, and usage of that particular attribute is described by the class. +/// +/// +/// This class is immutable: once it is constructed, the values cannot be changed. To change a value, callers must either +/// create a new instance of the class or, preferably, call the 's method. +/// +/// +public record AttributeRecord: TrackedRecord { + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public AttributeRecord(): base() { } + + /// + /// Initializes a new instance of the class, using the specified key/value pair. + /// + /// + /// The string identifier for the collection item key/value pair. + /// + /// + /// The string value text for the collection item key/value pair. + /// + /// + /// An optional boolean indicator noting whether the collection item is a new value, and + /// should thus be saved to the database when is next called. + /// + /// + /// The value that the attribute was last modified. This is intended primarily for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// Determines if the attribute originated from an extended attributes data store. + /// + /// !String.IsNullOrWhiteSpace(key) + /// + public AttributeRecord( + string key, + string? value, + bool isDirty = true, + DateTime? lastModified = null, + bool? isExtendedAttribute = null + ): base(key, value, isDirty, lastModified) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set local values + \-------------------------------------------------------------------------------------------------------------------------*/ + IsExtendedAttribute = isExtendedAttribute; + + } /*============================================================================================================================ - | CLASS: ATTRIBUTE RECORD + | PROPERTY: IS EXTENDED ATTRIBUTE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents the immutable value of a particular attribute on a . + /// Determines if this attribute originated from a data store as an extended attribute. /// /// /// - /// Provides values and metadata specific to individual attribute values, such as state (e.g., the property signifies whether the attribute value has changed) and its date. - /// - /// - /// Typically, the will be exposed as part of a via the - /// collection. + /// How an attribute is stored in the underlying repository doesn't impact how the attribute is treated as part of the + /// object model. By tracking this, however, OnTopic is able to evaluate configuration mismatches during . This allows the to effective handle + /// scenarios where the configuration for an has changed prior to the last time a was saved, and thus change the location where it is stored. /// /// - /// Be aware that while represents the value of a specific attribute, the metadata for - /// describing the purpose, constraints, and usage of that particular attribute is described by the class. + /// This is important because, otherwise, implementations rely primarily on to determine if a value should be saved. If an attribute's value hasn't changed, + /// but the location it should be stored has, that could potentially result in the attribute being deleted, as the + /// attribute won't show up for when is called with isDirty set to + /// true and isExtendedAttribute is set to either true or false. By introducing , the is able to detect conflicts between the configuration and + /// the underlying data store, and ensure data is stored appropriately. /// /// - /// This class is immutable: once it is constructed, the values cannot be changed. To change a value, callers must either - /// create a new instance of the class or, preferably, call the 's method. + /// The property maps to the + /// property. The former describes where the data was actually stored, whereas the latter describes where the + /// data should be stored. /// /// - public record AttributeRecord: TrackedRecord { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public AttributeRecord(): base() { } - - /// - /// Initializes a new instance of the class, using the specified key/value pair. - /// - /// - /// The string identifier for the collection item key/value pair. - /// - /// - /// The string value text for the collection item key/value pair. - /// - /// - /// An optional boolean indicator noting whether the collection item is a new value, and - /// should thus be saved to the database when is next called. - /// - /// - /// The value that the attribute was last modified. This is intended primarily for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// Determines if the attribute originated from an extended attributes data store. - /// - /// !String.IsNullOrWhiteSpace(key) - /// - public AttributeRecord( - string key, - string? value, - bool isDirty = true, - DateTime? lastModified = null, - bool? isExtendedAttribute = null - ): base(key, value, isDirty, lastModified) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Set local values - \-----------------------------------------------------------------------------------------------------------------------*/ - IsExtendedAttribute = isExtendedAttribute; - - } - - /*========================================================================================================================== - | PROPERTY: IS EXTENDED ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if this attribute originated from a data store as an extended attribute. - /// - /// - /// - /// How an attribute is stored in the underlying repository doesn't impact how the attribute is treated as part of the - /// object model. By tracking this, however, OnTopic is able to evaluate configuration mismatches during . This allows the to effective handle - /// scenarios where the configuration for an has changed prior to the last time a was saved, and thus change the location where it is stored. - /// - /// - /// This is important because, otherwise, implementations rely primarily on to determine if a value should be saved. If an attribute's value hasn't changed, - /// but the location it should be stored has, that could potentially result in the attribute being deleted, as the - /// attribute won't show up for when is called with isDirty set to - /// true and isExtendedAttribute is set to either true or false. By introducing , the is able to detect conflicts between the configuration and - /// the underlying data store, and ensure data is stored appropriately. - /// - /// - /// The property maps to the - /// property. The former describes where the data was actually stored, whereas the latter describes where the - /// data should be stored. - /// - /// - public bool? IsExtendedAttribute { get; init; } + public bool? IsExtendedAttribute { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Attributes/AttributeSetterAttribute.cs b/OnTopic/Attributes/AttributeSetterAttribute.cs index 0068f903..807d4a6a 100644 --- a/OnTopic/Attributes/AttributeSetterAttribute.cs +++ b/OnTopic/Attributes/AttributeSetterAttribute.cs @@ -6,43 +6,42 @@ using OnTopic.Collections; using OnTopic.Collections.Specialized; -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; - /*============================================================================================================================ - | CLASS: ATTRIBUTE SETTER [ATTRIBUTE] - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Flags that a property should be used when setting an attribute via . - /// - /// - /// - /// When a call is made to , the - /// code will check to see if a property with the same name as the attribute key exists, and whether that property is - /// decorated with the (i.e., [AttributeSetter]). If it is, then the update - /// will be routed through that property. This ensures that business logic is enforced by local properties, instead of - /// allowing business logic to be potentially bypassed by writing directly to the - /// collection. - /// - /// - /// As an example, the property is adorned with the . As a - /// result, if a client calls topic.Attributes.SetValue("Key", "NewKey") then that update will be routed through - /// , thus enforcing key validation, and calling . Similarly, if topic.Attributes.SetValue("Key", ":/? ") were called, a contract exception will be - /// thrown since :/? violates . - /// - /// - /// To ensure this logic, it is critical that implementers of ensure that the - /// property setters call overload with the final parameter set to false to disable the enforcement of business logic. - /// Otherwise, an infinite loop will occur. Calling that overload tells that the - /// business logic has already been enforced by the caller. As this is an internal overload, implementers should use the - /// local proxy at , which ensures that final parameter is - /// set to false. - /// - /// - [AttributeUsage(AttributeTargets.Property)] - public sealed class AttributeSetterAttribute : Attribute { +/*============================================================================================================================== +| CLASS: ATTRIBUTE SETTER [ATTRIBUTE] +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a property should be used when setting an attribute via . +/// +/// +/// +/// When a call is made to , the +/// code will check to see if a property with the same name as the attribute key exists, and whether that property is +/// decorated with the (i.e., [AttributeSetter]). If it is, then the update +/// will be routed through that property. This ensures that business logic is enforced by local properties, instead of +/// allowing business logic to be potentially bypassed by writing directly to the +/// collection. +/// +/// +/// As an example, the property is adorned with the . As a +/// result, if a client calls topic.Attributes.SetValue("Key", "NewKey") then that update will be routed through +/// , thus enforcing key validation, and calling . Similarly, if topic.Attributes.SetValue("Key", ":/? ") were called, a contract exception will be +/// thrown since :/? violates . +/// +/// +/// To ensure this logic, it is critical that implementers of ensure that the +/// property setters call overload with the final parameter set to false to disable the enforcement of business logic. +/// Otherwise, an infinite loop will occur. Calling that overload tells that the +/// business logic has already been enforced by the caller. As this is an internal overload, implementers should use the +/// local proxy at , which ensures that final parameter is +/// set to false. +/// +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class AttributeSetterAttribute : Attribute { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Attributes/AttributeValueConverter.cs b/OnTopic/Attributes/AttributeValueConverter.cs index e890cb42..934ba78e 100644 --- a/OnTopic/Attributes/AttributeValueConverter.cs +++ b/OnTopic/Attributes/AttributeValueConverter.cs @@ -7,151 +7,130 @@ using System.Globalization; using OnTopic.Mapping; -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE VALUE CONVERTER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Attribute values are stored as strings, but may be deserialized to other value types using e.g. the or the . This class provides basic methods for +/// converting from the string representation to supported value types. +/// +internal static class AttributeValueConverter { /*============================================================================================================================ - | CLASS: ATTRIBUTE VALUE CONVERTER + | PROPERTY: CONVERTIBLE TYPES \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Attribute values are stored as strings, but may be deserialized to other value types using e.g. the or the . This class provides basic methods for - /// converting from the string representation to supported value types. + /// A list of types that are allowed to be converted using . /// - internal static class AttributeValueConverter { + private static Collection ConvertibleTypes { get; } = + new() { + typeof(bool), + typeof(bool?), + typeof(int), + typeof(int?), + typeof(double), + typeof(double?), + typeof(string), + typeof(DateTime), + typeof(DateTime?), + typeof(Uri) + }; - /*========================================================================================================================== - | PROPERTY: CONVERTIBLE TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A list of types that are allowed to be converted using . - /// - private static Collection ConvertibleTypes { get; } = - new() { - typeof(bool), - typeof(bool?), - typeof(int), - typeof(int?), - typeof(double), - typeof(double?), - typeof(string), - typeof(DateTime), - typeof(DateTime?), - typeof(Uri) - }; - - /*========================================================================================================================== - | METHOD: IS CONVERTIBLE? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether the supports converting a to a . - /// - /// The to be converted to. - /// - - internal static bool IsConvertible(Type type) => ConvertibleTypes.Contains(type); - - /*========================================================================================================================== - | METHOD: CONVERT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Converts the supplied to an object of type . - /// - /// The value to convert to the . - /// The to be converted to. - /// An instance of the as a . - internal static object? Convert(string? value, Type type) { - - var valueObject = (object?)null; - - //Treat empty as null for non-strings, regardless of whether they’re nullable - if (!type.Equals(typeof(string)) && String.IsNullOrWhiteSpace(value)) { - return null; - } + /*============================================================================================================================ + | METHOD: IS CONVERTIBLE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether the supports converting a to a . + /// + /// The to be converted to. + /// - if (value is null) return null; + internal static bool IsConvertible(Type type) => ConvertibleTypes.Contains(type); - if (type.Equals(typeof(string))) { - valueObject = value; - } - else if (type.Equals(typeof(bool)) || type.Equals(typeof(bool?))) { - if (value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)) { - valueObject = true; - } - else if (value is "0" || value.Equals("false", StringComparison.OrdinalIgnoreCase)) { - valueObject = false; - } - } - else if (type.Equals(typeof(int)) || type.Equals(typeof(int?))) { - if (Int32.TryParse(value, out var intValue)) { - valueObject = intValue; - } - } - else if (type.Equals(typeof(double)) || type.Equals(typeof(double?))) { - if (Double.TryParse(value, out var doubleValue)) { - valueObject = doubleValue; - } - } - else if (type.Equals(typeof(DateTime)) || type.Equals(typeof(DateTime?))) { - if (DateTime.TryParse(value, out var date)) { - valueObject = date; - } - } - else if (type.Equals(typeof(Uri))) { - if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out var uri)) { - valueObject = uri; - } - } + /*============================================================================================================================ + | METHOD: CONVERT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Converts the supplied to an object of type . + /// + /// The value to convert to the . + /// The to be converted to. + /// An instance of the as a . + internal static object? Convert(string? value, Type type) { - return valueObject; + var valueObject = (object?)null; + //Treat empty as null for non-strings, regardless of whether they’re nullable + if (!type.Equals(typeof(string)) && String.IsNullOrWhiteSpace(value)) { + return null; } - /// - internal static T? Convert(string? value) => (T?)Convert(value, typeof(T))?? default; - - /// - /// Converts the supplied to an object of type . - /// - /// The value to convert to a . - /// An instance of the as a . - internal static string? Convert(object? value) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null values - \-----------------------------------------------------------------------------------------------------------------------*/ - if (value is null) { - return null; - } + if (value is null) return null; - /*------------------------------------------------------------------------------------------------------------------------ - | Handle type-specific rules - \-----------------------------------------------------------------------------------------------------------------------*/ - if (value is string stringValue) { - return stringValue; + if (type.Equals(typeof(string))) { + valueObject = value; + } + else if (type.Equals(typeof(bool)) || type.Equals(typeof(bool?))) { + if (value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)) { + valueObject = true; } - else if (value is bool boolValue) { - return boolValue ? "1" : "0"; + else if (value is "0" || value.Equals("false", StringComparison.OrdinalIgnoreCase)) { + valueObject = false; } - else if (value is int intValue) { - return intValue.ToString(CultureInfo.InvariantCulture); + } + else if (type.Equals(typeof(int)) || type.Equals(typeof(int?))) { + if (Int32.TryParse(value, out var intValue)) { + valueObject = intValue; } - else if (value is double doubleValue) { - return doubleValue.ToString(CultureInfo.InvariantCulture); + } + else if (type.Equals(typeof(double)) || type.Equals(typeof(double?))) { + if (Double.TryParse(value, out var doubleValue)) { + valueObject = doubleValue; } - else if (value is DateTime dateTimeValue) { - return dateTimeValue.ToString(CultureInfo.InvariantCulture); + } + else if (type.Equals(typeof(DateTime)) || type.Equals(typeof(DateTime?))) { + if (DateTime.TryParse(value, out var date)) { + valueObject = date; } - else if (value is Uri uriValue) { - return uriValue.ToString(); + } + else if (type.Equals(typeof(Uri))) { + if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out var uri)) { + valueObject = uri; } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Fallback to default - \-----------------------------------------------------------------------------------------------------------------------*/ - return value.ToString(); + return valueObject; - } + } + + /// + internal static T? Convert(string? value) => (T?)Convert(value, typeof(T))?? default; + + /// + /// Converts the supplied to an object of type . + /// + /// The value to convert to a . + /// An instance of the as a . + internal static string? Convert(object? value) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Convert to string by type + \-------------------------------------------------------------------------------------------------------------------------*/ + return value switch { + null => null, + string stringValue => stringValue, + bool boolValue => boolValue ? "1" : "0", + int intValue => intValue.ToString(CultureInfo.InvariantCulture), + double doubleValue => doubleValue.ToString(CultureInfo.InvariantCulture), + DateTime dateTimeValue => dateTimeValue.ToString(CultureInfo.InvariantCulture), + Uri uriValue => uriValue.ToString(), + _ => value.ToString() + }; } + } \ No newline at end of file diff --git a/OnTopic/Collections/KeyedTopicCollection.cs b/OnTopic/Collections/KeyedTopicCollection.cs index 1edae63f..927e1cb8 100644 --- a/OnTopic/Collections/KeyedTopicCollection.cs +++ b/OnTopic/Collections/KeyedTopicCollection.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: KEYED TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +public class KeyedTopicCollection : KeyedTopicCollection { /*============================================================================================================================ - | CLASS: KEYED TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Initializes a new instance of the . /// - public class KeyedTopicCollection : KeyedTopicCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - /// Seeds the collection with an optional list of topic references. - public KeyedTopicCollection(IEnumerable? topics = null) : base(topics) { - } + /// Seeds the collection with an optional list of topic references. + public KeyedTopicCollection(IEnumerable? topics = null) : base(topics) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/KeyedTopicCollection{T}.cs b/OnTopic/Collections/KeyedTopicCollection{T}.cs index 885780d6..5dae6309 100644 --- a/OnTopic/Collections/KeyedTopicCollection{T}.cs +++ b/OnTopic/Collections/KeyedTopicCollection{T}.cs @@ -5,123 +5,122 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: KEYED TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed collection of instances, or a derived type. +/// +public class KeyedTopicCollection: KeyedCollection, IEnumerable where T : Topic { /*============================================================================================================================ - | CLASS: KEYED TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed collection of instances, or a derived type. + /// Initializes a new instance of the class. /// - public class KeyedTopicCollection: KeyedCollection, IEnumerable where T : Topic { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// Seeds the collection with an optional list of topic references. - public KeyedTopicCollection(IEnumerable? topics = null) : base(StringComparer.OrdinalIgnoreCase) { - if (topics is not null) { - foreach (var topic in topics) { - Add(topic); - } + /// Seeds the collection with an optional list of topic references. + public KeyedTopicCollection(IEnumerable? topics = null) : base(StringComparer.OrdinalIgnoreCase) { + if (topics is not null) { + foreach (var topic in topics) { + Add(topic); } } + } - /*========================================================================================================================== - | METHOD: GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a by . - /// - public T? GetValue(string key) { - TopicFactory.ValidateKey(key); - if (Contains(key)) { - return this[key]; - } - return null; + /*============================================================================================================================ + | METHOD: GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a by . + /// + public T? GetValue(string key) { + TopicFactory.ValidateKey(key); + if (Contains(key)) { + return this[key]; } + return null; + } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(GetTopic)} method has been renamed to {nameof(GetValue)}.", true)] - public T? GetTopic(string key) => GetValue(key); + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(GetTopic)} method has been renamed to {nameof(GetValue)}.", true)] + public T? GetTopic(string key) => GetValue(key); - /*========================================================================================================================== - | METHOD: AS READ ONLY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a read-only version of this . - /// - public ReadOnlyKeyedTopicCollection AsReadOnly() => new(this); - - /*========================================================================================================================== - | OVERRIDE: INSERT ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// Fires any time a is added to the collection. - /// - /// Compared to the base implementation, will throw a specific error if a duplicate key is - /// inserted. This conveniently provides the name of the 's , so - /// it's clear what key is being duplicated. - /// - /// The zero-based index at which should be inserted. - /// The instance to insert. - /// - /// A {typeof(T).Name} with the Key '{item.Key}' already exists. The UniqueKey of the existing {typeof(T).Name} is - /// '{GetUniqueKey()}'; the new item's is '{item.GetUniqueKey()}'. - /// - protected override sealed void InsertItem(int index, T item) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(item, nameof(item)); + /*============================================================================================================================ + | METHOD: AS READ ONLY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a read-only version of this . + /// + public ReadOnlyKeyedTopicCollection AsReadOnly() => new(this); - /*------------------------------------------------------------------------------------------------------------------------ - | Insert item, if not already present - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!Contains(item.Key)) { - base.InsertItem(index, item); - } - else { - throw new ArgumentException( - $"A {typeof(T).Name} with the Key '{item.Key}' already exists. The UniqueKey of the existing {typeof(T).Name} is " + - $"'{this[item.Key].GetUniqueKey()}'; the new item's is '{item.GetUniqueKey()}'.", - nameof(item) - ); - } - } + /*============================================================================================================================ + | OVERRIDE: INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// Fires any time a is added to the collection. + /// + /// Compared to the base implementation, will throw a specific error if a duplicate key is + /// inserted. This conveniently provides the name of the 's , so + /// it's clear what key is being duplicated. + /// + /// The zero-based index at which should be inserted. + /// The instance to insert. + /// + /// A {typeof(T).Name} with the Key '{item.Key}' already exists. The UniqueKey of the existing {typeof(T).Name} is + /// '{GetUniqueKey()}'; the new item's is '{item.GetUniqueKey()}'. + /// + protected override sealed void InsertItem(int index, T item) { - /*========================================================================================================================== - | METHOD: CHANGE KEY + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Changes the key associated with a topic to maintain referential integrity. - /// - /// - /// By default, doesn't permit mutable keys; this mitigates that issue by - /// allowing the collection's lookup dictionary to be updated whenever the key is updated in the corresponding topic - /// object. - /// - /// The topic object for which the should be changed. - /// The string value for the new key. - internal void ChangeKey(T topic, string newKey) => base.ChangeItemKey(topic, newKey); + Contract.Requires(item, nameof(item)); - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM + /*-------------------------------------------------------------------------------------------------------------------------- + | Insert item, if not already present \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Method must be overridden for the EntityCollection to extract the keys from the items. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - [ExcludeFromCodeCoverage] - protected override sealed string GetKeyForItem(T item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Key; + if (!Contains(item.Key)) { + base.InsertItem(index, item); + } + else { + throw new ArgumentException( + $"A {typeof(T).Name} with the Key '{item.Key}' already exists. The UniqueKey of the existing {typeof(T).Name} is " + + $"'{this[item.Key].GetUniqueKey()}'; the new item's is '{item.GetUniqueKey()}'.", + nameof(item) + ); } + } + + /*============================================================================================================================ + | METHOD: CHANGE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Changes the key associated with a topic to maintain referential integrity. + /// + /// + /// By default, doesn't permit mutable keys; this mitigates that issue by + /// allowing the collection's lookup dictionary to be updated whenever the key is updated in the corresponding topic + /// object. + /// + /// The topic object for which the should be changed. + /// The string value for the new key. + internal void ChangeKey(T topic, string newKey) => base.ChangeItemKey(topic, newKey); + + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Method must be overridden for the EntityCollection to extract the keys from the items. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + [ExcludeFromCodeCoverage] + protected override sealed string GetKeyForItem(T item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Key; + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/ReadOnlyKeyedTopicCollection.cs b/OnTopic/Collections/ReadOnlyKeyedTopicCollection.cs index 8e2bcd57..ad774505 100644 --- a/OnTopic/Collections/ReadOnlyKeyedTopicCollection.cs +++ b/OnTopic/Collections/ReadOnlyKeyedTopicCollection.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: READ-ONLY KEYED TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +public class ReadOnlyKeyedTopicCollection : ReadOnlyKeyedTopicCollection { /*============================================================================================================================ - | CLASS: READ-ONLY KEYED TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Establishes a new based on an existing . /// - public class ReadOnlyKeyedTopicCollection : ReadOnlyKeyedTopicCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// The underlying . - public ReadOnlyKeyedTopicCollection(IList? innerCollection = null) : base(innerCollection) { - } + /// The underlying . + public ReadOnlyKeyedTopicCollection(IList? innerCollection = null) : base(innerCollection) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/ReadOnlyKeyedTopicCollection{T}.cs b/OnTopic/Collections/ReadOnlyKeyedTopicCollection{T}.cs index aca8270b..30d45eff 100644 --- a/OnTopic/Collections/ReadOnlyKeyedTopicCollection{T}.cs +++ b/OnTopic/Collections/ReadOnlyKeyedTopicCollection{T}.cs @@ -5,73 +5,72 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: READ-ONLY KEYED TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a read-only collection of topics. +/// +public class ReadOnlyKeyedTopicCollection : ReadOnlyCollection where T : Topic { /*============================================================================================================================ - | CLASS: READ-ONLY KEYED TOPIC COLLECTION + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly KeyedTopicCollection _innerCollection; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a read-only collection of topics. + /// Establishes a new based on an existing . /// - public class ReadOnlyKeyedTopicCollection : ReadOnlyCollection where T : Topic { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly KeyedTopicCollection _innerCollection; + /// The underlying . + public ReadOnlyKeyedTopicCollection(IList? innerCollection = null) : base(innerCollection?? new List()) { + _innerCollection = innerCollection as KeyedTopicCollection?? new(innerCollection); + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// The underlying . - public ReadOnlyKeyedTopicCollection(IList? innerCollection = null) : base(innerCollection?? new List()) { - _innerCollection = innerCollection as KeyedTopicCollection?? new(innerCollection); - } - - /*========================================================================================================================== - | FACTORY METHOD: FROM LIST - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// - /// The will be converted to a . - /// - /// The underlying . - [ExcludeFromCodeCoverage] - [Obsolete("This is effectively satisfied by the related overload, and has been removed.", true)] - public ReadOnlyTopicCollection FromList(IList innerCollection) => throw new NotImplementedException(); + /*============================================================================================================================ + | FACTORY METHOD: FROM LIST + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new based on an existing . + /// + /// + /// The will be converted to a . + /// + /// The underlying . + [ExcludeFromCodeCoverage] + [Obsolete("This is effectively satisfied by the related overload, and has been removed.", true)] + public ReadOnlyTopicCollection FromList(IList innerCollection) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a by . - /// - public T? GetValue(string key) { - TopicFactory.ValidateKey(key); - if (_innerCollection.Contains(key)) { - return _innerCollection[key]; - } - return null; + /*============================================================================================================================ + | METHOD: GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a by . + /// + public T? GetValue(string key) { + TopicFactory.ValidateKey(key); + if (_innerCollection.Contains(key)) { + return _innerCollection[key]; } + return null; + } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(GetTopic)} method has been renamed to {nameof(GetValue)}.", true)] - public T? GetTopic(string key) => GetValue(key); + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(GetTopic)} method has been renamed to {nameof(GetValue)}.", true)] + public T? GetTopic(string key) => GetValue(key); - /*========================================================================================================================== - | INDEXER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves an by key. - /// - /// The topic key. - public Topic this[string key] => _innerCollection[key]; + /*============================================================================================================================ + | INDEXER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves an by key. + /// + /// The topic key. + public Topic this[string key] => _innerCollection[key]; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/ReadOnlyTopicCollection.cs b/OnTopic/Collections/ReadOnlyTopicCollection.cs index c0a50758..2de234fe 100644 --- a/OnTopic/Collections/ReadOnlyTopicCollection.cs +++ b/OnTopic/Collections/ReadOnlyTopicCollection.cs @@ -5,64 +5,63 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: READ-ONLY TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +public class ReadOnlyTopicCollection : ReadOnlyCollection { /*============================================================================================================================ - | CLASS: READ-ONLY TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Establishes a new based on an existing . /// - public class ReadOnlyTopicCollection : ReadOnlyCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// The underlying . - [ExcludeFromCodeCoverage] - public ReadOnlyTopicCollection(IList? innerCollection = null) : base(innerCollection?? new List()) { - } + /// The underlying . + [ExcludeFromCodeCoverage] + public ReadOnlyTopicCollection(IList? innerCollection = null) : base(innerCollection?? new List()) { + } - /*========================================================================================================================== - | FACTORY METHOD: FROM LIST - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// - /// The will be converted to a . - /// - /// The underlying . - [ExcludeFromCodeCoverage] - [Obsolete("This is effectively satisfied by the related overload, and has been removed.", true)] - public ReadOnlyTopicCollection FromList(IList innerCollection) => throw new NotImplementedException(); + /*============================================================================================================================ + | FACTORY METHOD: FROM LIST + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new based on an existing . + /// + /// + /// The will be converted to a . + /// + /// The underlying . + [ExcludeFromCodeCoverage] + [Obsolete("This is effectively satisfied by the related overload, and has been removed.", true)] + public ReadOnlyTopicCollection FromList(IList innerCollection) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: GET TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The {nameof(GetValue)} method is not implemented on {nameof(ReadOnlyTopicCollection)}. Use " + - $"{nameof(ReadOnlyKeyedTopicCollection)} instead.", - true - )] - public Topic? GetValue(string key) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: GET TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"The {nameof(GetValue)} method is not implemented on {nameof(ReadOnlyTopicCollection)}. Use " + + $"{nameof(ReadOnlyKeyedTopicCollection)} instead.", + true + )] + public Topic? GetValue(string key) => throw new NotImplementedException(); - /*========================================================================================================================== - | INDEXER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"Indexing by key is not implemented on {nameof(ReadOnlyTopicCollection)}. Use {nameof(ReadOnlyKeyedTopicCollection)} " + - $"instead.", - true - )] - public Topic this[string key] => throw new ArgumentOutOfRangeException(nameof(key)); + /*============================================================================================================================ + | INDEXER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"Indexing by key is not implemented on {nameof(ReadOnlyTopicCollection)}. Use {nameof(ReadOnlyKeyedTopicCollection)} " + + $"instead.", + true + )] + public Topic this[string key] => throw new ArgumentOutOfRangeException(nameof(key)); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/DirtyKeyCollection.cs b/OnTopic/Collections/Specialized/DirtyKeyCollection.cs index 6cdf6e7b..54cb27db 100644 --- a/OnTopic/Collections/Specialized/DirtyKeyCollection.cs +++ b/OnTopic/Collections/Specialized/DirtyKeyCollection.cs @@ -5,76 +5,75 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: DIRTY KEY COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of dirty keys. +/// +/// +/// This collection does not track the values of those keys or attempt to determine if a value is dirty. It simply provides +/// a convenient way for other collections to track dirty keys based on their own internal logic. +/// +internal sealed class DirtyKeyCollection : Collection, ITrackDirtyKeys { /*============================================================================================================================ - | CLASS: DIRTY KEY COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of dirty keys. + /// Initializes a new instance of the . /// - /// - /// This collection does not track the values of those keys or attempt to determine if a value is dirty. It simply provides - /// a convenient way for other collections to track dirty keys based on their own internal logic. - /// - internal class DirtyKeyCollection : Collection, ITrackDirtyKeys { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - public DirtyKeyCollection() : base() {} + public DirtyKeyCollection() : base() {} - /*========================================================================================================================== - | METHOD: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public bool IsDirty() => Count > 0; + /*============================================================================================================================ + | METHOD: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public bool IsDirty() => Count > 0; - /// - public bool IsDirty(string key) => Contains(key); + /// + public bool IsDirty(string key) => Contains(key); - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public void MarkClean() => Clear(); + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public void MarkClean() => Clear(); - /// - public void MarkClean(string key) { - if (Contains(key)) { - Remove(key); - } + /// + public void MarkClean(string key) { + if (Contains(key)) { + Remove(key); } + } - /*========================================================================================================================== - | METHOD: MARK DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Marks a specific as dirty, if it isn't already. - /// - public void MarkDirty(string key) { - if (!Contains(key)) { - Add(key); - } + /*============================================================================================================================ + | METHOD: MARK DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Marks a specific as dirty, if it isn't already. + /// + public void MarkDirty(string key) { + if (!Contains(key)) { + Add(key); } + } - /*========================================================================================================================== - | METHOD: MARK AS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Marks a specific as clean or dirty based on the parameter. - /// - public void MarkAs(string key, bool markDirty) { - if (markDirty) { - MarkDirty(key); - } - else { - MarkClean(key); - } + /*============================================================================================================================ + | METHOD: MARK AS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Marks a specific as clean or dirty based on the parameter. + /// + public void MarkAs(string key, bool markDirty) { + if (markDirty) { + MarkDirty(key); + } + else { + MarkClean(key); } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/ITrackDirtyKeys.cs b/OnTopic/Collections/Specialized/ITrackDirtyKeys.cs index f9ca2a33..fe344e13 100644 --- a/OnTopic/Collections/Specialized/ITrackDirtyKeys.cs +++ b/OnTopic/Collections/Specialized/ITrackDirtyKeys.cs @@ -4,41 +4,40 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| INTERFACE: TRACK DIRTY KEYS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines an interface for tracking dirty keys. +/// +public interface ITrackDirtyKeys { /*============================================================================================================================ - | INTERFACE: TRACK DIRTY KEYS + | METHOD: IS DIRTY? \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines an interface for tracking dirty keys. + /// Determines whether the collection is dirty. /// - public interface ITrackDirtyKeys { - - /*========================================================================================================================== - | METHOD: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether the collection is dirty. - /// - bool IsDirty(); + bool IsDirty(); - /// - /// Determines whether the provided in the collection is dirty. - /// - bool IsDirty(string key); + /// + /// Determines whether the provided in the collection is dirty. + /// + bool IsDirty(string key); - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Marks the collection as clean. - /// - void MarkClean(); + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Marks the collection as clean. + /// + void MarkClean(); - /// - /// Marks the specified in the collection as clean. - /// - void MarkClean(string key); + /// + /// Marks the specified in the collection as clean. + /// + void MarkClean(string key); - } //Interface -} //Namespace \ No newline at end of file +} //Interface \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/KeyValuesPair{TKey,TValue}.cs b/OnTopic/Collections/Specialized/KeyValuesPair{TKey,TValue}.cs index f17924a1..45688d85 100644 --- a/OnTopic/Collections/Specialized/KeyValuesPair{TKey,TValue}.cs +++ b/OnTopic/Collections/Specialized/KeyValuesPair{TKey,TValue}.cs @@ -4,72 +4,71 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: KEY VALUES PAIR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a 1:n relationship used for implementations of as a means of +/// supporting a multimap. +/// +/// +/// Out of the box, the .NET CLR includes a similar class, which serves an +/// identical purpose. The class, however, provides more intuitive semantics for +/// working with multimap�i.e., 1:n�scenarios. +/// +/// +/// As an example, the supports the following: +/// +/// foreach (var relationship in topic.Relationships) { +/// foreach (var topic in relationship.Values) { +/// Console.Log(topic.Key); +/// } +/// } +/// +/// +public class KeyValuesPair where TValue: class, ICollection { /*============================================================================================================================ - | CLASS: KEY VALUES PAIR + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a 1:n relationship used for implementations of as a means of - /// supporting a multimap. + /// Constructs a new instance of a class with a and, + /// optionally, a . /// - /// - /// Out of the box, the .NET CLR includes a similar class, which serves an - /// identical purpose. The class, however, provides more intuitive semantics for - /// working with multimap—i.e., 1:n—scenarios. - /// - /// - /// As an example, the supports the following: - /// - /// foreach (var relationship in topic.Relationships) { - /// foreach (var topic in relationship.Values) { - /// Console.Log(topic.Key); - /// } - /// } - /// - /// - public class KeyValuesPair where TValue: class, ICollection { + /// The key for the given instance. + /// The optional set of values for the given instance. + public KeyValuesPair(TKey key, TValue values) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new instance of a class with a and, - /// optionally, a . - /// - /// The key for the given instance. - /// The optional set of values for the given instance. - public KeyValuesPair(TKey key, TValue values) { + Contract.Requires(key, nameof(key)); + Contract.Requires(values, nameof(values)); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(key, nameof(key)); - Contract.Requires(values, nameof(values)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Key = key; - Values = values; + /*-------------------------------------------------------------------------------------------------------------------------- + | Set properties + \-------------------------------------------------------------------------------------------------------------------------*/ + Key = key; + Values = values; - } + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the for a given item. - /// - public TKey Key { get; init; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the for a given item. + /// + public TKey Key { get; init; } - /*========================================================================================================================== - | PROPERTY: VALUES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the for the given item. - /// - public TValue Values { get; init; } + /*============================================================================================================================ + | PROPERTY: VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the for the given item. + /// + public TValue Values { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/ReadOnlyTopicMultiMap.cs b/OnTopic/Collections/Specialized/ReadOnlyTopicMultiMap.cs index fd219369..b040cf9b 100644 --- a/OnTopic/Collections/Specialized/ReadOnlyTopicMultiMap.cs +++ b/OnTopic/Collections/Specialized/ReadOnlyTopicMultiMap.cs @@ -6,154 +6,153 @@ using System.Collections; using System.Collections.ObjectModel; -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: READ-ONLY TOPIC MULTIMAP +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The provides a read-only façade to a . +/// +public class ReadOnlyTopicMultiMap: IEnumerable> { /*============================================================================================================================ - | CLASS: READ-ONLY TOPIC MULTIMAP + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The provides a read-only façade to a . + /// Constructs a new instance of a class with a reference to an underlying instance. /// - public class ReadOnlyTopicMultiMap: IEnumerable> { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new instance of a class with a reference to an underlying instance. - /// - public ReadOnlyTopicMultiMap(TopicMultiMap source) { - Contract.Requires(source, nameof(source)); - Source = source; - } + public ReadOnlyTopicMultiMap(TopicMultiMap source) { + Contract.Requires(source, nameof(source)); + Source = source; + } + + /*============================================================================================================================ + | PROPERTY: SOURCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides access to the underlying from which the will + /// derive values. + /// + /// + /// The must be passed in via either the public + /// constructor, or must be set manually from the constructor of a derived class when using the protected constructor. + /// + [NotNull, DisallowNull] + protected TopicMultiMap? Source { get; init; } + + /*============================================================================================================================ + | PROPERTY: KEYS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of keys available for the available collections. + /// + /// + /// Returns an enumerable list of keys. + /// + public ReadOnlyCollection Keys => new([.. Source.Select(m => m.Key)]); + + /*============================================================================================================================ + | PROPERTY: COUNT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a count of items in the source collection. + /// + /// + /// The number of collections in the underlying source collection. + /// + public int Count => Source.Count; + + /*============================================================================================================================ + | INDEXER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a collection from the source collection based on the . + /// + /// + /// A collection. + /// + public ReadOnlyTopicCollection this[string key] => new(Source[key].Values); + + /*============================================================================================================================ + | METHOD: CONTAINS? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public bool Contains(string key) => Source.Contains(key); + + /// + public bool Contains(string key, Topic topic) => Source.Contains(key, topic); - /*========================================================================================================================== - | PROPERTY: SOURCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides access to the underlying from which the will - /// derive values. - /// - /// - /// The must be passed in via either the public - /// constructor, or must be set manually from the constructor of a derived class when using the protected constructor. - /// - [NotNull, DisallowNull] - protected TopicMultiMap? Source { get; init; } - - /*========================================================================================================================== - | PROPERTY: KEYS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of keys available for the available collections. - /// - /// - /// Returns an enumerable list of keys. - /// - public ReadOnlyCollection Keys => new(Source.Select(m => m.Key).ToList()); - - /*========================================================================================================================== - | PROPERTY: COUNT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a count of items in the source collection. - /// - /// - /// The number of collections in the underlying source collection. - /// - public int Count => Source.Count; - - /*========================================================================================================================== - | INDEXER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a collection from the source collection based on the . - /// - /// - /// A collection. - /// - public ReadOnlyTopicCollection this[string key] => new(Source[key].Values); - - /*========================================================================================================================== - | METHOD: CONTAINS? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public bool Contains(string key) => Source.Contains(key); - - /// - public bool Contains(string key, Topic topic) => Source.Contains(key, topic); - - /*========================================================================================================================== - | METHOD: GET VALUES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of objects grouped by a specific . - /// - /// - /// Returns a reference to the underlying collection. - /// - /// The key of the collection to be returned. - public ReadOnlyTopicCollection GetValues(string key) { - Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); - if (Contains(key)) { - return new(Source[key].Values); - } - return new(new List()); + /*============================================================================================================================ + | METHOD: GET VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of objects grouped by a specific . + /// + /// + /// Returns a reference to the underlying collection. + /// + /// The key of the collection to be returned. + public ReadOnlyTopicCollection GetValues(string key) { + Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); + if (Contains(key)) { + return new(Source[key].Values); } + return new(new List()); + } + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(GetTopics)} method has been renamed to {nameof(GetValues)}.", true)] + public ReadOnlyTopicCollection GetTopics(string key) => GetValues(key); - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(GetTopics)} method has been renamed to {nameof(GetValues)}.", true)] - public ReadOnlyTopicCollection GetTopics(string key) => GetValues(key); - - /*========================================================================================================================== - | METHOD: GET ALL VALUES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of all related objects, independent of collection key. - /// - /// - /// Returns an enumerable list of objects. - /// - public ReadOnlyTopicCollection GetAllValues() => - new(Source.SelectMany(list => list.Values).Distinct().ToList()); - - /// - /// Retrieves a list of all related objects, independent of key, filtered by content - /// type. - /// - /// - /// Returns an enumerable list of objects. - /// - public ReadOnlyTopicCollection GetAllValues(string contentType) => - new(GetAllValues().Where(t => t.ContentType == contentType).ToList()); - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(GetAllTopics)} method has been renamed to {nameof(GetAllValues)}.", true)] - public ReadOnlyTopicCollection GetAllTopics(string key) => GetAllValues(key); - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(GetAllTopics)} method has been renamed to {nameof(GetAllValues)}.", true)] - public ReadOnlyTopicCollection GetAllTopics() => GetAllValues(); - - /*========================================================================================================================== - | GET ENUMERATOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public IEnumerator> GetEnumerator() { - foreach (var collection in Source) { - yield return new(collection.Key, new(collection.Values)); - } + /*============================================================================================================================ + | METHOD: GET ALL VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of all related objects, independent of collection key. + /// + /// + /// Returns an enumerable list of objects. + /// + public ReadOnlyTopicCollection GetAllValues() => + new([.. Source.SelectMany(list => list.Values).Distinct()]); + + /// + /// Retrieves a list of all related objects, independent of key, filtered by content + /// type. + /// + /// + /// Returns an enumerable list of objects. + /// + public ReadOnlyTopicCollection GetAllValues(string contentType) => + new([.. GetAllValues().Where(t => t.ContentType == contentType)]); + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(GetAllTopics)} method has been renamed to {nameof(GetAllValues)}.", true)] + public ReadOnlyTopicCollection GetAllTopics(string key) => GetAllValues(key); + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(GetAllTopics)} method has been renamed to {nameof(GetAllValues)}.", true)] + public ReadOnlyTopicCollection GetAllTopics() => GetAllValues(); + + /*============================================================================================================================ + | GET ENUMERATOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public IEnumerator> GetEnumerator() { + foreach (var collection in Source) { + yield return new(collection.Key, new(collection.Values)); } + } - /// - [ExcludeFromCodeCoverage] - IEnumerator IEnumerable.GetEnumerator() => Source.GetEnumerator(); + /// + [ExcludeFromCodeCoverage] + IEnumerator IEnumerable.GetEnumerator() => Source.GetEnumerator(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/TopicIndex.cs b/OnTopic/Collections/Specialized/TopicIndex.cs index 67dbfbe6..85cb6ee7 100644 --- a/OnTopic/Collections/Specialized/TopicIndex.cs +++ b/OnTopic/Collections/Specialized/TopicIndex.cs @@ -4,30 +4,29 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: TOPIC INDEX +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects indexed by . +/// +public class TopicIndex : Dictionary { /*============================================================================================================================ - | CLASS: TOPIC INDEX + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects indexed by . + /// Initializes a new instance of the . /// - public class TopicIndex : Dictionary { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - /// Seeds the collection with an optional list of topic references. - public TopicIndex(IEnumerable? topics = null) : base() { - if (topics is not null) { - foreach(var topic in topics) { - Add(topic.Id, topic); - } + /// Seeds the collection with an optional list of topic references. + public TopicIndex(IEnumerable? topics = null) : base() { + if (topics is not null) { + foreach(var topic in topics) { + Add(topic.Id, topic); } } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/TopicMultiMap.cs b/OnTopic/Collections/Specialized/TopicMultiMap.cs index 18cf2b76..c81024cd 100644 --- a/OnTopic/Collections/Specialized/TopicMultiMap.cs +++ b/OnTopic/Collections/Specialized/TopicMultiMap.cs @@ -5,156 +5,155 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: TOPIC MULTIMAP +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The offers support for a keyed collection where each key is mapped to a collection of instances, thus supporting a 1:n relationship with zero or more topics, organized by key. +/// +public class TopicMultiMap: KeyedCollection> { /*============================================================================================================================ - | CLASS: TOPIC MULTIMAP + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The offers support for a keyed collection where each key is mapped to a collection of instances, thus supporting a 1:n relationship with zero or more topics, organized by key. + /// Constructs a new instance of a class. /// - public class TopicMultiMap: KeyedCollection> { + public TopicMultiMap(): base(StringComparer.OrdinalIgnoreCase) { - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new instance of a class. - /// - public TopicMultiMap(): base(StringComparer.OrdinalIgnoreCase) { + } + + /*============================================================================================================================ + | METHOD: CONTAINS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if the exists in a collection with the supplied . + /// + /// + /// Returns true if the exists in the specified collection. Returns false if the + /// collection doesn't exist. + /// + public bool Contains(string key, Topic topic) => Contains(key) && this[key].Values.Contains(topic); + /*============================================================================================================================ + | METHOD: GET VALUES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of objects grouped by a specific . + /// + /// + /// Returns a reference to the underlying collection. + /// + /// The key of the collection to be returned. + public TopicCollection GetValues(string key) { + Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); + if (Contains(key)) { + return this[key].Values; } + return new(); + } + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(GetTopics)} method has been renamed to {nameof(GetValues)}.", true)] + public TopicCollection GetTopics(string key) => GetValues(key); + + /*============================================================================================================================ + | METHOD: ADD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a to a collection with the supplied . If the collection with + /// doesn't exist, it will be established. + /// + public void Add(string key, Topic topic) { - /*========================================================================================================================== - | METHOD: CONTAINS + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if the exists in a collection with the supplied . - /// - /// - /// Returns true if the exists in the specified collection. Returns false if the - /// collection doesn't exist. - /// - public bool Contains(string key, Topic topic) => Contains(key) && this[key].Values.Contains(topic); - - /*========================================================================================================================== - | METHOD: GET VALUES + Contract.Requires(key, nameof(key)); + Contract.Requires(topic, nameof(topic)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure collection is established \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of objects grouped by a specific . - /// - /// - /// Returns a reference to the underlying collection. - /// - /// The key of the collection to be returned. - public TopicCollection GetValues(string key) { - Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); - if (Contains(key)) { - return this[key].Values; - } - return new(); + if (!Contains(key)) { + Add(new(key, new())); } - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(GetTopics)} method has been renamed to {nameof(GetValues)}.", true)] - public TopicCollection GetTopics(string key) => GetValues(key); - - /*========================================================================================================================== - | METHOD: ADD + /*-------------------------------------------------------------------------------------------------------------------------- + | Add topic, if it hasn't already been added \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a to a collection with the supplied . If the collection with - /// doesn't exist, it will be established. - /// - public void Add(string key, Topic topic) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(key, nameof(key)); - Contract.Requires(topic, nameof(topic)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure collection is established - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!Contains(key)) { - Add(new(key, new())); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Add topic, if it hasn't already been added - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!Contains(key, topic)) { - this[key].Values.Add(topic); - } - + if (!Contains(key, topic)) { + this[key].Values.Add(topic); } - /*========================================================================================================================== - | METHOD: REMOVE + } + + /*============================================================================================================================ + | METHOD: REMOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes a from a collection with the supplied . + /// + /// The key of the collection. + /// The to be removed. + /// + /// Returns true if the is removed; returns false if either the + /// or the cannot be found. + /// + public bool Remove(string key, Topic topic) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); + Contract.Requires(topic, nameof(topic)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate key \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes a from a collection with the supplied . - /// - /// The key of the collection. - /// The to be removed. - /// - /// Returns true if the is removed; returns false if either the - /// or the cannot be found. - /// - public bool Remove(string key, Topic topic) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); - Contract.Requires(topic, nameof(topic)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate key - \-----------------------------------------------------------------------------------------------------------------------*/ - var topics = GetValues(key); - - if (topics is null || !topics.Contains(topic)) { - return false; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Remove topic - \-----------------------------------------------------------------------------------------------------------------------*/ - topics.Remove(topic); - - /*------------------------------------------------------------------------------------------------------------------------ - | Remove true - \-----------------------------------------------------------------------------------------------------------------------*/ - return true; + var topics = GetValues(key); + if (topics is null || !topics.Contains(topic)) { + return false; } - /*========================================================================================================================== - | METHOD: CLEAR + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes all objects grouped by a specific . - /// - /// The key of the collection to be cleared. - public void Clear(string key) => GetValues(key).Clear(); - - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM + topics.Remove(topic); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove true \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Method must be overridden for the to extract the keys from the items. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - [ExcludeFromCodeCoverage] - protected override sealed string GetKeyForItem(KeyValuesPair item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Key; - } + return true; - } //Class -} //Namespace \ No newline at end of file + } + + /*============================================================================================================================ + | METHOD: CLEAR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes all objects grouped by a specific . + /// + /// The key of the collection to be cleared. + public void Clear(string key) => GetValues(key).Clear(); + + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Method must be overridden for the to extract the keys from the items. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + [ExcludeFromCodeCoverage] + protected override sealed string GetKeyForItem(KeyValuesPair item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Key; + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/TrackedRecordCollection{TItem,TValue,TAttribute}.cs b/OnTopic/Collections/Specialized/TrackedRecordCollection{TItem,TValue,TAttribute}.cs index f952e5ba..0ab54374 100644 --- a/OnTopic/Collections/Specialized/TrackedRecordCollection{TItem,TValue,TAttribute}.cs +++ b/OnTopic/Collections/Specialized/TrackedRecordCollection{TItem,TValue,TAttribute}.cs @@ -7,667 +7,666 @@ using OnTopic.Internal.Reflection; using OnTopic.Repositories; -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: TRACKED RECORD COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of records, along with methods "updating" those records and +/// working with their state. +/// +/// +/// records represent individual instances of values associated with a particular . The class tracks these through e.g. its property. The class provides a base class with methods for working with +/// these records, such as , for determining if a given record has been modified, or for creating or "updating" a record. (Records are +/// immutable, so updates actually involve cloning the record with updated values.) +/// +public abstract class TrackedRecordCollection : + KeyedCollection, ITrackDirtyKeys + where TItem: TrackedRecord, new() + where TAttribute: Attribute + where TValue : class +{ + + /*============================================================================================================================ + | DISPATCHER + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly TopicPropertyDispatcher _topicPropertyDispatcher; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the class. + /// + /// A reference to the topic that the current collection is bound to. + internal TrackedRecordCollection(Topic parentTopic) : base(StringComparer.OrdinalIgnoreCase) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set properties + \-------------------------------------------------------------------------------------------------------------------------*/ + AssociatedTopic = parentTopic; + _topicPropertyDispatcher = new(parentTopic); + + } /*============================================================================================================================ - | CLASS: TRACKED RECORD COLLECTION + | ASSOCIATED TOPIC \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of records, along with methods "updating" those records and - /// working with their state. + /// The that the current collection is associated with. /// /// - /// records represent individual instances of values associated with a particular . The class tracks these through e.g. its property. The class provides a base class with methods for working with - /// these records, such as , for determining if a given record has been modified, or for creating or "updating" a record. (Records are - /// immutable, so updates actually involve cloning the record with updated values.) + /// This is used for operations that require inheritance or pass-through of properies in order to e.g. + /// enforce business logic. /// - public abstract class TrackedRecordCollection : - KeyedCollection, ITrackDirtyKeys - where TItem: TrackedRecord, new() - where TAttribute: Attribute - where TValue : class - { - - /*========================================================================================================================== - | DISPATCHER - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly TopicPropertyDispatcher _topicPropertyDispatcher; + protected Topic AssociatedTopic { get; init; } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// A reference to the topic that the current collection is bound to. - internal TrackedRecordCollection(Topic parentTopic) : base(StringComparer.OrdinalIgnoreCase) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Set properties - \-----------------------------------------------------------------------------------------------------------------------*/ - AssociatedTopic = parentTopic; - _topicPropertyDispatcher = new(parentTopic); + /*============================================================================================================================ + | PROPERTY: DELETED ITEMS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// When a is deleted, keep track of it so that it can be marked for deletion when the is saved. + /// + /// + /// As a performance enhancement, implementations will only save topics that are marked as + /// . If a is deleted, then it won't be marked as . If no other instances were modified, then the won't get saved, and that won't be deleted. Further more, methods like + /// the method have no way of detecting the deletion of + /// arbitrary values�i.e., attributes that were deleted which don't correspond to attributes configured on the . By tracking any deleted instances, we ensure both + /// scenarios can be accounted for. + /// + internal List DeletedItems { get; } = new(); - } + /*============================================================================================================================ + | METHOD: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ - /*========================================================================================================================== - | ASSOCIATED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The that the current collection is associated with. - /// - /// - /// This is used for operations that require inheritance or pass-through of properies in order to e.g. - /// enforce business logic. - /// - protected Topic AssociatedTopic { get; init; } - - /*========================================================================================================================== - | PROPERTY: DELETED ITEMS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// When a is deleted, keep track of it so that it can be marked for deletion when the is saved. - /// - /// - /// As a performance enhancement, implementations will only save topics that are marked as - /// . If a is deleted, then it won't be marked as . If no other instances were modified, then the won't get saved, and that won't be deleted. Further more, methods like - /// the method have no way of detecting the deletion of - /// arbitrary values—i.e., attributes that were deleted which don't correspond to attributes configured on the . By tracking any deleted instances, we ensure both - /// scenarios can be accounted for. - /// - internal List DeletedItems { get; } = new(); - - /*========================================================================================================================== - | METHOD: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ + /// + public virtual bool IsDirty() => DeletedItems.Count > 0 || Items.Any(a => a.IsDirty); - /// - public virtual bool IsDirty() => DeletedItems.Count > 0 || Items.Any(a => a.IsDirty); - - /// - /// Determine if a given is marked as . Will return - /// false if the cannot be found in the collection. - /// - /// - /// This method is intended primarily for data storage providers, such as , which may need - /// to determine the state of a prior to saving it - /// to the data storage medium. Because is a state of the current , it does not support inheritFromParent or inheritFromBase (which otherwise default - /// to true). - /// - /// The string identifier for the . - /// - /// Returns true if the is marked as ; - /// otherwise false. - /// - public bool IsDirty(string key) { - if (!Contains(key)) { - return false; - } - return this[key].IsDirty; + /// + /// Determine if a given is marked as . Will return + /// false if the cannot be found in the collection. + /// + /// + /// This method is intended primarily for data storage providers, such as , which may need + /// to determine the state of a prior to saving it + /// to the data storage medium. Because is a state of the current , it does not support inheritFromParent or inheritFromBase (which otherwise default + /// to true). + /// + /// The string identifier for the . + /// + /// Returns true if the is marked as ; + /// otherwise false. + /// + public bool IsDirty(string key) { + if (!Contains(key)) { + return false; } + return this[key].IsDirty; + } - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ - /// - public void MarkClean() => MarkClean((DateTime?)null); - - /// - /// Marks the collection—including all instances—as clean, meaning they have been persisted - /// to the underlying . - /// - /// - /// This method is intended primarily for data storage providers, such as , so that they can - /// mark the collection, and all instances it contains, as clean. After this, method will return false until any instances are added, modified, - /// or removed. - /// - /// - /// The value that the was last saved. This corresponds to the . - /// - public void MarkClean(DateTime? version) { - if (AssociatedTopic.IsNew) { - return; - } - foreach (var trackedRecord in Items.Where(a => a.IsDirty).ToArray()) { - if (AllowClean(trackedRecord)) { - SetValue(trackedRecord.Key, trackedRecord.Value, false, false, version?? DateTime.UtcNow); - } - } - DeletedItems.Clear(); - } + /// + public void MarkClean() => MarkClean((DateTime?)null); - /// - public void MarkClean(string key) => MarkClean(key, null); - - /// - /// Marks an individual as clean. - /// - /// - /// This method is intended primarily for data storage providers, such as , so that they can - /// mark an as clean. After this, will return false - /// for that item until it is modified. - /// - /// The string identifier for the . - /// - /// The value that the was last saved. This corresponds to the . - /// - public void MarkClean(string key, DateTime? version) { - if (AssociatedTopic.IsNew) { - return; - } - else if (Contains(key)) { - var trackedRecord = this[key]; - if (trackedRecord.IsDirty && AllowClean(trackedRecord)) { - SetValue(trackedRecord.Key, trackedRecord.Value, false, false, version?? DateTime.UtcNow); - } + /// + /// Marks the collection�including all instances�as clean, meaning they have been persisted + /// to the underlying . + /// + /// + /// This method is intended primarily for data storage providers, such as , so that they can + /// mark the collection, and all instances it contains, as clean. After this, method will return false until any instances are added, modified, + /// or removed. + /// + /// + /// The value that the was last saved. This corresponds to the . + /// + public void MarkClean(DateTime? version) { + if (AssociatedTopic.IsNew) { + return; + } + foreach (var trackedRecord in Items.Where(a => a.IsDirty).ToArray()) { + if (AllowClean(trackedRecord)) { + SetValue(trackedRecord.Key, trackedRecord.Value, false, false, version?? DateTime.UtcNow); } } + DeletedItems.Clear(); + } - /*========================================================================================================================== - | METHOD: GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ + /// + public void MarkClean(string key) => MarkClean(key, null); - /// - /// Gets a from the collection based on the . - /// - /// The string identifier for the . - /// - /// Boolean indicator nothing whether to recusrively search through s in order to get the value. - /// - /// The for the . - public TValue? GetValue(string key, bool inheritFromParent = false) => GetValue(key, null, inheritFromParent); - - /// - /// Gets a from the collection based on the with a - /// specified , an optional setting to enable , and an - /// optional setting for . - /// - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to recusrively search through s in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's topics in - /// order to get the value. - /// - /// The for the . - [return: NotNullIfNotNull(nameof(defaultValue))] - public TValue? GetValue(string key, TValue? defaultValue, bool inheritFromParent = false, bool inheritFromBase = true) { - Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); - return GetValue(key, defaultValue, inheritFromParent, inheritFromBase ? 5 : 0); + /// + /// Marks an individual as clean. + /// + /// + /// This method is intended primarily for data storage providers, such as , so that they can + /// mark an as clean. After this, will return false + /// for that item until it is modified. + /// + /// The string identifier for the . + /// + /// The value that the was last saved. This corresponds to the . + /// + public void MarkClean(string key, DateTime? version) { + if (AssociatedTopic.IsNew) { + return; } - - /// - /// Gets a from the collection based on the with a - /// specified paramref name="defaultValue"/> and an optional number of s through whom to - /// crawl to retrieve an inherited value. - /// - /// The string identifier for the . - /// - /// A to which to fall back in the case the value is not found. - /// - /// - /// Boolean indicator nothing whether to recusrively search through s in order to get the value. - /// - /// The number of recursions to perform when attempting to get the value. - /// The value for the . - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !key.Contains(" ") - /// - /// - /// maxHops >= 0 - /// - /// - /// maxHops <= 100 - /// - [return: NotNullIfNotNull(nameof(defaultValue))] - internal virtual TValue? GetValue(string key, TValue? defaultValue, bool inheritFromParent, int maxHops) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicFactory.ValidateKey(key, true); - Contract.Requires(maxHops >= 0, "The maximum number of hops should be a positive number."); - Contract.Requires(maxHops <= 100, "The maximum number of hops should not exceed 100."); - - TValue? value = null; - - /*------------------------------------------------------------------------------------------------------------------------ - | Look up value from collection - \-----------------------------------------------------------------------------------------------------------------------*/ - if (Contains(key)) { - value = this[key].Value; + else if (Contains(key)) { + var trackedRecord = this[key]; + if (trackedRecord.IsDirty && AllowClean(trackedRecord)) { + SetValue(trackedRecord.Key, trackedRecord.Value, false, false, version?? DateTime.UtcNow); } + } + } - if (value is "") { - value = null; - } + /*============================================================================================================================ + | METHOD: GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ - /*------------------------------------------------------------------------------------------------------------------------ - | Look up value from topic pointer - \-----------------------------------------------------------------------------------------------------------------------*/ - if ( - value is null && - maxHops > 0 && - BaseCollection is not null - ) { - value = BaseCollection.GetValue(key, null, false, maxHops - 1); - } + /// + /// Gets a from the collection based on the . + /// + /// The string identifier for the . + /// + /// Boolean indicator nothing whether to recusrively search through s in order to get the value. + /// + /// The for the . + public TValue? GetValue(string key, bool inheritFromParent = false) => GetValue(key, null, inheritFromParent); - /*------------------------------------------------------------------------------------------------------------------------ - | Look up value from parent - \-----------------------------------------------------------------------------------------------------------------------*/ - if ( - value is null && - inheritFromParent && - ParentCollection is not null - ) { - value = ParentCollection.GetValue(key, defaultValue, inheritFromParent); - } + /// + /// Gets a from the collection based on the with a + /// specified , an optional setting to enable , and an + /// optional setting for . + /// + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to recusrively search through s in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's topics in + /// order to get the value. + /// + /// The for the . + [return: NotNullIfNotNull(nameof(defaultValue))] + public TValue? GetValue(string key, TValue? defaultValue, bool inheritFromParent = false, bool inheritFromBase = true) { + Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); + return GetValue(key, defaultValue, inheritFromParent, inheritFromBase ? 5 : 0); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return value, if found - \-----------------------------------------------------------------------------------------------------------------------*/ - if (value is not null) { - return value; - } + /// + /// Gets a from the collection based on the with a + /// specified paramref name="defaultValue"/> and an optional number of s through whom to + /// crawl to retrieve an inherited value. + /// + /// The string identifier for the . + /// + /// A to which to fall back in the case the value is not found. + /// + /// + /// Boolean indicator nothing whether to recusrively search through s in order to get the value. + /// + /// The number of recursions to perform when attempting to get the value. + /// The value for the . + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !key.Contains(" ") + /// + /// + /// maxHops >= 0 + /// + /// + /// maxHops <= 100 + /// + [return: NotNullIfNotNull(nameof(defaultValue))] + internal virtual TValue? GetValue(string key, TValue? defaultValue, bool inheritFromParent, int maxHops) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + TopicFactory.ValidateKey(key, true); + Contract.Requires(maxHops >= 0, "The maximum number of hops should be a positive number."); + Contract.Requires(maxHops <= 100, "The maximum number of hops should not exceed 100."); - /*------------------------------------------------------------------------------------------------------------------------ - | Finally, return default - \-----------------------------------------------------------------------------------------------------------------------*/ - return defaultValue; + TValue? value = null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Look up value from collection + \-------------------------------------------------------------------------------------------------------------------------*/ + if (Contains(key)) { + value = this[key].Value; } - /*========================================================================================================================== - | METHOD: PARENT COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the corresponding on the , if available. - /// - protected abstract TrackedRecordCollection? ParentCollection { get; } - - /*========================================================================================================================== - | METHOD: BASE COLLECTION + if (value is "") { + value = null; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Look up value from topic pointer \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the corresponding on the , if available. - /// - protected abstract TrackedRecordCollection? BaseCollection { get; } - - /*========================================================================================================================== - | METHOD: SET VALUE + if ( + value is null && + maxHops > 0 && + BaseCollection is not null + ) { + value = BaseCollection.GetValue(key, null, false, maxHops - 1); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Look up value from parent \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// - /// Working with records can be a bit cumbersome, and especially in determining if a value should be marked as , since that's based on a comparison with the previous value. The method handles this logic for implementers, while simultaneously allowing - /// callers to explicitly set whether the instances should be marked as dirty—via the - /// parameter—and, optionally, what the should be. - /// - /// The string identifier for the . - /// The text value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// The value that the was last modified. This is intended - /// exclusively for use when populating the topic graph from a persistent data store as a means of indicating the current - /// version for each . This is used when e.g. importing values to determine if the existing - /// value is newer than the source value. - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !value.Contains(" ") - /// - public virtual void SetValue( - string key, - TValue? value, - bool? markDirty = null, - DateTime? version = null - ) - => SetValue(key, value, markDirty, true, version); - - /// - /// Internal helper method that either adds a new object or updates the value of an - /// existing one, depending on whether that value already exists. - /// - /// - /// When the parameter is called, no attempt will be made to route the call - /// through the corresponding properties, if available. As such, this is intended specifically to be called by internal - /// properties as a means of avoiding the property being called again when a caller uses the property's setter directly. - /// - /// The string identifier for the . - /// The text value for the . - /// - /// Instructs the underlying code to call corresponding properties, if available, to ensure business logic is enforced. - /// This should be set to false if setting items from internal properties in order to avoid an infinite loop. - /// - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as true if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// The value that the attribute was last modified. This is intended exclusively for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !value.Contains(" ") - /// - internal void SetValue( - string key, - TValue? value, - bool? markDirty, - bool enforceBusinessLogic, - DateTime? version = null + if ( + value is null && + inheritFromParent && + ParentCollection is not null ) { + value = ParentCollection.GetValue(key, defaultValue, inheritFromParent); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicFactory.ValidateKey(key, true); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value, if found + \-------------------------------------------------------------------------------------------------------------------------*/ + if (value is not null) { + return value; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve original item - \-----------------------------------------------------------------------------------------------------------------------*/ - TItem? originalItem = null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Finally, return default + \-------------------------------------------------------------------------------------------------------------------------*/ + return defaultValue; - if (Contains(key)) { - originalItem = this[key]; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Update from business logic - >------------------------------------------------------------------------------------------------------------------------- - | If the original values have already been applied, and SetValue() is being triggered a second time after enforcing - | business logic, then use the original values, while applying any change in the value triggered by the business logic. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (_topicPropertyDispatcher.IsRegistered(key, out var updatedItem)) { - if (updatedItem.Value != value) { - updatedItem = updatedItem with { - Value = value - }; - } - } + /*============================================================================================================================ + | METHOD: PARENT COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the corresponding on the , if available. + /// + protected abstract TrackedRecordCollection? ParentCollection { get; } - /*------------------------------------------------------------------------------------------------------------------------ - | Update existing item - >------------------------------------------------------------------------------------------------------------------------- - | Because TrackedRecord is immutable, a new instance must be constructed to replace the previous version. - \-----------------------------------------------------------------------------------------------------------------------*/ - else if (originalItem is not null) { - var markAsDirty = originalItem.IsDirty; - if (AssociatedTopic.IsNew) { - markAsDirty = true; - } - else if (markDirty.HasValue) { - markAsDirty = markDirty.Value; - } - else if (!originalItem.Value?.Equals(value)?? false) { - markAsDirty = true; - } - else if (!version.HasValue) { - return; - } - updatedItem = originalItem with { - Value = value, - IsDirty = markAsDirty, - LastModified = version?? originalItem.LastModified - }; - } + /*============================================================================================================================ + | METHOD: BASE COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the corresponding on the , if available. + /// + protected abstract TrackedRecordCollection? BaseCollection { get; } - /*------------------------------------------------------------------------------------------------------------------------ - | Ignore if null - >------------------------------------------------------------------------------------------------------------------------- - | ###NOTE JJC20200501: Null or empty values are treated as deletions, and are not persisted to the data store. With - | existing values, these are written to DeletedItems to ensure the collection is marked as IsDirty, thus allowing previous - | values to be overwritten. Non-existent values should simply be ignored, however; we shouldn't delete what doesn't exist. - \-----------------------------------------------------------------------------------------------------------------------*/ - else if (value is null || String.IsNullOrEmpty(value.ToString())) { - return; - } + /*============================================================================================================================ + | METHOD: SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// + /// Working with records can be a bit cumbersome, and especially in determining if a value should be marked as , since that's based on a comparison with the previous value. The method handles this logic for implementers, while simultaneously allowing + /// callers to explicitly set whether the instances should be marked as dirty�via the + /// parameter�and, optionally, what the should be. + /// + /// The string identifier for the . + /// The text value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// The value that the was last modified. This is intended + /// exclusively for use when populating the topic graph from a persistent data store as a means of indicating the current + /// version for each . This is used when e.g. importing values to determine if the existing + /// value is newer than the source value. + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !value.Contains(" ") + /// + public virtual void SetValue( + string key, + TValue? value, + bool? markDirty = null, + DateTime? version = null + ) + => SetValue(key, value, markDirty, true, version); - /*------------------------------------------------------------------------------------------------------------------------ - | Create new item - \-----------------------------------------------------------------------------------------------------------------------*/ - else { - updatedItem = new TItem() { - Key = key, - Value = value, - IsDirty = AssociatedTopic.IsNew || (markDirty ?? true), - LastModified = version?? DateTime.UtcNow + /// + /// Internal helper method that either adds a new object or updates the value of an + /// existing one, depending on whether that value already exists. + /// + /// + /// When the parameter is called, no attempt will be made to route the call + /// through the corresponding properties, if available. As such, this is intended specifically to be called by internal + /// properties as a means of avoiding the property being called again when a caller uses the property's setter directly. + /// + /// The string identifier for the . + /// The text value for the . + /// + /// Instructs the underlying code to call corresponding properties, if available, to ensure business logic is enforced. + /// This should be set to false if setting items from internal properties in order to avoid an infinite loop. + /// + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as true if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// The value that the attribute was last modified. This is intended exclusively for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !value.Contains(" ") + /// + internal void SetValue( + string key, + TValue? value, + bool? markDirty, + bool enforceBusinessLogic, + DateTime? version = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + TopicFactory.ValidateKey(key, true); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve original item + \-------------------------------------------------------------------------------------------------------------------------*/ + TItem? originalItem = null; + + if (Contains(key)) { + originalItem = this[key]; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Update from business logic + >------------------------------------------------------------------------------------------------------------------------- + | If the original values have already been applied, and SetValue() is being triggered a second time after enforcing + | business logic, then use the original values, while applying any change in the value triggered by the business logic. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (_topicPropertyDispatcher.IsRegistered(key, out var updatedItem)) { + if (updatedItem.Value != value) { + updatedItem = updatedItem with { + Value = value }; } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Register that business logic has already been enforced - >------------------------------------------------------------------------------------------------------------------------- - | We want to ensure that any attempt to set references that have corresponding (writable) properties use those properties, - | thus enforcing business logic. In order to ensure this is enforced on all entry points exposed by ICollection, and not - | just SetValue, the underlying interceptors (e.g., InsertItem, SetItem) call the Enforce() method. If it returns false, - | they assume the property set the value (e.g., by calling the internal SetValue method with enforceBusinessLogic set to - | false). Otherwise, the corresponding property will be called. The Register() method thus avoids a redirect loop in this - | scenario. This, of course, assumes that properties are correctly written to call the enforceBusinessLogic parameter. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!enforceBusinessLogic) { - _topicPropertyDispatcher.Register(key, updatedItem); + /*-------------------------------------------------------------------------------------------------------------------------- + | Update existing item + >------------------------------------------------------------------------------------------------------------------------- + | Because TrackedRecord is immutable, a new instance must be constructed to replace the previous version. + \-------------------------------------------------------------------------------------------------------------------------*/ + else if (originalItem is not null) { + var markAsDirty = originalItem.IsDirty; + if (AssociatedTopic.IsNew) { + markAsDirty = true; } - - /*------------------------------------------------------------------------------------------------------------------------ - | Persist item to collection - \-----------------------------------------------------------------------------------------------------------------------*/ - if (updatedItem.Value is null) { - Remove(key); + else if (markDirty.HasValue) { + markAsDirty = markDirty.Value; } - else if (originalItem is not null) { - this[IndexOf(originalItem)] = updatedItem; + else if (!originalItem.Value?.Equals(value)?? false) { + markAsDirty = true; } - else { - Add(updatedItem); + else if (!version.HasValue) { + return; } + updatedItem = originalItem with { + Value = value, + IsDirty = markAsDirty, + LastModified = version?? originalItem.LastModified + }; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Ignore if null + >------------------------------------------------------------------------------------------------------------------------- + | ###NOTE JJC20200501: Null or empty values are treated as deletions, and are not persisted to the data store. With + | existing values, these are written to DeletedItems to ensure the collection is marked as IsDirty, thus allowing previous + | values to be overwritten. Non-existent values should simply be ignored, however; we shouldn't delete what doesn't exist. + \-------------------------------------------------------------------------------------------------------------------------*/ + else if (value is null || String.IsNullOrEmpty(value.ToString())) { + return; } - /*========================================================================================================================== - | OVERRIDE: INSERT ITEM + /*-------------------------------------------------------------------------------------------------------------------------- + | Create new item \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to insert a new into the collection, to ensure that local - /// business logic is enforced. - /// - /// - /// - /// If a settable property is available corresponding to the , the call should be - /// routed through that to ensure local business logic is enforced, if it hasn't already been enforced. - /// - /// - /// Compared to the base implementation, will throw a specific error if a duplicate key - /// is inserted. This conveniently provides the name of the so it's clear what key is - /// being duplicated. - /// - /// - /// The location that the should be set. - /// The object which is being inserted. - /// - /// An is thrown if an with the same as the already exists. - /// - protected override void InsertItem(int index, TItem item) { - Contract.Requires(item, nameof(item)); - if (!AllowClean(item)) { - item = item with { - IsDirty = true - }; - } - if (_topicPropertyDispatcher.Enforce(item.Key, item)) { - if (!Contains(item.Key)) { - base.InsertItem(index, item); - if (DeletedItems.Contains(item.Key)) { - DeletedItems.Remove(item.Key); - } - } - else { - throw new ArgumentException( - $"An {nameof(TItem)} with the Key '{item.Key}' already exists. The Value of the existing item is " + - $"{this[item.Key].Value}; the new item's Value is '{item.Value}'. These {nameof(TItem)}s are associated " + - $"with the {nameof(Topic)} '{AssociatedTopic.GetUniqueKey()}'.", - nameof(item) - ); - } - } + else { + updatedItem = new TItem() { + Key = key, + Value = value, + IsDirty = AssociatedTopic.IsNew || (markDirty ?? true), + LastModified = version?? DateTime.UtcNow + }; } - /*========================================================================================================================== - | OVERRIDE: SET ITEM + /*-------------------------------------------------------------------------------------------------------------------------- + | Register that business logic has already been enforced + >------------------------------------------------------------------------------------------------------------------------- + | We want to ensure that any attempt to set references that have corresponding (writable) properties use those properties, + | thus enforcing business logic. In order to ensure this is enforced on all entry points exposed by ICollection, and not + | just SetValue, the underlying interceptors (e.g., InsertItem, SetItem) call the Enforce() method. If it returns false, + | they assume the property set the value (e.g., by calling the internal SetValue method with enforceBusinessLogic set to + | false). Otherwise, the corresponding property will be called. The Register() method thus avoids a redirect loop in this + | scenario. This, of course, assumes that properties are correctly written to call the enforceBusinessLogic parameter. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to update an in the collection, to ensure that local business - /// logic is enforced. - /// - /// - /// If a settable property is available corresponding to the , the call should be routed - /// through that to ensure local business logic is enforced, if it hasn't already been enforced. - /// - /// The location that the should be set. - /// The object which is being inserted. - protected override void SetItem(int index, TItem item) { - Contract.Requires(item, nameof(item)); - if (!AllowClean(item)) { - item = item with { - IsDirty = true - }; - } - if (_topicPropertyDispatcher.Enforce(item.Key, item)) { - base.SetItem(index, item); - } + if (!enforceBusinessLogic) { + _topicPropertyDispatcher.Register(key, updatedItem); } - /*========================================================================================================================== - | OVERRIDE: REMOVE ITEM + /*-------------------------------------------------------------------------------------------------------------------------- + | Persist item to collection \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to remove an from the collection, to ensure that it is - /// appropriately marked as . - /// - /// - /// When an is removed, will return true—even if no remaining s are marked as . - /// - protected override void RemoveItem(int index) { - var trackedRecord = this[index] with { - Value = null + if (updatedItem.Value is null) { + Remove(key); + } + else if (originalItem is not null) { + this[IndexOf(originalItem)] = updatedItem; + } + else { + Add(updatedItem); + } + + } + + /*============================================================================================================================ + | OVERRIDE: INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to insert a new into the collection, to ensure that local + /// business logic is enforced. + /// + /// + /// + /// If a settable property is available corresponding to the , the call should be + /// routed through that to ensure local business logic is enforced, if it hasn't already been enforced. + /// + /// + /// Compared to the base implementation, will throw a specific error if a duplicate key + /// is inserted. This conveniently provides the name of the so it's clear what key is + /// being duplicated. + /// + /// + /// The location that the should be set. + /// The object which is being inserted. + /// + /// An is thrown if an with the same as the already exists. + /// + protected override void InsertItem(int index, TItem item) { + Contract.Requires(item, nameof(item)); + if (!AllowClean(item)) { + item = item with { + IsDirty = true }; - if (_topicPropertyDispatcher.Enforce(trackedRecord.Key, trackedRecord)) { - if (!AssociatedTopic.IsNew) { - DeletedItems.Add(trackedRecord.Key); + } + if (_topicPropertyDispatcher.Enforce(item.Key, item)) { + if (!Contains(item.Key)) { + base.InsertItem(index, item); + if (DeletedItems.Contains(item.Key)) { + DeletedItems.Remove(item.Key); } - base.RemoveItem(index); + } + else { + throw new ArgumentException( + $"An {nameof(TItem)} with the Key '{item.Key}' already exists. The Value of the existing item is " + + $"{this[item.Key].Value}; the new item's Value is '{item.Value}'. These {nameof(TItem)}s are associated " + + $"with the {nameof(Topic)} '{AssociatedTopic.GetUniqueKey()}'.", + nameof(item) + ); } } + } - /*========================================================================================================================== - | OVERRIDE: CLEAR ITEMS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to clear the , to ensure that - /// it is appropriately marked as . - /// - /// - /// In order to ensure any business logic is enforced, loops through every in the and explicitly calls . This is slower, but ensures that any state tracking and null - /// validation that occurs in the properties is maintained. Fortunately, this is a rare use case; we typically expect - /// attributes to be handled individually. - /// - protected override void ClearItems() { - foreach (var item in Items.ToList()) { - Remove(item); - } - base.ClearItems(); + /*============================================================================================================================ + | OVERRIDE: SET ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to update an in the collection, to ensure that local business + /// logic is enforced. + /// + /// + /// If a settable property is available corresponding to the , the call should be routed + /// through that to ensure local business logic is enforced, if it hasn't already been enforced. + /// + /// The location that the should be set. + /// The object which is being inserted. + protected override void SetItem(int index, TItem item) { + Contract.Requires(item, nameof(item)); + if (!AllowClean(item)) { + item = item with { + IsDirty = true + }; } + if (_topicPropertyDispatcher.Enforce(item.Key, item)) { + base.SetItem(index, item); + } + } - /*========================================================================================================================== - | METHOD: ALLOW CLEAN? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if a is permitted to be marked as not . - /// - /// - /// If the is or the is and the is , then - /// should never be set to false. - /// - /// The object which is being inserted. - protected bool AllowClean(TItem item) { - Contract.Requires(item, nameof(item)); - var topic = item.Value as Topic; - if (topic is not null && topic.IsNew) { - return false; - } - if (AssociatedTopic.IsNew && !item.IsDirty) { - return false; + /*============================================================================================================================ + | OVERRIDE: REMOVE ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to remove an from the collection, to ensure that it is + /// appropriately marked as . + /// + /// + /// When an is removed, will return true�even if no remaining s are marked as . + /// + protected override void RemoveItem(int index) { + var trackedRecord = this[index] with { + Value = null + }; + if (_topicPropertyDispatcher.Enforce(trackedRecord.Key, trackedRecord)) { + if (!AssociatedTopic.IsNew) { + DeletedItems.Add(trackedRecord.Key); } - return true; + base.RemoveItem(index); } + } - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Method must be overridden for the EntityCollection to extract the keys from the items. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - [ExcludeFromCodeCoverage] - protected override sealed string GetKeyForItem(TItem item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Key; + /*============================================================================================================================ + | OVERRIDE: CLEAR ITEMS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to clear the , to ensure that + /// it is appropriately marked as . + /// + /// + /// In order to ensure any business logic is enforced, loops through every in the and explicitly calls . This is slower, but ensures that any state tracking and null + /// validation that occurs in the properties is maintained. Fortunately, this is a rare use case; we typically expect + /// attributes to be handled individually. + /// + protected override void ClearItems() { + foreach (var item in Items.ToList()) { + Remove(item); } + base.ClearItems(); + } - } //Class -} //Namespace \ No newline at end of file + /*============================================================================================================================ + | METHOD: ALLOW CLEAN? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if a is permitted to be marked as not . + /// + /// + /// If the is or the is and the is , then + /// should never be set to false. + /// + /// The object which is being inserted. + protected bool AllowClean(TItem item) { + Contract.Requires(item, nameof(item)); + var topic = item.Value as Topic; + if (topic is not null && topic.IsNew) { + return false; + } + if (AssociatedTopic.IsNew && !item.IsDirty) { + return false; + } + return true; + } + + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Method must be overridden for the EntityCollection to extract the keys from the items. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + [ExcludeFromCodeCoverage] + protected override sealed string GetKeyForItem(TItem item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Key; + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/Specialized/TrackedRecord{T}.cs b/OnTopic/Collections/Specialized/TrackedRecord{T}.cs index ab74e5ee..3547dff3 100644 --- a/OnTopic/Collections/Specialized/TrackedRecord{T}.cs +++ b/OnTopic/Collections/Specialized/TrackedRecord{T}.cs @@ -5,109 +5,108 @@ \=============================================================================================================================*/ using OnTopic.Repositories; -namespace OnTopic.Collections.Specialized { +namespace OnTopic.Collections.Specialized; + +/*============================================================================================================================== +| CLASS: TRACKED RECORD +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a base class for tracking versioned records, such as . +/// +/// +/// The class is comparable to the , in that it tracks the and for an item, but it additionally provides metadata related to the record, including +/// the and whether or not it . This makes it easier for e.g. implementations to make more informed decisions about whether a record needs to be saved or +/// overwritten during a or . +/// +public abstract record TrackedRecord { /*============================================================================================================================ - | CLASS: TRACKED RECORD + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ + /// - /// Provides a base class for tracking versioned records, such as . + /// Constructs a new instance of a class. /// - /// - /// The class is comparable to the , in that it tracks the and for an item, but it additionally provides metadata related to the record, including - /// the and whether or not it . This makes it easier for e.g. implementations to make more informed decisions about whether a record needs to be saved or - /// overwritten during a or . - /// - public abstract record TrackedRecord { + protected TrackedRecord() { + LastModified = DateTime.UtcNow; + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - - /// - /// Constructs a new instance of a class. - /// - protected TrackedRecord() { - LastModified = DateTime.UtcNow; - } - - /// - /// Constructs a new instance of a class. - /// - /// The for the instance. - /// The for the instance. - /// The optional state for the instance. - /// - /// The optional for the instance. - /// - protected TrackedRecord(string key, T? value, bool isDirty = true, DateTime? lastModified = null) { + /// + /// Constructs a new instance of a class. + /// + /// The for the instance. + /// The for the instance. + /// The optional state for the instance. + /// + /// The optional for the instance. + /// + protected TrackedRecord(string key, T? value, bool isDirty = true, DateTime? lastModified = null) { - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicFactory.ValidateKey(key, false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + TopicFactory.ValidateKey(key, false); - /*------------------------------------------------------------------------------------------------------------------------ - | Set properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Key = key; - Value = value; - IsDirty = isDirty; - LastModified = lastModified?? DateTime.UtcNow; + /*-------------------------------------------------------------------------------------------------------------------------- + | Set properties + \-------------------------------------------------------------------------------------------------------------------------*/ + Key = key; + Value = value; + IsDirty = isDirty; + LastModified = lastModified?? DateTime.UtcNow; - } + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the for a given item. - /// - /// - /// !value.Contains(" ") - /// - [NotNull] - public string? Key { get; init; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the for a given item. + /// + /// + /// !value.Contains(" ") + /// + [NotNull] + public string? Key { get; init; } - /*========================================================================================================================== - | PROPERTY: VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the for the given item. - /// - public T? Value { get; init; } + /*============================================================================================================================ + | PROPERTY: VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the for the given item. + /// + public T? Value { get; init; } - /*========================================================================================================================== - | PROPERTY: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if the item has been modified relative to its persisted state. - /// - /// - /// The property is used by the to determine whether or - /// not the value has been persisted to the data store. If it is set to true, the item's value is sent to the - /// data store when is called. Otherwise, it is ignored, - /// thus preventing the need to update records (or create new versions of records) whose values haven't changed. - /// - public bool IsDirty { get; init; } + /*============================================================================================================================ + | PROPERTY: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if the item has been modified relative to its persisted state. + /// + /// + /// The property is used by the to determine whether or + /// not the value has been persisted to the data store. If it is set to true, the item's value is sent to the + /// data store when is called. Otherwise, it is ignored, + /// thus preventing the need to update records (or create new versions of records) whose values haven't changed. + /// + public bool IsDirty { get; init; } - /*========================================================================================================================== - | PROPERTY: LAST MODIFIED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the for the given item. - /// - /// - /// If loaded from a data store from e.g. , the should be set to the Version. If the is novel, however, then it should be - /// set to the current date. That won't be the same date established by for the Version, however, which is why this property is labeled . - /// - public DateTime LastModified { get; init; } + /*============================================================================================================================ + | PROPERTY: LAST MODIFIED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the for the given item. + /// + /// + /// If loaded from a data store from e.g. , the should be set to the Version. If the is novel, however, then it should be + /// set to the current date. That won't be the same date established by for the Version, however, which is why this property is labeled . + /// + public DateTime LastModified { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Collections/TopicCollection.cs b/OnTopic/Collections/TopicCollection.cs index 7c4df021..5b67b13c 100644 --- a/OnTopic/Collections/TopicCollection.cs +++ b/OnTopic/Collections/TopicCollection.cs @@ -5,57 +5,56 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +public class TopicCollection : Collection { /*============================================================================================================================ - | CLASS: TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Initializes a new instance of the . /// - public class TopicCollection : Collection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - /// Seeds the collection with an optional list of topic references. - [ExcludeFromCodeCoverage] - public TopicCollection(IEnumerable? topics = null) : base(topics?.ToList()?? new()) { - } + /// Seeds the collection with an optional list of topic references. + [ExcludeFromCodeCoverage] + public TopicCollection(IEnumerable? topics = null) : base(topics?.ToList()?? new()) { + } - /*========================================================================================================================== - | METHOD: AS READ ONLY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a read-only version of this . - /// - public ReadOnlyTopicCollection AsReadOnly() => new(this); + /*============================================================================================================================ + | METHOD: AS READ ONLY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a read-only version of this . + /// + public ReadOnlyTopicCollection AsReadOnly() => new(this); - /*========================================================================================================================== - | METHOD: GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The {nameof(GetValue)} method is not implemented on {nameof(TopicCollection)}. Use {nameof(KeyedTopicCollection)} " + - $"instead.", - true - )] - public Topic? GetValue(string key) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"The {nameof(GetValue)} method is not implemented on {nameof(TopicCollection)}. Use {nameof(KeyedTopicCollection)} " + + $"instead.", + true + )] + public Topic? GetValue(string key) => throw new NotImplementedException(); - /*========================================================================================================================== - | INDEXER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"Indexing by key is not implemented on the {nameof(TopicCollection)}. Use the {nameof(KeyedTopicCollection)} instead.", - true - )] - public Topic this[string key] => throw new ArgumentOutOfRangeException(nameof(key)); + /*============================================================================================================================ + | INDEXER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"Indexing by key is not implemented on the {nameof(TopicCollection)}. Use the {nameof(KeyedTopicCollection)} instead.", + true + )] + public Topic this[string key] => throw new ArgumentOutOfRangeException(nameof(key)); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Diagnostics/Contract.cs b/OnTopic/Internal/Diagnostics/Contract.cs index 0e425c53..3ae8d691 100644 --- a/OnTopic/Internal/Diagnostics/Contract.cs +++ b/OnTopic/Internal/Diagnostics/Contract.cs @@ -4,165 +4,215 @@ | Project Topics Library \=============================================================================================================================*/ using System.Reflection; +using System.Runtime.CompilerServices; using Microsoft; -namespace OnTopic.Internal.Diagnostics { +namespace OnTopic.Internal.Diagnostics; + +/*============================================================================================================================== +| CLASS: CONTRACT [STATIC] +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// A static class for validating contract-style code declarations. +/// +/// +/// +/// Initially, OnTopic used Microsoft's references alongside their Code +/// Contracts analysis and rewrite modules. Those modules have seen been deprecated and are no longer actively maintained +/// by either Microsoft nor the community. Further, there is no evidence that Microsoft intends to support code contracts +/// analysis or rewriting in .NET Core. For this reason, code contracts is being removed from OnTopic. +/// +/// +/// is not a replacement for Microsoft's Code Contract analysis and rewrite modules. Instead, it +/// aims to maintain basic synatactical and functional support for the most basic (and important) features of the rewrite +/// module, such as Contract.Requires(), which is necessary to ensure paramater validation in many methods +/// throughout the OnTopic library. does not seek to functionally reproduce Code Contract's +/// Ensures(), Assume(), or Invariant()—those methods are not implemented. +/// +/// +/// C# 8.0 will introduce nullable reference types. This largely mitigates the need for Contract.Requires(). As +/// such, this library can be seen as a temporary bridge to maintain parameter validation until C# 8.0 is released. At +/// that point, nullable reference types should be used in preference for many of the Contract.Requires() +/// calls—though, acknowledging, that there are some conditions that won't be satisfied by that (e.g., range checks). +/// +/// +/// +/// +/// +public static class Contract { /*============================================================================================================================ - | CLASS: CONTRACT [STATIC] + | METHOD: REQUIRES \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// A static class for validating contract-style code declarations. + /// Will throw a if the supplied expression evaluates to false. /// - /// - /// - /// Initially, OnTopic used Microsoft's references alongside their Code - /// Contracts analysis and rewrite modules. Those modules have seen been deprecated and are no longer actively maintained - /// by either Microsoft nor the community. Further, there is no evidence that Microsoft intends to support code contracts - /// analysis or rewriting in .NET Core. For this reason, code contracts is being removed from OnTopic. - /// - /// - /// is not a replacement for Microsoft's Code Contract analysis and rewrite modules. Instead, it - /// aims to maintain basic synatactical and functional support for the most basic (and important) features of the rewrite - /// module, such as Contract.Requires(), which is necessary to ensure paramater validation in many methods - /// throughout the OnTopic library. does not seek to functionally reproduce Code Contract's - /// Ensures(), Assume(), or Invariant()—those methods are not implemented. - /// - /// - /// C# 8.0 will introduce nullable reference types. This largely mitigates the need for Contract.Requires(). As - /// such, this library can be seen as a temporary bridge to maintain parameter validation until C# 8.0 is released. At - /// that point, nullable reference types should be used in preference for many of the Contract.Requires() - /// calls—though, acknowledging, that there are some conditions that won't be satisfied by that (e.g., range checks). - /// - /// - /// - /// - /// - public static class Contract { - - /*========================================================================================================================== - | METHOD: REQUIRES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Will throw a if the supplied expression evaluates to false. - /// - /// An expression resulting in a boolean value indicating if an exception should be thrown. - /// Optionally provides an error message in case an exception is thrown. - /// - /// Thrown when returns . - /// - public static void Requires(bool isValid, string? errorMessage = null) => - Requires(isValid, errorMessage); + /// An expression resulting in a boolean value indicating if an exception should be thrown. + /// Optionally provides an error message in case an exception is thrown. + /// + /// Automatically captures the source text of ; used as the fallback error message when + /// is not supplied. + /// + /// + /// Thrown when returns . + /// + public static void Requires( + bool isValid, + string? errorMessage = null, + [CallerArgumentExpression(nameof(isValid))] string? expression = null + ) => Requires(isValid, errorMessage, expression); - /// - /// Will throw an if the supplied object is . - /// - /// An object that is required to be provided. - /// Optionally provides an error message in case an exception is thrown. - /// - /// Thrown when is . - /// - #pragma warning disable CS8777 // Parameter must have a non-null value when exiting. - public static void Requires([ValidatedNotNull, NotNull]object? requiredObject, string? errorMessage = null) => - Requires(requiredObject is not null, errorMessage); - #pragma warning restore CS8777 // Parameter must have a non-null value when exiting. - - /// - /// Will throw the provided generic exception if the supplied expression evaluates to false. - /// - /// - /// If the is included, this method assumes that the has a - /// constructor which accepts a single parameter of type , representing the error message for the - /// exception. If no such constructor is available, an will be thrown. - /// - /// An expression resulting in a boolean value indicating if an exception should be thrown. - /// Optionally provides an error message in case an exception is thrown. - /// - /// Thrown when returns . - /// - /// - /// Thrown when the does not a constructor accepting a sole parameter - /// representing the error message, and the parameter was supplied. - /// - public static void Requires(bool isValid, string? errorMessage = null) where T : Exception, new() { - if (isValid) return; - if (String.IsNullOrEmpty(errorMessage)) { - throw new T(); - } - try { - throw (T?)Activator.CreateInstance(typeof(T), new object[] { errorMessage })!; - } - catch (Exception ex) when ( - ex is MissingMethodException - or MethodAccessException - or TargetInvocationException - or NotSupportedException - ) { - throw new ArgumentException( - "The exception provided as the generic type argument does not have a constructor that accepts an error message as" + - " its sole argument", - nameof(errorMessage), - new T() - ); - } + /// + /// Will throw an if the supplied value is ; otherwise, + /// returns the value. + /// + /// The type of value being validated. + /// An object that is required to be provided. + /// Optionally provides an error message in case an exception is thrown. + /// + /// Automatically captures the source text of ; used as the fallback error message when + /// is not supplied. + /// + /// The supplied when it is not . + /// + /// Thrown when is . + /// + #pragma warning disable CS8777 // Parameter must have a non-null value when exiting. + public static T Requires( + [AllowNull, ValidatedNotNull, NotNull]T requiredObject, + string? errorMessage = null, + [CallerArgumentExpression(nameof(requiredObject))] string? expression = null + ) { + Requires(requiredObject is not null, errorMessage, expression); + return requiredObject!; + } + #pragma warning restore CS8777 // Parameter must have a non-null value when exiting. + /// + /// Will throw the provided generic exception if the supplied expression evaluates to false. + /// + /// + /// If the is included, this method assumes that the has a + /// constructor which accepts a single parameter of type , representing the error message for the + /// exception. If no such constructor is available, an will be thrown. + /// + /// An expression resulting in a boolean value indicating if an exception should be thrown. + /// Optionally provides an error message in case an exception is thrown. + /// + /// Automatically captures the source text of ; used as the fallback error message when + /// is not supplied. + /// + /// + /// Thrown when returns . + /// + /// + /// Thrown when the does not a constructor accepting a sole parameter + /// representing the error message, and an or is available. + /// + public static void Requires( + bool isValid, + string? errorMessage = null, + [CallerArgumentExpression(nameof(isValid))] string? expression = null + ) where T : Exception, new() { + if (isValid) return; + var message = errorMessage is not null && errorMessage.Length > 0 ? errorMessage : expression; + if (String.IsNullOrEmpty(message)) { + throw new T(); + } + try { + throw (T?)Activator.CreateInstance(typeof(T), message)!; + } + catch (Exception ex) when ( + ex is MissingMethodException + or MethodAccessException + or TargetInvocationException + or NotSupportedException + ) { + throw new ArgumentException( + "The exception provided as the generic type argument does not have a constructor that accepts an error message as" + + " its sole argument", + nameof(errorMessage), + new T() + ); } - /*========================================================================================================================== - | METHOD: ASSUME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a condition is met. If not, an is thrown. - /// - /// - /// This is virtually identical to except that, syntactically, it is expected to - /// live within the body of a method—where as is expected to live at the beginning - /// of a method. This communicates to readers that is validating runtime state, - /// whereas is validating preconditions. - /// - /// An expression resulting in a boolean value indicating if an exception should be thrown. - /// Optionally provides an error message in case an exception is thrown. - /// - /// Thrown when returns . - /// - public static void Assume(bool isValid, string? errorMessage = null) => - Requires(isValid, errorMessage); + } - /// - /// Ensures that a condition is met. If not, the provided exception is thrown. - /// - /// - /// Unlike the standard Assumes() method that ships with .NET, this custom overload accepts a generic , of type , which will be thrown if the condition is not met. This is virtually - /// identical to except that, syntactically, it is expected to live within the - /// body of a method—where as is expected to live at the beginning of a method. - /// This communicates to readers that is validating runtime state, whereas is validating preconditions. - /// - /// An expression resulting in a boolean value indicating if an exception should be thrown. - /// Optionally provides an error message in case an exception is thrown. - /// - /// Thrown when returns . - /// - /// - /// Thrown when the does not a constructor accepting a sole parameter - /// representing the error message, and the parameter was supplied. - /// - public static void Assume(bool isValid, string? errorMessage = null) where T : Exception, new() => - Requires(isValid, errorMessage); + /*============================================================================================================================ + | METHOD: ASSUME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a condition is met. If not, an is thrown. + /// + /// + /// This is virtually identical to except that, syntactically, it is + /// expected to live within the body of a method—where as is expected to + /// live at the beginning of a method. This communicates to readers that is + /// validating runtime state, whereas is validating preconditions. + /// + /// An expression resulting in a boolean value indicating if an exception should be thrown. + /// Optionally provides an error message in case an exception is thrown. + /// + /// Automatically captures the source text of ; used as the fallback error message when + /// is not supplied. + /// + /// + /// Thrown when returns . + /// + public static void Assume( + bool isValid, + string? errorMessage = null, + [CallerArgumentExpression(nameof(isValid))] string? expression = null + ) => Requires(isValid, errorMessage, expression); - /// - /// Will throw an if the supplied object is . - /// - /// An object that is required to be provided. - /// Optionally provides an error message in case an exception is thrown. - /// - /// Thrown when is . - /// - #pragma warning disable CS8777 // Parameter must have a non-null value when exiting. - public static void Assume([ValidatedNotNull, NotNull]object? requiredObject, string? errorMessage = null) - => Requires(requiredObject is not null, errorMessage); - #pragma warning restore CS8777 // Parameter must have a non-null value when exiting. + /// + /// Ensures that a condition is met. If not, the provided exception is thrown. + /// + /// + /// Unlike the standard Assumes() method that ships with .NET, this custom overload accepts a generic , of type , which will be thrown if the condition is not met. This is virtually + /// identical to except that, syntactically, it is expected to live + /// within the body of a method—where as is expected to live at the + /// beginning of a method. This communicates to readers that is + /// validating runtime state, whereas is validating preconditions. + /// + /// An expression resulting in a boolean value indicating if an exception should be thrown. + /// Optionally provides an error message in case an exception is thrown. + /// + /// Automatically captures the source text of ; used as the fallback error message when + /// is not supplied. + /// + /// + /// Thrown when returns . + /// + /// + /// Thrown when the does not a constructor accepting a sole parameter + /// representing the error message, and an or is available. + /// + public static void Assume( + bool isValid, + string? errorMessage = null, + [CallerArgumentExpression(nameof(isValid))] string? expression = null + ) where T : Exception, new() => Requires(isValid, errorMessage, expression); + + /// + /// Will throw an if the supplied object is . + /// + /// An object that is required to be provided. + /// Optionally provides an error message in case an exception is thrown. + /// + /// Automatically captures the source text of ; used as the fallback error message when + /// is not supplied. + /// + /// + /// Thrown when is . + /// + #pragma warning disable CS8777 // Parameter must have a non-null value when exiting. + public static void Assume( + [ValidatedNotNull, NotNull]object? requiredObject, + string? errorMessage = null, + [CallerArgumentExpression(nameof(requiredObject))] string? expression = null + ) => Requires(requiredObject is not null, errorMessage, expression); + #pragma warning restore CS8777 // Parameter must have a non-null value when exiting. - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Reflection/ItemMetadata.cs b/OnTopic/Internal/Reflection/ItemMetadata.cs index 4dbe44df..6d3e6131 100644 --- a/OnTopic/Internal/Reflection/ItemMetadata.cs +++ b/OnTopic/Internal/Reflection/ItemMetadata.cs @@ -9,191 +9,187 @@ using OnTopic.Mapping.Internal; using OnTopic.Mapping.Reverse; -namespace OnTopic.Internal.Reflection { +namespace OnTopic.Internal.Reflection; + +/*============================================================================================================================== +| CLASS: ITEM METADATA +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides metadata associated with a given parameter, method, or property. +/// +internal abstract class ItemMetadata { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly static List _listTypes = new(); + private readonly ICustomAttributeProvider _attributeProvider; /*============================================================================================================================ - | CLASS: ITEM METADATA + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides metadata associated with a given parameter, method, or property. + /// Establishes a new instance of a with required dependencies. /// - internal abstract class ItemMetadata { + static ItemMetadata() { + _listTypes.Add(typeof(IEnumerable<>)); + _listTypes.Add(typeof(ICollection<>)); + _listTypes.Add(typeof(IList<>)); + } - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly static List _listTypes = new(); - private readonly ICustomAttributeProvider _attributeProvider; - private readonly Type _type = default!; - private List _customAttributes = default!; - private ItemConfiguration? _itemConfiguration; - - /*========================================================================================================================== - | CONSTRUCTOR + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the class associated with a or instance. + /// + /// The of the or . + /// + /// The or associated with the . + /// + internal ItemMetadata(string name, ICustomAttributeProvider attributeProvider) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set Fields \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a with required dependencies. - /// - static ItemMetadata() { - _listTypes.Add(typeof(IEnumerable<>)); - _listTypes.Add(typeof(ICollection<>)); - _listTypes.Add(typeof(IList<>)); - } + _attributeProvider = attributeProvider; - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Set Properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class associated with a or instance. - /// - /// The of the or . - /// - /// The or associated with the . - /// - internal ItemMetadata(string name, ICustomAttributeProvider attributeProvider) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Set Fields - \-----------------------------------------------------------------------------------------------------------------------*/ - _attributeProvider = attributeProvider; - - /*------------------------------------------------------------------------------------------------------------------------ - | Set Properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Name = name; + Name = name; - } + } - /*========================================================================================================================== - | NAME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - internal string Name { get; } + /*============================================================================================================================ + | NAME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + internal string Name { get; } - /*========================================================================================================================== - | TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the associated with this member. For properties and get methods, this is the return type. For - /// set methods, this is the type of the parameter. - /// - /// - /// Ideally, the would be provided as part of the constructor. - /// Unfortunately, however, the logic for setting this type varies based on whether it is a parameter, a methor, or a - /// property. As such, it makes more sense for this logic to be implemented in derived classes. To facilitate this, the - /// property is provided with an initter, which will automatically set , , and when it is set. If this is not done properly, dependency classes will - /// not work properly, and will likely fail. Since there are only two expected derived classes— and —this shouldn't be a problem. To help avoid this scenario, a is thrown with instructions in the unexpected case that is not set. - /// - public Type Type { - get { - return _type?? throw new ArgumentNullException( - nameof(Type), - $"This {nameof(Type)} property must be initialized by classes derived by {nameof(ItemMetadata)}" - ); - } - init { - _type = value; - IsNullable = !Type.IsValueType || Nullable.GetUnderlyingType(Type) != null; - IsList = isList(); - IsConvertible = AttributeValueConverter.IsConvertible(Type); - bool isList() - => typeof(IList).IsAssignableFrom(Type) || Type.IsGenericType && _listTypes.Contains(Type.GetGenericTypeDefinition()); - } + /*============================================================================================================================ + | TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the associated with this member. For properties and get methods, this is the return type. For + /// set methods, this is the type of the parameter. + /// + /// + /// Ideally, the would be provided as part of the constructor. + /// Unfortunately, however, the logic for setting this type varies based on whether it is a parameter, a methor, or a + /// property. As such, it makes more sense for this logic to be implemented in derived classes. To facilitate this, the + /// property is provided with an initter, which will automatically set , , and when it is set. If this is not done properly, dependency classes will + /// not work properly, and will likely fail. Since there are only two expected derived classes— and —this shouldn't be a problem. To help avoid this scenario, a is thrown with instructions in the unexpected case that is not set. + /// + public Type Type { + get { + return field?? throw new ArgumentNullException( + nameof(Type), + $"This {nameof(Type)} property must be initialized by classes derived by {nameof(ItemMetadata)}" + ); + } + init { + field = value; + IsNullable = !Type.IsValueType || Nullable.GetUnderlyingType(Type) != null; + IsList = isList(); + IsConvertible = AttributeValueConverter.IsConvertible(Type); + bool isList() + => typeof(IList).IsAssignableFrom(Type) || Type.IsGenericType && _listTypes.Contains(Type.GetGenericTypeDefinition()); } + } - /*========================================================================================================================== - | CONFIGURATION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a reference to the configuration settings for the current item, based on the annotations configured in the code. - /// - /// - /// The class identifies annotations used by the and the - /// . While it can be called on any , it is only expected to - /// offer a benefit for model classes intended for mapping. - /// - internal ItemConfiguration Configuration { - get { - _itemConfiguration ??= new(this); - return _itemConfiguration; - } + /*============================================================================================================================ + | CONFIGURATION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a reference to the configuration settings for the current item, based on the annotations configured in the code. + /// + /// + /// The class identifies annotations used by the and the + /// . While it can be called on any , it is only expected to + /// offer a benefit for model classes intended for mapping. + /// + internal ItemConfiguration Configuration { + get { + field ??= new(this); + return field; } + } - /*========================================================================================================================== - | IS NULLABLE? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if the member accepts null values. - /// - /// - /// If the is a reference type, then it will always accept null values; this doesn't detect C# 9.0 - /// nullable reference types. - /// - internal bool IsNullable { get; init; } - - /*========================================================================================================================== - | IS LIST? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if the member is a , , , or . - /// - internal bool IsList { get; init; } - - /*========================================================================================================================== - | IS CONVERTIBLE? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if the member is of a type that can be converted using the class. - /// - internal bool IsConvertible { get; init; } + /*============================================================================================================================ + | IS NULLABLE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if the member accepts null values. + /// + /// + /// If the is a reference type, then it will always accept null values; this doesn't detect C# 9.0 + /// nullable reference types. + /// + internal bool IsNullable { get; init; } - /*========================================================================================================================== - | MAYBE COMPATIBLE? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if the item corresponds to a member on the class (or derivative) associated with the - /// parent . - /// - /// - /// - /// The does not guarantee that a corresponding compatible property will be found. - /// First, it cannot know what the source will be, so it relies only evaluates topics who match the - /// naming convention (e.g., {ContentType}TopicViewModel maps to {ContentType}), and otherwise falls back - /// to ; if a model is mapped to a different derivative of , additional matches - /// may be available. Second, it evaluates whether the member is of a type that can be assigned to - /// the model member, or otherwise converted—i.e., that the member is a string, and the model - /// member is one of the . This provides a hint for avoiding type - /// checks in cases we don't expect to be compatible, while deferring to the caller to provide more sophisticated checks - /// based on the actual . - /// - /// - /// The property must be set from the , which is best positioned - /// to efficiently determine the corresponding attributes. To do this, it must rely on attributes accessed via the property. As a result, the must be set after the instance has been constructed, instead of during initialization like the other properties. - /// That isn't ideal, but isn't easy to avoid without making each aware of the parent . - /// - /// - internal bool MaybeCompatible { get; set; } - - /*========================================================================================================================== - | CUSTOM ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a cached list of custom attributes associated with member. - /// - internal List CustomAttributes { - get { - _customAttributes ??= _attributeProvider.GetCustomAttributes(true).OfType().ToList(); - return _customAttributes; - } + /*============================================================================================================================ + | IS LIST? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if the member is a , , , or . + /// + internal bool IsList { get; init; } + + /*============================================================================================================================ + | IS CONVERTIBLE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if the member is of a type that can be converted using the class. + /// + internal bool IsConvertible { get; init; } + + /*============================================================================================================================ + | MAYBE COMPATIBLE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if the item corresponds to a member on the class (or derivative) associated with the + /// parent . + /// + /// + /// + /// The does not guarantee that a corresponding compatible property will be found. + /// First, it cannot know what the source will be, so it relies only evaluates topics who match the + /// naming convention (e.g., {ContentType}TopicViewModel maps to {ContentType}), and otherwise falls back + /// to ; if a model is mapped to a different derivative of , additional matches + /// may be available. Second, it evaluates whether the member is of a type that can be assigned to + /// the model member, or otherwise converted—i.e., that the member is a string, and the model + /// member is one of the . This provides a hint for avoiding type + /// checks in cases we don't expect to be compatible, while deferring to the caller to provide more sophisticated checks + /// based on the actual . + /// + /// + /// The property must be set from the , which is best positioned + /// to efficiently determine the corresponding attributes. To do this, it must rely on attributes accessed via the property. As a result, the must be set after the instance has been constructed, instead of during initialization like the other properties. + /// That isn't ideal, but isn't easy to avoid without making each aware of the parent . + /// + /// + internal bool MaybeCompatible { get; set; } + + /*============================================================================================================================ + | CUSTOM ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a cached list of custom attributes associated with member. + /// + internal List CustomAttributes { + get { + field ??= [.. _attributeProvider.GetCustomAttributes(true).OfType()]; + return field; } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Reflection/MemberAccessor.cs b/OnTopic/Internal/Reflection/MemberAccessor.cs index a7ad9bcc..3d3fd76e 100644 --- a/OnTopic/Internal/Reflection/MemberAccessor.cs +++ b/OnTopic/Internal/Reflection/MemberAccessor.cs @@ -6,453 +6,448 @@ using System.ComponentModel.DataAnnotations; using System.Reflection; -namespace OnTopic.Internal.Reflection { +namespace OnTopic.Internal.Reflection; + +/*============================================================================================================================== +| CLASS: MEMBER ACCESSOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides metadata and accessor methods for getting and setting data, as appropriate, from properties and methods. +/// +/// +/// This provides comparatively low-level access. It doesn't make any attempt to validate that e.g. the value submitted is +/// compatible with the property or method parameter type being set, nor does it make any effort to provide explicit +/// conversions. Those capabilities will be handled by higher-level libraries. +/// +internal sealed class MemberAccessor: ItemMetadata { /*============================================================================================================================ - | CLASS: MEMBER ACCESSOR + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides metadata and accessor methods for getting and setting data, as appropriate, from properties and methods. + /// Initializes a new instance of the class associated with a + /// instance. /// - /// - /// This provides comparatively low-level access. It doesn't make any attempt to validate that e.g. the value submitted is - /// compatible with the property or method parameter type being set, nor does it make any effort to provide explicit - /// conversions. Those capabilities will be handled by higher-level libraries. - /// - internal class MemberAccessor: ItemMetadata { + /// The associated with the . + internal MemberAccessor(MemberInfo memberInfo): base(memberInfo.Name, memberInfo) { - /*========================================================================================================================== - | PRIVATE VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - private Action? _setter; - private Func? _getter; + Contract.Requires( + memberInfo is PropertyInfo or MethodInfo, + $"The {nameof(memberInfo)} parameter must be of type {nameof(PropertyInfo)} or {nameof(MethodInfo)}." + ); - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Set Properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class associated with a - /// instance. - /// - /// The associated with the . - internal MemberAccessor(MemberInfo memberInfo): base(memberInfo.Name, memberInfo) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires( - memberInfo is PropertyInfo or MethodInfo, - $"The {nameof(memberInfo)} parameter must be of type {nameof(PropertyInfo)} or {nameof(MethodInfo)}." - ); + MemberInfo = memberInfo; + MemberType = MemberInfo.MemberType; + Type = GetType(memberInfo); + + } + + /*============================================================================================================================ + | MEMBER INFO + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides access to the underlying upon which the is based. + /// + internal MemberInfo MemberInfo { get; } + + /*============================================================================================================================ + | MEMBER TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + internal MemberTypes MemberType { get; } + + /*============================================================================================================================ + | CAN READ? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if the member can be used to retrieve a value. + /// + /// + /// Unlike the the , the property can be set for either properties + /// or methods. To be readable by , a method must have a return type and no parameters. + /// + internal bool CanRead { get; private set; } - /*------------------------------------------------------------------------------------------------------------------------ - | Set Properties - \-----------------------------------------------------------------------------------------------------------------------*/ - MemberInfo = memberInfo; - MemberType = MemberInfo.MemberType; - Type = GetType(memberInfo); + /*============================================================================================================================ + | CAN WRITE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if the member can be used to set a value. + /// + /// + /// Unlike the the , the property can be set for either + /// properties or methods. To be writable by , a method must be void and have exactly one + /// parameter. + /// + internal bool CanWrite { get; private set; } + /*============================================================================================================================ + | METHOD: IS SETTABLE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether the current member is settable, either assuming the list of , + /// or provided a specific . + /// + /// The to evaluate against . + /// + /// Determines whether a fallback to is permitted. + /// + internal bool IsSettable(Type? sourceType = null, bool allowConversion = false) { + if (sourceType is not null && (sourceType == Type || Type.IsAssignableFrom(sourceType))) { + return true; + } + if (allowConversion) { + var isSourceConvertible = sourceType is null || AttributeValueConverter.IsConvertible(sourceType); + return IsConvertible && isSourceConvertible; } + return false; + } - /*========================================================================================================================== - | MEMBER INFO - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides access to the underlying upon which the is based. - /// - internal MemberInfo MemberInfo { get; } + /*============================================================================================================================ + | GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves the value of the given member from a object. + /// + /// + /// The method can retrieve values from either property getters or methods which accept no + /// parameters and have a return type. + /// + /// The object from which the member value should be retrieved. + /// The value of the member, if available. + internal object? GetValue(object source) { - /*========================================================================================================================== - | MEMBER TYPE + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - internal MemberTypes MemberType { get; } + if (MemberInfo.DeclaringType != source.GetType() && !MemberInfo.DeclaringType!.IsAssignableFrom(source.GetType())) { + throw new ArgumentException( + $"The {nameof(MemberAccessor)} for {MemberInfo.DeclaringType} cannot be used to access a member of {source.GetType()}", + nameof(source) + ); + } - /*========================================================================================================================== - | CAN READ? + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate member type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if the member can be used to retrieve a value. - /// - /// - /// Unlike the the , the property can be set for either properties - /// or methods. To be readable by , a method must have a return type and no parameters. - /// - internal bool CanRead { get; private set; } - - /*========================================================================================================================== - | CAN WRITE? + if (!CanRead) { + return null; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if the member can be used to set a value. - /// - /// - /// Unlike the the , the property can be set for either - /// properties or methods. To be writable by , a method must be void and have exactly one - /// parameter. - /// - internal bool CanWrite { get; private set; } - - /*========================================================================================================================== - | METHOD: IS SETTABLE? + return Getter?.Invoke(source); + + } + + /*============================================================================================================================ + | SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets the value of the member on the object to the . + /// + /// + /// + /// The method can set values on either property setters or methods + /// which accept one parameter and don't have a return type. + /// + /// + /// The method makes no attempt to validate whether is compatible with the target property or method parameter type. If it is not compatible, the underlying + /// reflection library will throw an exception. It is expected that callers will validate the types before calling this + /// method. + /// + /// + /// The object on which the member should be set. + /// The value that the member should be set to. + /// + /// Determines whether a fallback to is permitted. + /// + internal void SetValue(object target, object? value, bool allowConversion = false) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether the current member is settable, either assuming the list of , - /// or provided a specific . - /// - /// The to evaluate against . - /// - /// Determines whether a fallback to is permitted. - /// - internal bool IsSettable(Type? sourceType = null, bool allowConversion = false) { - if (sourceType is not null && (sourceType == Type || Type.IsAssignableFrom(sourceType))) { - return true; - } - if (allowConversion) { - var isSourceConvertible = sourceType is null || AttributeValueConverter.IsConvertible(sourceType); - return IsConvertible && isSourceConvertible; - } - return false; + if (MemberInfo.DeclaringType != target.GetType() && !MemberInfo.DeclaringType!.IsAssignableFrom(target.GetType())) { + throw new ArgumentException( + $"The {nameof(MemberAccessor)} for {MemberInfo.DeclaringType} cannot be used to set a member of {target.GetType()}", + nameof(target) + ); } - /*========================================================================================================================== - | GET VALUE + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the value of the given member from a object. - /// - /// - /// The method can retrieve values from either property getters or methods which accept no - /// parameters and have a return type. - /// - /// The object from which the member value should be retrieved. - /// The value of the member, if available. - internal object? GetValue(object source) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - if (MemberInfo.DeclaringType != source.GetType() && !MemberInfo.DeclaringType.IsAssignableFrom(source.GetType())) { - throw new ArgumentException( - $"The {nameof(MemberAccessor)} for {MemberInfo.DeclaringType} cannot be used to access a member of {source.GetType()}", - nameof(source) - ); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate member type - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!CanRead) { - return null; - } + var valueObject = value; + var sourceType = value?.GetType(); - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve value - \-----------------------------------------------------------------------------------------------------------------------*/ - return Getter?.Invoke(source); + if (!CanWrite) { + return; + } + else if (value is null && !IsNullable) { + return; + } + else if (value is null || Type.IsAssignableFrom(sourceType)) { + //Proceed with conversion + } + else if (allowConversion && value is string) { + valueObject = AttributeValueConverter.Convert(value as string, Type); + } + if (valueObject is null && !IsNullable) { + return; } - /*========================================================================================================================== - | SET VALUE + /*-------------------------------------------------------------------------------------------------------------------------- + | Set value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets the value of the member on the object to the . - /// - /// - /// - /// The method can set values on either property setters or methods - /// which accept one parameter and don't have a return type. - /// - /// - /// The method makes no attempt to validate whether is compatible with the target property or method parameter type. If it is not compatible, the underlying - /// reflection library will throw an exception. It is expected that callers will validate the types before calling this - /// method. - /// - /// - /// The object on which the member should be set. - /// The value that the member should be set to. - /// - /// Determines whether a fallback to is permitted. - /// - internal void SetValue(object target, object? value, bool allowConversion = false) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - if (MemberInfo.DeclaringType != target.GetType() && !MemberInfo.DeclaringType.IsAssignableFrom(target.GetType())) { - throw new ArgumentException( - $"The {nameof(MemberAccessor)} for {MemberInfo.DeclaringType} cannot be used to set a member of {target.GetType()}", - nameof(target) - ); - } + Setter?.Invoke(target, valueObject); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate value - \-----------------------------------------------------------------------------------------------------------------------*/ - var valueObject = value; - var sourceType = value?.GetType(); + } - if (!CanWrite) { - return; - } - else if (value is null && !IsNullable) { - return; - } - else if (value is null || Type.IsAssignableFrom(sourceType)) { - //Proceed with conversion - } - else if (allowConversion && value is string) { - valueObject = AttributeValueConverter.Convert(value as string, Type); - } + /*============================================================================================================================ + | METHOD: VALIDATE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a target DTO, will automatically identify any attributes that derive from and + /// ensure that their conditions are satisfied. + /// + /// The target DTO to validate the current property on. + internal void Validate(object target) { + foreach (ValidationAttribute validator in CustomAttributes.OfType()) { + validator.Validate(GetValue(target), Name); + } + } - if (valueObject is null && !IsNullable) { - return; - } + /*============================================================================================================================ + | EXCLUDED MEMBERS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a list of member names automatically generated by the compiler for record types, but which aren't + /// relevant to mapping and should be excluded. + /// + private static List ExcludedMembers { get; } = new List() { + "EqualityContract", + "GetHashCode", + "ToString", + "$" + }; - /*------------------------------------------------------------------------------------------------------------------------ - | Set value - \-----------------------------------------------------------------------------------------------------------------------*/ - Setter?.Invoke(target, valueObject); - } + /*============================================================================================================================ + | IS VALID? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a given instance is compatible with the . + /// + /// + /// This is used by the to validate whether a should be created + /// for a given . For example, constructors, private members, and methods with more than one + /// parameter will return false. + /// + internal static Func IsValid => memberInfo => { - /*========================================================================================================================== - | METHOD: VALIDATE + /*-------------------------------------------------------------------------------------------------------------------------- + | Exclude unsupported types and members \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a target DTO, will automatically identify any attributes that derive from and - /// ensure that their conditions are satisfied. - /// - /// The target DTO to validate the current property on. - internal void Validate(object target) { - foreach (ValidationAttribute validator in CustomAttributes.OfType()) { - validator.Validate(GetValue(target), Name); - } - } + if (memberInfo.DeclaringType == typeof(object)) return false; + if (memberInfo is not MethodInfo and not PropertyInfo) return false; + if (memberInfo.Name.Contains("et_", StringComparison.Ordinal)) return false; + if (ExcludedMembers.Contains(memberInfo.Name)) return false; - /*========================================================================================================================== - | EXCLUDED MEMBERS + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a list of member names automatically generated by the compiler for record types, but which aren't - /// relevant to mapping and should be excluded. - /// - private static List ExcludedMembers { get; } = new List() { - "EqualityContract", - "GetHashCode", - "ToString", - "$" - }; - - - /*========================================================================================================================== - | IS VALID? + if (memberInfo is PropertyInfo) return true; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish method variables \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a given instance is compatible with the . - /// - /// - /// This is used by the to validate whether a should be created - /// for a given . For example, constructors, private members, and methods with more than one - /// parameter will return false. - /// - internal static Func IsValid => memberInfo => { - - /*------------------------------------------------------------------------------------------------------------------------ - | Exclude unsupported types and members - \-----------------------------------------------------------------------------------------------------------------------*/ - if (memberInfo.DeclaringType == typeof(object)) return false; - if (memberInfo is not MethodInfo and not PropertyInfo) return false; - if (memberInfo.Name.Contains("et_", StringComparison.Ordinal)) return false; - if (ExcludedMembers.Contains(memberInfo.Name)) return false; - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate properties - \-----------------------------------------------------------------------------------------------------------------------*/ - if (memberInfo is PropertyInfo) return true; - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish method variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var methodInfo = (MethodInfo)memberInfo; - var parameters = methodInfo.GetParameters(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate get methods - \-----------------------------------------------------------------------------------------------------------------------*/ - if (methodInfo.ReturnType != typeof(void)) { - return parameters.Length == 0; - } + var methodInfo = (MethodInfo)memberInfo; + var parameters = methodInfo.GetParameters(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate get methods + \-------------------------------------------------------------------------------------------------------------------------*/ + if (methodInfo.ReturnType != typeof(void)) { + return parameters.Length == 0; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate set methods + \-------------------------------------------------------------------------------------------------------------------------*/ + return parameters.Length == 1; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate set methods - \-----------------------------------------------------------------------------------------------------------------------*/ - return parameters.Length == 1; + }; - }; + /*============================================================================================================================ + | GET TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a reference, will evaluate features of the underlying and + /// use them to set the properties of this instance. + /// + /// + /// The method is private, and intended exclusively to break up the functionality + /// required by the constructor. + /// + /// The source that this instance is based on. + /// + private Type GetType(MemberInfo memberInfo) { - /*========================================================================================================================== - | GET TYPE + /*-------------------------------------------------------------------------------------------------------------------------- + | Set type as return type of property \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a reference, will evaluate features of the underlying and - /// use them to set the properties of this instance. - /// - /// - /// The method is private, and intended exclusively to break up the functionality - /// required by the constructor. - /// - /// The source that this instance is based on. - /// - private Type GetType(MemberInfo memberInfo) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Set type as return type of property - \-----------------------------------------------------------------------------------------------------------------------*/ - if (memberInfo is PropertyInfo propertyInfo) { - CanRead = propertyInfo.CanRead; - CanWrite = propertyInfo.CanWrite; - return propertyInfo.PropertyType; - } + if (memberInfo is PropertyInfo propertyInfo) { + CanRead = propertyInfo.CanRead; + CanWrite = propertyInfo.CanWrite; + return propertyInfo.PropertyType; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate method - \-----------------------------------------------------------------------------------------------------------------------*/ - var methodInfo = (MethodInfo)memberInfo; - var parameters = methodInfo.GetParameters(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set type as return type of method - \-----------------------------------------------------------------------------------------------------------------------*/ - if (methodInfo.ReturnType != typeof(void)) { - Contract.Assume( - parameters.Length == 0, - $"The '{memberInfo.Name}()' method must not expect any parameters if the return type is not void." - ); - CanRead = true; - return methodInfo.ReturnType; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate method + \-------------------------------------------------------------------------------------------------------------------------*/ + var methodInfo = (MethodInfo)memberInfo; + var parameters = methodInfo.GetParameters(); - /*------------------------------------------------------------------------------------------------------------------------ - | Set type as first parameter of method - \-----------------------------------------------------------------------------------------------------------------------*/ + /*-------------------------------------------------------------------------------------------------------------------------- + | Set type as return type of method + \-------------------------------------------------------------------------------------------------------------------------*/ + if (methodInfo.ReturnType != typeof(void)) { Contract.Assume( - parameters.Length == 1, - $"The '{memberInfo.Name}()' method must have one—and exactly one—parameter if the return type is void. This parameter " + - $"will be used as the value of the setter." + parameters.Length == 0, + $"The '{memberInfo.Name}()' method must not expect any parameters if the return type is not void." ); - - CanWrite = true; - return parameters[0].ParameterType; - + CanRead = true; + return methodInfo.ReturnType; } - /*========================================================================================================================== - | GETTER + /*-------------------------------------------------------------------------------------------------------------------------- + | Set type as first parameter of method \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly typed delegate for accessing either a property getter or a method with a return type and no - /// parameters. - /// - /// - /// The value is cached alongside this instance of the to improve performance across multiple - /// calls. - /// - private Func? Getter { - get { - if (_getter is null) { - var delegateType = typeof(Func<,>).MakeGenericType(MemberInfo.DeclaringType, Type); - var delegateGetter = (Delegate?)null; - if (MemberInfo is PropertyInfo propertInfo) { - delegateGetter = propertInfo.GetGetMethod().CreateDelegate(delegateType); - } - else if (MemberInfo is MethodInfo methodInfo) { - delegateGetter = methodInfo.CreateDelegate(delegateType); - } - var getterWithTypes = GetterDelegateMethod.MakeGenericMethod(MemberInfo.DeclaringType, Type); - _getter = (Func)getterWithTypes.Invoke(null, new[] { delegateGetter }); - } - return _getter; + Contract.Assume( + parameters.Length == 1, + $"The '{memberInfo.Name}()' method must have one—and exactly one—parameter if the return type is void. This parameter " + + $"will be used as the value of the setter." + ); + + CanWrite = true; + return parameters[0].ParameterType; + + } + + /*============================================================================================================================ + | GETTER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a strongly typed delegate for accessing either a property getter or a method with a return type and no + /// parameters. + /// + /// + /// The value is cached alongside this instance of the to improve performance across multiple + /// calls. + /// + private Func? Getter { + get { + if (field is null) { + var delegateType = typeof(Func<,>).MakeGenericType(MemberInfo.DeclaringType!, Type); + var delegateGetter = MemberInfo switch { + PropertyInfo propertInfo => (propertInfo.GetGetMethod() ?? + throw new InvalidOperationException( + $"The {propertInfo.Name} property does not have a public getter and cannot be used to retrieve a value." + )).CreateDelegate(delegateType), + MethodInfo methodInfo => methodInfo.CreateDelegate(delegateType), + _ => (Delegate?)null + }; + var getterWithTypes = GetterDelegateMethod.MakeGenericMethod(MemberInfo.DeclaringType!, Type); + field = (Func?)getterWithTypes.Invoke(null, [delegateGetter]); } + return field; } + } - /*========================================================================================================================== - | SETTER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a strongly typed delegate for accessing either a property setter or a void method with a single parameter. - /// - /// - /// The value is cached alongside this instance of the to improve performance across multiple - /// calls. - /// - private Action? Setter { - get { - if (_setter is null) { - var delegateType = typeof(Action<,>).MakeGenericType(MemberInfo.DeclaringType, Type); - var delegateSetter = (Delegate?)null; - if (MemberInfo is PropertyInfo propertInfo) { - delegateSetter = propertInfo.GetSetMethod().CreateDelegate(delegateType); - } - else if (MemberInfo is MethodInfo methodInfo) { - delegateSetter = methodInfo.CreateDelegate(delegateType); - } - var setterWithTypes = SetterDelegateMethod.MakeGenericMethod(MemberInfo.DeclaringType, Type); - _setter = (Action)setterWithTypes.Invoke(null, new[] { delegateSetter }); - } - return _setter; + /*============================================================================================================================ + | SETTER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a strongly typed delegate for accessing either a property setter or a void method with a single parameter. + /// + /// + /// The value is cached alongside this instance of the to improve performance across multiple + /// calls. + /// + private Action? Setter { + get { + if (field is null) { + var delegateType = typeof(Action<,>).MakeGenericType(MemberInfo.DeclaringType!, Type); + var delegateSetter = MemberInfo switch { + PropertyInfo propertInfo => (propertInfo.GetSetMethod() ?? + throw new InvalidOperationException( + $"The {propertInfo.Name} property does not have a public setter and cannot be used to set a value." + )).CreateDelegate(delegateType), + MethodInfo methodInfo => methodInfo.CreateDelegate(delegateType), + _ => (Delegate?)null + }; + var setterWithTypes = SetterDelegateMethod.MakeGenericMethod(MemberInfo.DeclaringType!, Type); + field = (Action?)setterWithTypes.Invoke(null, [delegateSetter]); } + return field; } + } - /*========================================================================================================================== - | CREATE SETTER DELEGATE SIGNATURE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a generic signature for a setter action. - /// - /// The object containing the member to set the value on. - /// The value that the member should be set to. - /// The strongly typed used to set the value. - /// - /// A loosely typed that wraps the strongly typed . - /// - private static Action CreateSetterDelegateSignature(Action deleg) - => (instance, value) => deleg((TClass)instance, (TValue?)value); - - /*========================================================================================================================== - | CREATE GETTER DELEGATE SIGNATURE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a generic signature for a getter action. - /// - /// The object containing the member to retrieve. - /// The return value of the member. - /// The strongly typed used to retrieve the value. - /// - /// A loosely typed that wraps the strongly typed . - /// - private static Func CreateGetterDelegateSignature(Func deleg) - => instance => deleg((TClass)instance); - - /*========================================================================================================================== - | SETTER DELEGATE METHOD REFERENCES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the method. - /// - private static readonly MethodInfo SetterDelegateMethod = - typeof(MemberAccessor).GetMethod(nameof(CreateSetterDelegateSignature), BindingFlags.NonPublic | BindingFlags.Static)!; - - /*========================================================================================================================== - | GETTER DELEGATE METHOD REFERENCES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the method. - /// - private static readonly MethodInfo GetterDelegateMethod = - typeof(MemberAccessor).GetMethod(nameof(CreateGetterDelegateSignature), BindingFlags.NonPublic | BindingFlags.Static)!; - - } //Class -} //Namespace \ No newline at end of file + /*============================================================================================================================ + | CREATE SETTER DELEGATE SIGNATURE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a generic signature for a setter action. + /// + /// The object containing the member to set the value on. + /// The value that the member should be set to. + /// The strongly typed used to set the value. + /// + /// A loosely typed that wraps the strongly typed . + /// + private static Action CreateSetterDelegateSignature(Action deleg) + => (instance, value) => deleg((TClass)instance, (TValue?)value); + + /*============================================================================================================================ + | CREATE GETTER DELEGATE SIGNATURE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a generic signature for a getter action. + /// + /// The object containing the member to retrieve. + /// The return value of the member. + /// The strongly typed used to retrieve the value. + /// + /// A loosely typed that wraps the strongly typed . + /// + private static Func CreateGetterDelegateSignature(Func deleg) + => instance => deleg((TClass)instance); + + /*============================================================================================================================ + | SETTER DELEGATE METHOD REFERENCES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the method. + /// + private static readonly MethodInfo SetterDelegateMethod = + typeof(MemberAccessor).GetMethod(nameof(CreateSetterDelegateSignature), BindingFlags.NonPublic | BindingFlags.Static)!; + + /*============================================================================================================================ + | GETTER DELEGATE METHOD REFERENCES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the method. + /// + private static readonly MethodInfo GetterDelegateMethod = + typeof(MemberAccessor).GetMethod(nameof(CreateGetterDelegateSignature), BindingFlags.NonPublic | BindingFlags.Static)!; + +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Reflection/ParameterMetadata.cs b/OnTopic/Internal/Reflection/ParameterMetadata.cs index 54700560..2612ee23 100644 --- a/OnTopic/Internal/Reflection/ParameterMetadata.cs +++ b/OnTopic/Internal/Reflection/ParameterMetadata.cs @@ -5,36 +5,40 @@ \=============================================================================================================================*/ using System.Reflection; -namespace OnTopic.Internal.Reflection { +namespace OnTopic.Internal.Reflection; + +/*============================================================================================================================== +| CLASS: PARAMETER METADATA +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides metadata associated with a given parameter. +/// +internal sealed class ParameterMetadata: ItemMetadata { /*============================================================================================================================ - | CLASS: PARAMETER METADATA + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides metadata associated with a given parameter. + /// Initializes a new instance of the class associated with a + /// instance. /// - internal class ParameterMetadata: ItemMetadata { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class associated with a - /// instance. - /// - /// The associated with this instance. - internal ParameterMetadata(ParameterInfo parameterInfo): base (parameterInfo.Name, parameterInfo) { - ParameterInfo = parameterInfo; - Type = parameterInfo.ParameterType; - } + /// The associated with this instance. + internal ParameterMetadata(ParameterInfo parameterInfo): base ( + parameterInfo.Name ?? throw new InvalidOperationException( + $"The {nameof(parameterInfo)} does not have a name and cannot be used to construct a {nameof(ParameterMetadata)}." + ), + parameterInfo + ) { + ParameterInfo = parameterInfo; + Type = parameterInfo.ParameterType; + } - /*========================================================================================================================== - | PARAMETER INFO - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the associated with this instance of . - /// - public ParameterInfo ParameterInfo { get; } + /*============================================================================================================================ + | PARAMETER INFO + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the associated with this instance of . + /// + public ParameterInfo ParameterInfo { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Reflection/TopicPropertyDispatcher{TItem,TValue,TAttributeType}.cs b/OnTopic/Internal/Reflection/TopicPropertyDispatcher{TItem,TValue,TAttributeType}.cs index b0d77adf..1cd20f5f 100644 --- a/OnTopic/Internal/Reflection/TopicPropertyDispatcher{TItem,TValue,TAttributeType}.cs +++ b/OnTopic/Internal/Reflection/TopicPropertyDispatcher{TItem,TValue,TAttributeType}.cs @@ -8,263 +8,262 @@ using OnTopic.Collections.Specialized; using OnTopic.Associations; -namespace OnTopic.Internal.Reflection { +namespace OnTopic.Internal.Reflection; + +/*============================================================================================================================== +| CLASS: TOPIC PROPERTY DISPATCHER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The allows a collection on a +/// entity to optionally route requests through properties on the corresponding which correspond to the +/// item key, thus ensuring local state and any business logic enforced by the property setter are maintained. +/// +/// +/// +/// Collections on , such as and , aren't +/// well-positioned to enforce attribute-specific business logic when adding or setting items in the collection. Instead, +/// this logic is typically handled by property setters on , such as or . This introduces a potential backdoor, as updates made directly to the collection can +/// bypass any business logic—such as data validation or local state management—handled by those property setters. The +/// class addresses this by allowing those +/// collections to route requests through appropriately decorated properties on prior to adding or +/// setting a value. +/// +/// +/// The requires two type arguments. represents an attribute which must be present on each property setter. This helps avoid +/// potential ambiguities. For instance, if both and have +/// the same key, and that key maps to a property, the usage will be restricted based on whether the +/// expected attribute is used to decorate the property—for instance, the or . In practice, this is an unexpected situation since a) individual content types +/// cannot use the same key for both and , and b) even if +/// they did, these properties support different data types, and thus are not intercompatible. Nevertheless, these +/// attributes provide an additional level of explicitness to avoid any ambiguity, and provide both developers as well as +/// the hints about what a +/// property is intended for. +/// +/// +/// The represents the value that is stored in the corresponding collection. This value is +/// saved as part of either or , and can +/// optionally be retrieved via . This is useful in case there is data from +/// the original request that might be lost when routed through the property setter. For example, the collection works with instances, which contain metadata such as , , and , which are not passed to the corresponding property decorated with . As such, by saving a reference to those as part of the process, we allow +/// the source collection to retrieve the original request in order to ensure that data isn't lost. This isn't as critical +/// for e.g. since the will be the same +/// that's sent to the corresponding property, and thus is expected to be the same as the value set by the property itself. +/// +/// +/// In a typical workflow, the method will end up getting once or twice. The first +/// occurs when a caller attempts to insert an item directly into a collection; if a corresponding property setter is +/// requested, then will call , trigger the +/// call to the corresponding property, and return false—indicating that the item should not be added to the +/// collection. In this case, the property setter will run its own business logic, then attempt to add or set the item +/// into the collection again. This time, the call to will prevent the second call +/// to from enforcing the business logic, thus preventing an infinite loop. +/// +/// +/// One caveat to this are cases where the caller attempts to set the value via the property directly, +/// instead of adding the item directly to the corresponding collection—e.g., they call instead +/// of e.g. the method from +/// . In that case, the business logic will already have been enforced, but the method will not have been called. To mitigate the property setter getting called twice, +/// collection implementors are advised to offer an internal overload that allows an item to be added to the collection +/// while bypassing the business logic. For instance, this can be done using or ; in each case, the internally +/// accessible enforceBusinessLogic parameter allows a property setter to disable business logic. Internally, this +/// is done by calling , thus assuring that +/// the business logic has already occurred. +/// +/// +internal sealed class TopicPropertyDispatcher + where TAttributeType: Attribute + where TItem: TrackedRecord + where TValue: class +{ + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly Topic _associatedTopic; /*============================================================================================================================ - | CLASS: TOPIC PROPERTY DISPATCHER + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The allows a collection on a - /// entity to optionally route requests through properties on the corresponding which correspond to the - /// item key, thus ensuring local state and any business logic enforced by the property setter are maintained. + /// Initializes a new instance of the class + /// associated with a specific . + /// + /// The whose properties should be called, when appropriate. + internal TopicPropertyDispatcher(Topic associatedTopic) { + _associatedTopic = associatedTopic; + } + + /*============================================================================================================================ + | PROPERTY: PROPERTY CACHE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a local cache of objects, keyed by an associated itemKey, prior + /// to having their business logic enforced. /// /// /// - /// Collections on , such as and , aren't - /// well-positioned to enforce attribute-specific business logic when adding or setting items in the collection. Instead, - /// this logic is typically handled by property setters on , such as or . This introduces a potential backdoor, as updates made directly to the collection can - /// bypass any business logic—such as data validation or local state management—handled by those property setters. The - /// class addresses this by allowing those - /// collections to route requests through appropriately decorated properties on prior to adding or - /// setting a value. + /// Whenever a property setter has been called, a record in the is added containing a) the + /// key associated with the item (and, therefore, property), and b) the original that + /// was to be added to the collection. This registers that the business logic for that property has been enforced. /// /// - /// The requires two type arguments. represents an attribute which must be present on each property setter. This helps avoid - /// potential ambiguities. For instance, if both and have - /// the same key, and that key maps to a property, the usage will be restricted based on whether the - /// expected attribute is used to decorate the property—for instance, the or . In practice, this is an unexpected situation since a) individual content types - /// cannot use the same key for both and , and b) even if - /// they did, these properties support different data types, and thus are not intercompatible. Nevertheless, these - /// attributes provide an additional level of explicitness to avoid any ambiguity, and provide both developers as well as - /// the hints about what a - /// property is intended for. + /// There are two ways that a record is created in the . The typical way is to call , which will check to see if there is a corresponding property setter and, if there + /// is, will add a record to the cache, and call the property. The second way is to call to directly register that the property has already been executed. This is typically done by special + /// internal methods, called exclusively by the property setters themselves, with a enforceBusinessLogic + /// parameter that is set to false; that prevents calls made directly to the property setter to bypass the + /// dispatcher. /// /// - /// The represents the value that is stored in the corresponding collection. This value is - /// saved as part of either or , and can - /// optionally be retrieved via . This is useful in case there is data from - /// the original request that might be lost when routed through the property setter. For example, the collection works with instances, which contain metadata such as , , and , which are not passed to the corresponding property decorated with . As such, by saving a reference to those as part of the process, we allow - /// the source collection to retrieve the original request in order to ensure that data isn't lost. This isn't as critical - /// for e.g. since the will be the same - /// that's sent to the corresponding property, and thus is expected to be the same as the value set by the property itself. + /// There is only one way to remove an item from the once it's been created. This happens + /// when is called, and a record already exists. When this occurs, the record + /// is removed, and returns true without any further action. This + /// instructs the caller—i.e., a method on a collection responsible for adding or setting an item—that it can complete + /// the request. /// + /// + private Dictionary PropertyCache { get; } = new(); + + /*============================================================================================================================ + | REGISTER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Instructs the that the business logic for a + /// corresponding property has been set, and does not need to be executed again. + /// + /// /// - /// In a typical workflow, the method will end up getting once or twice. The first - /// occurs when a caller attempts to insert an item directly into a collection; if a corresponding property setter is - /// requested, then will call , trigger the - /// call to the corresponding property, and return false—indicating that the item should not be added to the - /// collection. In this case, the property setter will run its own business logic, then attempt to add or set the item - /// into the collection again. This time, the call to will prevent the second call - /// to from enforcing the business logic, thus preventing an infinite loop. + /// The method is called by right before it + /// triggers a call to a corresponding property setter. This allows it to track that the business logic has been + /// enforced, and it doesn't need to make the call again on a round trip. /// /// - /// One caveat to this are cases where the caller attempts to set the value via the property directly, - /// instead of adding the item directly to the corresponding collection—e.g., they call instead - /// of e.g. the method from - /// . In that case, the business logic will already have been enforced, but the method will not have been called. To mitigate the property setter getting called twice, - /// collection implementors are advised to offer an internal overload that allows an item to be added to the collection - /// while bypassing the business logic. For instance, this can be done using or ; in each case, the internally - /// accessible enforceBusinessLogic parameter allows a property setter to disable business logic. Internally, this - /// is done by calling , thus assuring that - /// the business logic has already occurred. + /// The method can also be called directly by a collection to tell the that business logic should not be enforced when adding or + /// setting an item. The typical use case for this is an internal method which allows the property setters to bypass + /// business logic, thus preventing them from being called twice. These methods should be marked internal to prevent + /// external actors from bypassing the business logic; the purpose is to confirm that the business logic has already + /// been enforced, not to make the business logic optional. Two examples of this are the internal + /// enforceBusinessLogic parameters on and . + /// + /// + /// It's worth noting that any calls to are invalidated the next time is called. As such, is not a way to permanently + /// disable calling a property setter. (The correct way to do that is to remove the property setter, or at least its + /// corresponding .) Instead, it only disables the next attempt to add an item + /// corresponding to that key—which, if correctly implemented, will be when the current + /// is added to the collection. /// /// - internal class TopicPropertyDispatcher - where TAttributeType: Attribute - where TItem: TrackedRecord - where TValue: class - { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly Topic _associatedTopic; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class - /// associated with a specific . - /// - /// The whose properties should be called, when appropriate. - internal TopicPropertyDispatcher(Topic associatedTopic) { - _associatedTopic = associatedTopic; + /// + /// The key of the , which potentially corresponds to a property. + /// + /// The object which is being inserted. + internal bool Register(string itemKey, TItem? initialValue) { + var type = (Type?)null; + if (!AttributeValueConverter.IsConvertible(typeof(TValue))) { + type = typeof(TValue); } - - /*========================================================================================================================== - | PROPERTY: PROPERTY CACHE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a local cache of objects, keyed by an associated itemKey, prior - /// to having their business logic enforced. - /// - /// - /// - /// Whenever a property setter has been called, a record in the is added containing a) the - /// key associated with the item (and, therefore, property), and b) the original that - /// was to be added to the collection. This registers that the business logic for that property has been enforced. - /// - /// - /// There are two ways that a record is created in the . The typical way is to call , which will check to see if there is a corresponding property setter and, if there - /// is, will add a record to the cache, and call the property. The second way is to call to directly register that the property has already been executed. This is typically done by special - /// internal methods, called exclusively by the property setters themselves, with a enforceBusinessLogic - /// parameter that is set to false; that prevents calls made directly to the property setter to bypass the - /// dispatcher. - /// - /// - /// There is only one way to remove an item from the once it's been created. This happens - /// when is called, and a record already exists. When this occurs, the record - /// is removed, and returns true without any further action. This - /// instructs the caller—i.e., a method on a collection responsible for adding or setting an item—that it can complete - /// the request. - /// - /// - private Dictionary PropertyCache { get; } = new(); - - /*========================================================================================================================== - | REGISTER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instructs the that the business logic for a - /// corresponding property has been set, and does not need to be executed again. - /// - /// - /// - /// The method is called by right before it - /// triggers a call to a corresponding property setter. This allows it to track that the business logic has been - /// enforced, and it doesn't need to make the call again on a round trip. - /// - /// - /// The method can also be called directly by a collection to tell the that business logic should not be enforced when adding or - /// setting an item. The typical use case for this is an internal method which allows the property setters to bypass - /// business logic, thus preventing them from being called twice. These methods should be marked internal to prevent - /// external actors from bypassing the business logic; the purpose is to confirm that the business logic has already - /// been enforced, not to make the business logic optional. Two examples of this are the internal - /// enforceBusinessLogic parameters on and . - /// - /// - /// It's worth noting that any calls to are invalidated the next time is called. As such, is not a way to permanently - /// disable calling a property setter. (The correct way to do that is to remove the property setter, or at least its - /// corresponding .) Instead, it only disables the next attempt to add an item - /// corresponding to that key—which, if correctly implemented, will be when the current - /// is added to the collection. - /// - /// - /// - /// The key of the , which potentially corresponds to a property. - /// - /// The object which is being inserted. - internal bool Register(string itemKey, TItem? initialValue) { - var type = (Type?)null; - if (!AttributeValueConverter.IsConvertible(typeof(TValue))) { - type = typeof(TValue); - } - if ( - !PropertyCache.ContainsKey(itemKey) && - TypeAccessorCache.GetTypeAccessor(_associatedTopic.GetType()).HasSettableProperty(itemKey, type) - ) { - PropertyCache.Add(itemKey, initialValue); - return true; - } - return false; + if ( + !PropertyCache.ContainsKey(itemKey) && + TypeAccessorCache.GetTypeAccessor(_associatedTopic.GetType()).HasSettableProperty(itemKey, type) + ) { + PropertyCache.Add(itemKey, initialValue); + return true; } + return false; + } - /*========================================================================================================================== - | IS REGISTERED? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Identifies whether the given has been registered—and, thus, has already had its business - /// logic enforced. - /// - /// - /// The key of the , which potentially corresponds to a property. - /// - /// Returns true if the has been registered, otherwise false. - [ExcludeFromCodeCoverage] - internal bool IsRegistered(string itemKey) => IsRegistered(itemKey, out var _); + /*============================================================================================================================ + | IS REGISTERED? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Identifies whether the given has been registered—and, thus, has already had its business + /// logic enforced. + /// + /// + /// The key of the , which potentially corresponds to a property. + /// + /// Returns true if the has been registered, otherwise false. + [ExcludeFromCodeCoverage] + internal bool IsRegistered(string itemKey) => IsRegistered(itemKey, out var _); - /// - /// Identifies whether the given has been registered—and, thus, has already had its business - /// logic enforced. Returns the that was registered as an out parameter. - /// - /// - /// The key of the , which potentially corresponds to a property. - /// - /// The object which is being inserted. - /// Returns true if the has been registered, otherwise false. - internal bool IsRegistered(string itemKey, [NotNullWhen(true)] out TItem? initialObject) => - PropertyCache.TryGetValue(itemKey, out initialObject!); + /// + /// Identifies whether the given has been registered—and, thus, has already had its business + /// logic enforced. Returns the that was registered as an out parameter. + /// + /// + /// The key of the , which potentially corresponds to a property. + /// + /// The object which is being inserted. + /// Returns true if the has been registered, otherwise false. + internal bool IsRegistered(string itemKey, [NotNullWhen(true)] out TItem? initialObject) => + PropertyCache.TryGetValue(itemKey, out initialObject!); - /*========================================================================================================================== - | METHOD: ENFORCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Inspects the requested to determine if the corresponding - /// should be routed through the associated in order to enforce business logic. - /// - /// - /// - /// If a settable property is available on the associated corresponding to the , the call should be routed through that property to ensure that local business logic is enforced. This is - /// determined by looking for attribute, which confirms that a property with a - /// matching name is aware of and intended to operate with a given collection. - /// - /// - /// The method should be called from an implementing collection prior to - /// committing an add, insert, or set operation. That operation should only be completed if returns true; otherwise, the request will be routed through the corresponding property on in order to enforce any business logic, after which the property will attempt to add the property to - /// the collection again. When is called a second time for the same , it won't enforce the business logic, and will instead return true. - /// - /// - /// - /// The key of the , which potentially corresponds to a property - /// setter. - /// - /// The object which is being inserted. - /// Returns true if the business logic has been enfored; otherwise false. - internal bool Enforce(string itemKey, TItem? initialObject) { - #pragma warning disable CA1853 // Unnecessary call to 'Dictionary.ContainsKey(key)' - if (PropertyCache.ContainsKey(itemKey)) { - PropertyCache.Remove(itemKey); - return true; + /*============================================================================================================================ + | METHOD: ENFORCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Inspects the requested to determine if the corresponding + /// should be routed through the associated in order to enforce business logic. + /// + /// + /// + /// If a settable property is available on the associated corresponding to the , the call should be routed through that property to ensure that local business logic is enforced. This is + /// determined by looking for attribute, which confirms that a property with a + /// matching name is aware of and intended to operate with a given collection. + /// + /// + /// The method should be called from an implementing collection prior to + /// committing an add, insert, or set operation. That operation should only be completed if returns true; otherwise, the request will be routed through the corresponding property on in order to enforce any business logic, after which the property will attempt to add the property to + /// the collection again. When is called a second time for the same , it won't enforce the business logic, and will instead return true. + /// + /// + /// + /// The key of the , which potentially corresponds to a property + /// setter. + /// + /// The object which is being inserted. + /// Returns true if the business logic has been enfored; otherwise false. + internal bool Enforce(string itemKey, TItem? initialObject) { + #pragma warning disable CA1853 // Unnecessary call to 'Dictionary.ContainsKey(key)' + if (PropertyCache.ContainsKey(itemKey)) { + PropertyCache.Remove(itemKey); + return true; + } + #pragma warning restore CA1853 // Unnecessary call to 'Dictionary.ContainsKey(key)' + else if (Register(itemKey, initialObject)) { + try { + var typeAccessor = TypeAccessorCache.GetTypeAccessor(_associatedTopic.GetType()); + typeAccessor.SetPropertyValue(_associatedTopic, itemKey, initialObject?.Value, true); } - #pragma warning restore CA1853 // Unnecessary call to 'Dictionary.ContainsKey(key)' - else if (Register(itemKey, initialObject)) { - try { - var typeAccessor = TypeAccessorCache.GetTypeAccessor(_associatedTopic.GetType()); - typeAccessor.SetPropertyValue(_associatedTopic, itemKey, initialObject?.Value, true); - } - catch (TargetInvocationException ex) { - PropertyCache.Remove(itemKey); - if (ex.InnerException is not null) { - ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); - } - throw; + catch (TargetInvocationException ex) { + PropertyCache.Remove(itemKey); + if (ex.InnerException is not null) { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); } - return false; + throw; } - return true; + return false; } + return true; + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Reflection/TypeAccessor.cs b/OnTopic/Internal/Reflection/TypeAccessor.cs index ca25a816..ba1e777e 100644 --- a/OnTopic/Internal/Reflection/TypeAccessor.cs +++ b/OnTopic/Internal/Reflection/TypeAccessor.cs @@ -5,451 +5,453 @@ \=============================================================================================================================*/ using System.Reflection; -namespace OnTopic.Internal.Reflection { +namespace OnTopic.Internal.Reflection; + +/*============================================================================================================================== +| CLASS: MEMBER ACCESSOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides access to a collection of instances related to a specific in +/// order to simplify common access scenarios for properties and methods. +/// +/// +/// +/// For retrieving values, the typical workflow is for a caller to check either or , followed by or to retrieve the value. +/// +/// +/// For setting values, the typical workflow is for a caller to check either or , followed by or to retrieve the value. In these +/// scenarios, the will attempt to deserialize the value parameter from to the type expected by the corresponding property or method. Typically, this will be a , +/// , , or . +/// +/// +/// Alternatively, setters can call or , in which case the final value parameter will be set the +/// target property, or passed as the parameter of the method without any attempt to convert it. Obviously, this requires +/// that the target type be assignable from the value object. +/// +/// +/// The is an internal service intended to meet the specific needs of OnTopic, and comes with +/// certain limitations. It only supports setting values of methods with a single parameter, which is assumed to +/// correspond to the value parameter. It will only operate against the first overload of a method, and/or the most +/// derived version of a member. +/// +/// +internal sealed class TypeAccessor { /*============================================================================================================================ - | CLASS: MEMBER ACCESSOR + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly Dictionary _members; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides access to a collection of instances related to a specific in - /// order to simplify common access scenarios for properties and methods. + /// Initializes a new instance of a based on a given . /// /// - /// - /// For retrieving values, the typical workflow is for a caller to check either or , followed by or to retrieve the value. - /// - /// - /// For setting values, the typical workflow is for a caller to check either or , followed by or to retrieve the value. In these - /// scenarios, the will attempt to deserialize the value parameter from to the type expected by the corresponding property or method. Typically, this will be a , - /// , , or . - /// - /// - /// Alternatively, setters can call or , in which case the final value parameter will be set the - /// target property, or passed as the parameter of the method without any attempt to convert it. Obviously, this requires - /// that the target type be assignable from the value object. - /// - /// - /// The is an internal service intended to meet the specific needs of OnTopic, and comes with - /// certain limitations. It only supports setting values of methods with a single parameter, which is assumed to - /// correspond to the value parameter. It will only operate against the first overload of a method, and/or the most - /// derived version of a member. - /// + /// The constructor automatically identifies each supported on the + /// and adds an associated to the of each. /// - internal class TypeAccessor { + /// + internal TypeAccessor(Type type) { - /*========================================================================================================================== - | PRIVATE VARIABLES + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize fields, properties \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly Dictionary _members; + _members = new(StringComparer.OrdinalIgnoreCase); + Type = type; - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Get members from type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a based on a given . - /// - /// - /// The constructor automatically identifies each supported on the - /// and adds an associated to the of each. - /// - /// - internal TypeAccessor(Type type) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize fields, properties - \-----------------------------------------------------------------------------------------------------------------------*/ - _members = new(StringComparer.OrdinalIgnoreCase); - Type = type; - - /*------------------------------------------------------------------------------------------------------------------------ - | Get members from type - \-----------------------------------------------------------------------------------------------------------------------*/ - var members = type.GetMembers( - BindingFlags.Instance | - BindingFlags.FlattenHierarchy | - BindingFlags.NonPublic | - BindingFlags.Public - ); - foreach (var member in members.Where(t => MemberAccessor.IsValid(t))) { - if (!_members.ContainsKey(member.Name)) { - _members.Add(member.Name, new(member)); - } - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Get parameters from primary constructor - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var parameter in GetPrimaryConstructor().GetParameters()) { - ConstructorParameters.Add(new(parameter)); + var members = type.GetMembers( + BindingFlags.Instance | + BindingFlags.FlattenHierarchy | + BindingFlags.NonPublic | + BindingFlags.Public + ); + foreach (var member in members.Where(t => MemberAccessor.IsValid(t))) { + if (!_members.ContainsKey(member.Name)) { + _members.Add(member.Name, new(member)); } - - /*------------------------------------------------------------------------------------------------------------------------ - | Identify expected topic, and set MaybeCompatible if a corresponding property exists - \-----------------------------------------------------------------------------------------------------------------------*/ - SetItemCompatibility(); - } - /*========================================================================================================================== - | TYPE + /*-------------------------------------------------------------------------------------------------------------------------- + | Get parameters from primary constructor \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the return type of a getter or the argument type of a setter. - /// - internal Type Type { get; } + foreach (var parameter in GetPrimaryConstructor().GetParameters()) { + ConstructorParameters.Add(new(parameter)); + } - /*========================================================================================================================== - | CONSTRUCTOR PARAMETERS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a list of instances derived from the primary constructor of the associated with this . - /// - internal List ConstructorParameters { get; } = new(); - - /*========================================================================================================================== - | GET MEMBERS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of properties and methods supported by the . - /// - /// Optionally filters the list of members by a list. - /// A list of instances. - internal List GetMembers(MemberTypes memberTypes = MemberTypes.All) => - _members.Values.Where(m => memberTypes == MemberTypes.All || memberTypes.HasFlag(m.MemberType)).ToList(); - - /// - /// Retrieves a list of properties and methods as objects, instead of s. - /// - /// A list of instances. - internal IEnumerable GetMembers() where T : MemberInfo - => GetMembers().Select(m => m.MemberInfo).Where(t => t is T).Cast(); - - /*========================================================================================================================== - | GET MEMBER + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify expected topic, and set MaybeCompatible if a corresponding property exists \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a property or method supported by the by . - /// - /// The name of the member to retrieve, derived from . - /// A instance for getting or setting values on a given member. - internal MemberAccessor? GetMember(string memberName) => _members.GetValueOrDefault(memberName); - - /*========================================================================================================================== - | METHOD: GET PRIMARY CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - internal ConstructorInfo GetPrimaryConstructor() => - Type.GetConstructors( - BindingFlags.Instance | - BindingFlags.FlattenHierarchy | - BindingFlags.Public - ).FirstOrDefault(); + SetItemCompatibility(); - /*========================================================================================================================== - | HAS GETTER? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if a with a getter exists for a member with the given . - /// - /// The name of the member to assess, derived from . - /// True if a gettable member exists; otherwise false. - internal bool HasGetter(string memberName) => GetMember(memberName)?.CanRead ?? false; - - /*========================================================================================================================== - | METHOD: HAS GETTABLE PROPERTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Used reflection to identify if a local property is available and gettable. - /// - /// - /// Will return false if the property is not available. - /// - /// The name of the property to assess, derived from . - /// Optional, the expected. - /// Optional, the expected on the property. - internal bool HasGettableProperty(string propertyName, Type? targetType = null, Type? attributeFlag = null) { - var property = GetMember(propertyName); - return ( - property is not null and { CanRead: true, MemberType: MemberTypes.Property } && - property.IsSettable(targetType, true) && - (attributeFlag is null || Attribute.IsDefined(property.MemberInfo, attributeFlag)) - ); - } + } - /// - /// The expected on the property. - internal bool HasGettableProperty(string propertyName, Type? targetType = null) where T : Attribute - => HasGettableProperty(propertyName, targetType, typeof(T)); + /*============================================================================================================================ + | TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the return type of a getter or the argument type of a setter. + /// + internal Type Type { get; } - /*========================================================================================================================== - | METHOD: HAS GETTABLE METHOD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Used reflection to identify if a local method is available and gettable. - /// - /// - /// Will return false if the method is not available. Methods are only considered gettable if they have no parameters and - /// their return value is a settable type. - /// - /// The name of the method to assess, derived from . - /// Optional, the expected. - /// Optional, the expected on the property. - internal bool HasGettableMethod(string methodName, Type? targetType = null, Type? attributeFlag = null) { - var method = GetMember(methodName); - return ( - method is not null and { CanRead: true, MemberType: MemberTypes.Method } && - method.IsSettable(targetType, true) && - (attributeFlag is null || Attribute.IsDefined(method.MemberInfo, attributeFlag)) - ); - } + /*============================================================================================================================ + | CONSTRUCTOR PARAMETERS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a list of instances derived from the primary constructor of the associated with this . + /// + internal List ConstructorParameters { get; } = new(); + + /*============================================================================================================================ + | GET MEMBERS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of properties and methods supported by the . + /// + /// Optionally filters the list of members by a list. + /// A list of instances. + internal List GetMembers(MemberTypes memberTypes = MemberTypes.All) => + [.. _members.Values.Where(m => memberTypes == MemberTypes.All || memberTypes.HasFlag(m.MemberType))]; - /// - /// The expected on the property. - internal bool HasGettableMethod(string name, Type? targetType = null) where T : Attribute - => HasGettableMethod(name, targetType, typeof(T)); + /// + /// Retrieves a list of properties and methods as objects, instead of s. + /// + /// A list of instances. + internal IEnumerable GetMembers() where T : MemberInfo + => GetMembers().Select(m => m.MemberInfo).Where(t => t is T).Cast(); - /*========================================================================================================================== - | GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the value from a member named from the supplied - /// object. - /// - /// The instance from which the value should be retrieved. - /// The name of the member to retrieve, derived from . - /// The value returned from the member. - internal object? GetValue(object source, string memberName) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve member - \-----------------------------------------------------------------------------------------------------------------------*/ - var member = GetMember(memberName); - - if (member is null) { - return null; - } + /*============================================================================================================================ + | GET MEMBER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a property or method supported by the by . + /// + /// The name of the member to retrieve, derived from . + /// A instance for getting or setting values on a given member. + internal MemberAccessor? GetMember(string memberName) => _members.GetValueOrDefault(memberName); - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve value - \-----------------------------------------------------------------------------------------------------------------------*/ - return member.GetValue(source); + /*============================================================================================================================ + | METHOD: GET PRIMARY CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + internal ConstructorInfo GetPrimaryConstructor() => + Type.GetConstructors( + BindingFlags.Instance | + BindingFlags.FlattenHierarchy | + BindingFlags.Public + ).FirstOrDefault() ?? + throw new InvalidOperationException( + $"The {Type.Name} type does not have a public constructor." + ); - } + /*============================================================================================================================ + | HAS GETTER? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if a with a getter exists for a member with the given . + /// + /// The name of the member to assess, derived from . + /// True if a gettable member exists; otherwise false. + internal bool HasGetter(string memberName) => GetMember(memberName)?.CanRead ?? false; - /*========================================================================================================================== - | METHOD: GET PROPERTY VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Uses reflection to call a property, assuming that it is a) readable, and b) of type , - /// , or . - /// - /// The object instance on which the property is defined. - /// The name of the property to retrieve, derived from . - internal object? GetPropertyValue(object source, string propertyName) => GetValue(source, propertyName); - - /*========================================================================================================================== - | METHOD: GET METHOD VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Uses reflection to call a method, assuming that it has no parameters. - /// - /// The object instance on which the method is defined. - /// The name of the method to retrieve, derived from . - internal object? GetMethodValue(object source, string methodName) => GetValue(source, methodName); - - /*========================================================================================================================== - | HAS SETTER? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if a with a setter exists for a member with the given . - /// - /// The name of the member to assess, derived from . - /// True if a settable member exists; otherwise false. - internal bool HasSetter(string memberName) => GetMember(memberName)?.CanWrite ?? false; - - /*========================================================================================================================== - | METHOD: HAS SETTABLE PROPERTY + /*============================================================================================================================ + | METHOD: HAS GETTABLE PROPERTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Used reflection to identify if a local property is available and gettable. + /// + /// + /// Will return false if the property is not available. + /// + /// The name of the property to assess, derived from . + /// Optional, the expected. + /// Optional, the expected on the property. + internal bool HasGettableProperty(string propertyName, Type? targetType = null, Type? attributeFlag = null) { + var property = GetMember(propertyName); + return ( + property is not null and { CanRead: true, MemberType: MemberTypes.Property } && + property.IsSettable(targetType, true) && + (attributeFlag is null || Attribute.IsDefined(property.MemberInfo, attributeFlag)) + ); + } + + /// + /// The expected on the property. + internal bool HasGettableProperty(string propertyName, Type? targetType = null) where T : Attribute + => HasGettableProperty(propertyName, targetType, typeof(T)); + + /*============================================================================================================================ + | METHOD: HAS GETTABLE METHOD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Used reflection to identify if a local method is available and gettable. + /// + /// + /// Will return false if the method is not available. Methods are only considered gettable if they have no parameters and + /// their return value is a settable type. + /// + /// The name of the method to assess, derived from . + /// Optional, the expected. + /// Optional, the expected on the property. + internal bool HasGettableMethod(string methodName, Type? targetType = null, Type? attributeFlag = null) { + var method = GetMember(methodName); + return ( + method is not null and { CanRead: true, MemberType: MemberTypes.Method } && + method.IsSettable(targetType, true) && + (attributeFlag is null || Attribute.IsDefined(method.MemberInfo, attributeFlag)) + ); + } + + /// + /// The expected on the property. + internal bool HasGettableMethod(string name, Type? targetType = null) where T : Attribute + => HasGettableMethod(name, targetType, typeof(T)); + + /*============================================================================================================================ + | GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves the value from a member named from the supplied + /// object. + /// + /// The instance from which the value should be retrieved. + /// The name of the member to retrieve, derived from . + /// The value returned from the member. + internal object? GetValue(object source, string memberName) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve member \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Used reflection to identify if a local property is available and settable. - /// - /// - /// Will return false if the property is not available. - /// - /// The name of the property to assess, derived from . - /// Optional, the expected. - /// Optional, the expected on the property. - internal bool HasSettableProperty(string propertyName, Type? targetType = null, Type? attributeFlag = null) { - var property = GetMember(propertyName); - return ( - property is not null and { CanWrite: true, MemberType: MemberTypes.Property } && - property.IsSettable(targetType, true) && - (attributeFlag is null || Attribute.IsDefined(property.MemberInfo as PropertyInfo, attributeFlag)) - ); + var member = GetMember(memberName); + + if (member is null) { + return null; } - /// - /// The expected on the property. - internal bool HasSettableProperty(string propertyName, Type? targetType = null) where T : Attribute - => HasSettableProperty(propertyName, targetType, typeof(T)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve value + \-------------------------------------------------------------------------------------------------------------------------*/ + return member.GetValue(source); + + } + + /*============================================================================================================================ + | METHOD: GET PROPERTY VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Uses reflection to call a property, assuming that it is a) readable, and b) of type , + /// , or . + /// + /// The object instance on which the property is defined. + /// The name of the property to retrieve, derived from . + internal object? GetPropertyValue(object source, string propertyName) => GetValue(source, propertyName); + + /*============================================================================================================================ + | METHOD: GET METHOD VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Uses reflection to call a method, assuming that it has no parameters. + /// + /// The object instance on which the method is defined. + /// The name of the method to retrieve, derived from . + internal object? GetMethodValue(object source, string methodName) => GetValue(source, methodName); + + /*============================================================================================================================ + | HAS SETTER? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if a with a setter exists for a member with the given . + /// + /// The name of the member to assess, derived from . + /// True if a settable member exists; otherwise false. + internal bool HasSetter(string memberName) => GetMember(memberName)?.CanWrite ?? false; - /*========================================================================================================================== - | METHOD: HAS SETTABLE METHOD + /*============================================================================================================================ + | METHOD: HAS SETTABLE PROPERTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Used reflection to identify if a local property is available and settable. + /// + /// + /// Will return false if the property is not available. + /// + /// The name of the property to assess, derived from . + /// Optional, the expected. + /// Optional, the expected on the property. + internal bool HasSettableProperty(string propertyName, Type? targetType = null, Type? attributeFlag = null) { + var property = GetMember(propertyName); + return ( + property is not null and { CanWrite: true, MemberType: MemberTypes.Property } && + property.IsSettable(targetType, true) && + (attributeFlag is null || Attribute.IsDefined((PropertyInfo)property.MemberInfo, attributeFlag)) + ); + } + + /// + /// The expected on the property. + internal bool HasSettableProperty(string propertyName, Type? targetType = null) where T : Attribute + => HasSettableProperty(propertyName, targetType, typeof(T)); + + /*============================================================================================================================ + | METHOD: HAS SETTABLE METHOD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Used reflection to identify if a local method is available and settable. + /// + /// + /// Will return false if the method is not available. Methods are only considered settable if they have one parameter of + /// a settable type. Be aware that this will return false if the method has additional parameters, even if those + /// additional parameters are optional. + /// + /// The name of the method to assess, derived from . + /// Optional, the expected. + /// Optional, the expected on the property. + internal bool HasSettableMethod(string methodName, Type? targetType = null, Type? attributeFlag = null) { + var method = GetMember(methodName); + return ( + method is not null and { CanWrite: true, MemberType: MemberTypes.Method } && + method.IsSettable(targetType, true) && + (attributeFlag is null || Attribute.IsDefined(method.MemberInfo, attributeFlag)) + ); + } + + /// + /// The expected on the property. + internal bool HasSettableMethod(string methodName, Type? targetType = null) where T : Attribute + => HasSettableMethod(methodName, targetType, typeof(T)); + + /*============================================================================================================================ + | SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets the value of a member named on the supplied object. + /// + /// The instance on which the value should be set. + /// The name of the member to set, derived from . + /// The value to set the member to. + /// + /// Determines whether a fallback to is permitted. + /// + internal void SetValue(object target, string memberName, object? value, bool allowConversion = false) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate dependencies \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Used reflection to identify if a local method is available and settable. - /// - /// - /// Will return false if the method is not available. Methods are only considered settable if they have one parameter of - /// a settable type. Be aware that this will return false if the method has additional parameters, even if those - /// additional parameters are optional. - /// - /// The name of the method to assess, derived from . - /// Optional, the expected. - /// Optional, the expected on the property. - internal bool HasSettableMethod(string methodName, Type? targetType = null, Type? attributeFlag = null) { - var method = GetMember(methodName); - return ( - method is not null and { CanWrite: true, MemberType: MemberTypes.Method } && - method.IsSettable(targetType, true) && - (attributeFlag is null || Attribute.IsDefined(method.MemberInfo, attributeFlag)) - ); - } + var member = GetMember(memberName); - /// - /// The expected on the property. - internal bool HasSettableMethod(string methodName, Type? targetType = null) where T : Attribute - => HasSettableMethod(methodName, targetType, typeof(T)); + Contract.Assume(member, $"The {memberName} property could not be retrieved."); - /*========================================================================================================================== - | SET VALUE + /*-------------------------------------------------------------------------------------------------------------------------- + | Set value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets the value of a member named on the supplied object. - /// - /// The instance on which the value should be set. - /// The name of the member to set, derived from . - /// The value to set the member to. - /// - /// Determines whether a fallback to is permitted. - /// - internal void SetValue(object target, string memberName, object? value, bool allowConversion = false) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - var member = GetMember(memberName); - - Contract.Assume(member, $"The {memberName} property could not be retrieved."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set value - \-----------------------------------------------------------------------------------------------------------------------*/ - member.SetValue(target, value, allowConversion); + member.SetValue(target, value, allowConversion); - } + } - /*========================================================================================================================== - | METHOD: SET PROPERTY VALUE + /*============================================================================================================================ + | METHOD: SET PROPERTY VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Uses reflection to call a property, assuming that it is a) writable, and b) of type , , or , or is otherwise compatible with the type. + /// + /// The object on which the property is defined. + /// The name of the property to set, derived from . + /// The value to set on the property. + /// + /// Determines whether a fallback to is permitted. + /// + internal void SetPropertyValue(object target, string propertyName, object? value, bool allowConversion = false) + => SetValue(target, propertyName, value, allowConversion); + + /*============================================================================================================================ + | METHOD: SET METHOD VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Uses reflection to call a method, assuming that the parameter value is compatible with the + /// type. + /// + /// + /// Be aware that this will only succeed if the method has a single parameter of a settable type. If additional parameters + /// are present it will return false, even if those additional parameters are optional. + /// + /// The object instance on which the method is defined. + /// The name of the method to set, derived from . + /// The value to set the method to. + /// + /// Determines whether a fallback to is permitted. + /// + internal void SetMethodValue(object target, string methodName, object? value, bool allowConversion = false) + => SetValue(target, methodName, value, allowConversion); + + /*============================================================================================================================ + | METHOD: SET ITEM COMPATIBILITY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if each member corresponds to a compatible or convertible member of a corresponding . + /// + /// + /// The method applies basic assumptions to identify the corresponding and whether or not any matching parameters or members are compatible with members of that . See for more details. + /// + private void SetItemCompatibility() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Only attempt to detect compatibility for model types, not for topics. + >------------------------------------------------------------------------------------------------------------------------- + | We expect mapping to topics to typically use e.g. Attributes or References, which will automatically marshal through + | properties if appropriate. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Uses reflection to call a property, assuming that it is a) writable, and b) of type , , or , or is otherwise compatible with the type. - /// - /// The object on which the property is defined. - /// The name of the property to set, derived from . - /// The value to set on the property. - /// - /// Determines whether a fallback to is permitted. - /// - internal void SetPropertyValue(object target, string propertyName, object? value, bool allowConversion = false) - => SetValue(target, propertyName, value, allowConversion); - - /*========================================================================================================================== - | METHOD: SET METHOD VALUE + if (typeof(Topic).IsAssignableFrom(Type)) { + return; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify corresponding topic type + >------------------------------------------------------------------------------------------------------------------------- + | Assuming a model follows the convention {ContentType}TopicViewModel or {ContentType}ViewModel, find a corresponding + | Topic named {ContentType}. If this cannot be found, fall back to Topic. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Uses reflection to call a method, assuming that the parameter value is compatible with the - /// type. - /// - /// - /// Be aware that this will only succeed if the method has a single parameter of a settable type. If additional parameters - /// are present it will return false, even if those additional parameters are optional. - /// - /// The object instance on which the method is defined. - /// The name of the method to set, derived from . - /// The value to set the method to. - /// - /// Determines whether a fallback to is permitted. - /// - internal void SetMethodValue(object target, string methodName, object? value, bool allowConversion = false) - => SetValue(target, methodName, value, allowConversion); - - /*========================================================================================================================== - | METHOD: SET ITEM COMPATIBILITY + var impliedContentType = Type.Name + .Replace("TopicViewModel", "", StringComparison.OrdinalIgnoreCase) + .Replace("ViewModel", "", StringComparison.OrdinalIgnoreCase); + var topicType = TopicFactory.TypeLookupService.Lookup(impliedContentType)?? typeof(Topic); + var topicAccessor = TypeAccessorCache.GetTypeAccessor(topicType); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Detect compatibility + >------------------------------------------------------------------------------------------------------------------------- + | If the Topic contains a property named {Name} or a method named Get{Name}, and that member's type is either compatible + | or convertible, then set MaybeCompatible to true. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if each member corresponds to a compatible or convertible member of a corresponding . - /// - /// - /// The method applies basic assumptions to identify the corresponding and whether or not any matching parameters or members are compatible with members of that . See for more details. - /// - private void SetItemCompatibility() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Only attempt to detect compatibility for model types, not for topics. - >------------------------------------------------------------------------------------------------------------------------- - | We expect mapping to topics to typically use e.g. Attributes or References, which will automatically marshal through - | properties if appropriate. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (typeof(Topic).IsAssignableFrom(Type)) { - return; + foreach (var member in ConstructorParameters.Cast().Union(_members.Values)) { + var attributeKey = member.Configuration.AttributeKey; + var topicMember = topicAccessor.GetMember(attributeKey)?? topicAccessor.GetMember($"Get{attributeKey}"); + if (topicMember is null) { + continue; } - - /*------------------------------------------------------------------------------------------------------------------------ - | Identify corresponding topic type - >------------------------------------------------------------------------------------------------------------------------- - | Assuming a model follows the convention {ContentType}TopicViewModel or {ContentType}ViewModel, find a corresponding - | Topic named {ContentType}. If this cannot be found, fall back to Topic. - \-----------------------------------------------------------------------------------------------------------------------*/ - var impliedContentType = Type.Name - .Replace("TopicViewModel", "", StringComparison.OrdinalIgnoreCase) - .Replace("ViewModel", "", StringComparison.OrdinalIgnoreCase); - var topicType = TopicFactory.TypeLookupService.Lookup(impliedContentType)?? typeof(Topic); - var topicAccessor = TypeAccessorCache.GetTypeAccessor(topicType); - - /*------------------------------------------------------------------------------------------------------------------------ - | Detect compatibility - >------------------------------------------------------------------------------------------------------------------------- - | If the Topic contains a property named {Name} or a method named Get{Name}, and that member's type is either compatible - | or convertible, then set MaybeCompatible to true. - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var member in ConstructorParameters.Cast().Union(_members.Values)) { - var attributeKey = member.Configuration.AttributeKey; - var topicMember = topicAccessor.GetMember(attributeKey)?? topicAccessor.GetMember($"Get{attributeKey}"); - if (topicMember is null) { - continue; - } - else if (member.IsConvertible && topicMember.Type == typeof(string)) { - member.MaybeCompatible = true; - } - else if (member.Type.IsAssignableFrom(topicMember.Type)) { - member.MaybeCompatible = true; - } - + else if (member.IsConvertible && topicMember.Type == typeof(string)) { + member.MaybeCompatible = true; } + else if (member.Type.IsAssignableFrom(topicMember.Type)) { + member.MaybeCompatible = true; + } + } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Internal/Reflection/TypeAccessorCache.cs b/OnTopic/Internal/Reflection/TypeAccessorCache.cs index 67189a34..a8cf51d0 100644 --- a/OnTopic/Internal/Reflection/TypeAccessorCache.cs +++ b/OnTopic/Internal/Reflection/TypeAccessorCache.cs @@ -5,41 +5,40 @@ \=============================================================================================================================*/ using System.Collections.Concurrent; -namespace OnTopic.Internal.Reflection { +namespace OnTopic.Internal.Reflection; + +/*============================================================================================================================== +| CLASS: TYPE ACCESSOR CACHE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides access to a cached set of instances across the application. +/// +internal static class TypeAccessorCache { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private static readonly ConcurrentDictionary _cache = new(); /*============================================================================================================================ - | CLASS: TYPE ACCESSOR CACHE + | GET TYPE ACCESSOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides access to a cached set of instances across the application. + /// Retrieves a for a given . /// - internal static class TypeAccessorCache { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private static readonly ConcurrentDictionary _cache = new(); - - /*========================================================================================================================== - | GET TYPE ACCESSOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a for a given . - /// - /// - /// As each is fixed at runtime, and we expect types that are mapped once to be mapped multiple times, - /// a static cache is maintained of instances. If the provided doesn't yet - /// exist in the cache, it will be created. - /// - /// The that needs to be dynamically accessed. - /// A for dynamically accessing the supplied . - internal static TypeAccessor GetTypeAccessor(Type type) { - return _cache.GetOrAdd(type, t => new(t)); - } + /// + /// As each is fixed at runtime, and we expect types that are mapped once to be mapped multiple times, + /// a static cache is maintained of instances. If the provided doesn't yet + /// exist in the cache, it will be created. + /// + /// The that needs to be dynamically accessed. + /// A for dynamically accessing the supplied . + internal static TypeAccessor GetTypeAccessor(Type type) { + return _cache.GetOrAdd(type, t => new(t)); + } - /// - /// The that needs to be dynamically accessed. - internal static TypeAccessor GetTypeAccessor() => GetTypeAccessor(typeof(T)); + /// + /// The that needs to be dynamically accessed. + internal static TypeAccessor GetTypeAccessor() => GetTypeAccessor(typeof(T)); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/InvalidKeyException.cs b/OnTopic/InvalidKeyException.cs index 50db9edf..fb20cca0 100644 --- a/OnTopic/InvalidKeyException.cs +++ b/OnTopic/InvalidKeyException.cs @@ -3,82 +3,68 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ -using System.Runtime.Serialization; +namespace OnTopic; -namespace OnTopic { +/*============================================================================================================================== +| CLASS: INVALID KEY EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Exception to be thrown when a property referencing a is assigned with an invalidate value. +/// +/// +/// s are alphanumeric, and may contain hyphens, periods, or underscores. Any other values, such as +/// spaces, slashes, or colons, are not permitted and will throw an exception. +/// +[ExcludeFromCodeCoverage] +public class InvalidKeyException: ArgumentException { /*============================================================================================================================ - | CLASS: INVALID KEY EXCEPTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Exception to be thrown when a property referencing a is assigned with an invalidate value. + /// Instantiates a new instance of a class with no parameters. /// - /// - /// s are alphanumeric, and may contain hyphens, periods, or underscores. Any other values, such as - /// spaces, slashes, or colons, are not permitted and will throw an exception. - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class InvalidKeyException: ArgumentException { + /// A new instance. + public InvalidKeyException(): base() { + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of a class with no parameters. - /// - /// A new instance. - public InvalidKeyException(): base() { - } - - /// - /// Instantiates a new instance of a class with a custom error message. - /// - /// An error message associated with this exception. - /// A new instance. - public InvalidKeyException(string message): base(message) { - } - - /// - /// Instantiates a new instance of a class with a custom error message and inner - /// exception. - /// - /// An error message associated with this exception. - /// The inner exception associated with the current exception. - /// A new instance. - public InvalidKeyException(string message, Exception inner): base(message, inner) { - } + /// + /// Instantiates a new instance of a class with a custom error message. + /// + /// An error message associated with this exception. + /// A new instance. + public InvalidKeyException(string message): base(message) { + } - /// - /// Instantiates a new instance of a class with a custom error message and associated - /// parameter name. - /// - /// An error message associated with this exception. - /// The name of the parameter that is associated with the exception. - /// A new instance. - public InvalidKeyException(string message, string paramName) : base(message, paramName) { - } + /// + /// Instantiates a new instance of a class with a custom error message and inner + /// exception. + /// + /// An error message associated with this exception. + /// The inner exception associated with the current exception. + /// A new instance. + public InvalidKeyException(string message, Exception inner): base(message, inner) { + } - /// - /// Instantiates a new instance of a class with a custom error message, associated - /// parameter name, and inner exception. - /// - /// An error message associated with this exception. - /// The name of the parameter that is associated with the exception. - /// The inner exception associated with the current exception. - /// A new instance. - public InvalidKeyException(string message, string paramName, Exception inner) : base(message, paramName, inner) { - } + /// + /// Instantiates a new instance of a class with a custom error message and associated + /// parameter name. + /// + /// An error message associated with this exception. + /// The name of the parameter that is associated with the exception. + /// A new instance. + public InvalidKeyException(string message, string paramName) : base(message, paramName) { + } - /// - /// Instantiates a new instance of a class for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected InvalidKeyException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Instantiates a new instance of a class with a custom error message, associated + /// parameter name, and inner exception. + /// + /// An error message associated with this exception. + /// The name of the parameter that is associated with the exception. + /// The inner exception associated with the current exception. + /// A new instance. + public InvalidKeyException(string message, string paramName, Exception inner) : base(message, paramName, inner) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/CompositeTypeLookupService.cs b/OnTopic/Lookup/CompositeTypeLookupService.cs index ad6cf71e..632c9ceb 100644 --- a/OnTopic/Lookup/CompositeTypeLookupService.cs +++ b/OnTopic/Lookup/CompositeTypeLookupService.cs @@ -4,67 +4,66 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: COMPOSITE TYPE LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The allows s from multiple s +/// to be merged into a single . +/// +/// +/// Different libraries—such as the OnTopic View Models or OnTopic Editors—may have their own for managing s that are specific to that library. The +/// allows those to be combined into a single by passing each of them to the constructor. +/// If conflicts occur, then the last entered will take precidence, overriding any initial definitions. +/// +public class CompositeTypeLookupService: ITypeLookupService { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly List _typeLookupServices = new(); /*============================================================================================================================ - | CLASS: COMPOSITE TYPE LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The allows s from multiple s - /// to be merged into a single . + /// Establishes a new instance of a . Accepts any number of instanced to be passed to the constructor. /// - /// - /// Different libraries—such as the OnTopic View Models or OnTopic Editors—may have their own for managing s that are specific to that library. The - /// allows those to be combined into a single by passing each of them to the constructor. - /// If conflicts occur, then the last entered will take precidence, overriding any initial definitions. - /// - public class CompositeTypeLookupService: ITypeLookupService { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly List _typeLookupServices = new(); + /// + /// The list of instances to expose as part of this service. + /// + public CompositeTypeLookupService(params ITypeLookupService[] typeLookupServices) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Add types to internal collection \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . Accepts any number of instanced to be passed to the constructor. - /// - /// - /// The list of instances to expose as part of this service. - /// - public CompositeTypeLookupService(params ITypeLookupService[] typeLookupServices) { + typeLookupServices.Reverse(); + _typeLookupServices.AddRange(typeLookupServices); - /*------------------------------------------------------------------------------------------------------------------------ - | Add types to internal collection - \-----------------------------------------------------------------------------------------------------------------------*/ - typeLookupServices.Reverse(); - _typeLookupServices.AddRange(typeLookupServices); + } - } - - /*========================================================================================================================== - | METHOD: LOOKUP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public Type? Lookup(params string[] typeNames) { - var type = typeof(object); - if (typeNames is not null) { - foreach (var typeName in typeNames) { - foreach (var typeLookupService in _typeLookupServices) { - type = typeLookupService.Lookup(typeName); - if (type is not null && type.Name.Equals(typeName, StringComparison.OrdinalIgnoreCase)) { - return type; - } + /*============================================================================================================================ + | METHOD: LOOKUP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public Type? Lookup(params string[] typeNames) { + var type = typeof(object); + if (typeNames is not null) { + foreach (var typeName in typeNames) { + foreach (var typeLookupService in _typeLookupServices) { + type = typeLookupService.Lookup(typeName); + if (type is not null && type.Name.Equals(typeName, StringComparison.OrdinalIgnoreCase)) { + return type; } } } - //Default to default return type of last query - return type; } + //Default to default return type of last query + return type; + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/DefaultTopicLookupService.cs b/OnTopic/Lookup/DefaultTopicLookupService.cs index c8d25917..eed9f8f2 100644 --- a/OnTopic/Lookup/DefaultTopicLookupService.cs +++ b/OnTopic/Lookup/DefaultTopicLookupService.cs @@ -6,37 +6,36 @@ using System.Reflection; using OnTopic.Metadata; -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: TYPE INDEX +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The can be configured to provide a lookup of . +/// +public class DefaultTopicLookupService: StaticTypeLookupService { /*============================================================================================================================ - | CLASS: TYPE INDEX + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The can be configured to provide a lookup of . + /// Establishes a new instance of a . Optionally accepts a list of instances and a default value. /// - public class DefaultTopicLookupService: StaticTypeLookupService { + /// + /// Any instances submitted via should be unique by ; if they are not, they will be removed. + /// + /// The list of instances to expose as part of this service. + public DefaultTopicLookupService(IEnumerable? types = null) : base(types) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure editor types are accounted for \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . Optionally accepts a list of instances and a default value. - /// - /// - /// Any instances submitted via should be unique by ; if they are not, they will be removed. - /// - /// The list of instances to expose as part of this service. - public DefaultTopicLookupService(IEnumerable? types = null) : base(types) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure editor types are accounted for - \-----------------------------------------------------------------------------------------------------------------------*/ - TryAdd(typeof(ContentTypeDescriptor)); - TryAdd(typeof(AttributeDescriptor)); + TryAdd(typeof(ContentTypeDescriptor)); + TryAdd(typeof(AttributeDescriptor)); - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/DynamicTopicBindingModelLookupService.cs b/OnTopic/Lookup/DynamicTopicBindingModelLookupService.cs index 35065dcd..647f721c 100644 --- a/OnTopic/Lookup/DynamicTopicBindingModelLookupService.cs +++ b/OnTopic/Lookup/DynamicTopicBindingModelLookupService.cs @@ -5,24 +5,23 @@ \=============================================================================================================================*/ using OnTopic.Models; -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: DYNAMIC TOPIC BINDING MODEL LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The will search all assemblies for s that +/// implement . +/// +public class DynamicTopicBindingModelLookupService : DynamicTypeLookupService { /*============================================================================================================================ - | CLASS: DYNAMIC TOPIC BINDING MODEL LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The will search all assemblies for s that - /// implement . + /// Establishes a new instance of a . /// - public class DynamicTopicBindingModelLookupService : DynamicTypeLookupService { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . - /// - public DynamicTopicBindingModelLookupService() : base(t => typeof(ITopicBindingModel).IsAssignableFrom(t)) { } + public DynamicTopicBindingModelLookupService() : base(t => typeof(ITopicBindingModel).IsAssignableFrom(t)) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/DynamicTopicLookupService.cs b/OnTopic/Lookup/DynamicTopicLookupService.cs index 3e376929..599a44c8 100644 --- a/OnTopic/Lookup/DynamicTopicLookupService.cs +++ b/OnTopic/Lookup/DynamicTopicLookupService.cs @@ -5,26 +5,25 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: DYNAMIC TOPIC LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The will search all assemblies for s that derive from . +/// +public class DynamicTopicLookupService : DynamicTypeLookupService { /*============================================================================================================================ - | CLASS: DYNAMIC TOPIC LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The will search all assemblies for s that derive from . + /// Establishes a new instance of a . /// - public class DynamicTopicLookupService : DynamicTypeLookupService { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . - /// - public DynamicTopicLookupService() : base( - t => typeof(Topic).IsAssignableFrom(t) - ) { } + public DynamicTopicLookupService() : base( + t => typeof(Topic).IsAssignableFrom(t) + ) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/DynamicTopicViewModelLookupService.cs b/OnTopic/Lookup/DynamicTopicViewModelLookupService.cs index 052abe33..5d4884b0 100644 --- a/OnTopic/Lookup/DynamicTopicViewModelLookupService.cs +++ b/OnTopic/Lookup/DynamicTopicViewModelLookupService.cs @@ -4,26 +4,25 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: DYNAMIC TOPIC VIEW MODEL LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The will search all assemblies for s that end with +/// "TopicViewModel" +/// +public class DynamicTopicViewModelLookupService : DynamicTypeLookupService { /*============================================================================================================================ - | CLASS: DYNAMIC TOPIC VIEW MODEL LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The will search all assemblies for s that end with - /// "TopicViewModel" + /// Establishes a new instance of a . /// - public class DynamicTopicViewModelLookupService : DynamicTypeLookupService { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . - /// - public DynamicTopicViewModelLookupService() : base( - t => t.Name.EndsWith("ViewModel", StringComparison.OrdinalIgnoreCase) - ) { } + public DynamicTopicViewModelLookupService() : base( + t => t.Name.EndsWith("ViewModel", StringComparison.OrdinalIgnoreCase) + ) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/DynamicTypeLookupService.cs b/OnTopic/Lookup/DynamicTypeLookupService.cs index 208f3e54..ea969305 100644 --- a/OnTopic/Lookup/DynamicTypeLookupService.cs +++ b/OnTopic/Lookup/DynamicTypeLookupService.cs @@ -4,47 +4,46 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: DYNAMIC TYPE LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The will search all assemblies for instances that match a +/// predicate. +/// +public class DynamicTypeLookupService : StaticTypeLookupService { /*============================================================================================================================ - | CLASS: DYNAMIC TYPE LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The will search all assemblies for instances that match a - /// predicate. + /// Establishes a new instance of a based on a and, + /// optionally, a default object to return if none is specified. /// - public class DynamicTypeLookupService : StaticTypeLookupService { + /// The search condition to use to identify target classes. + public DynamicTypeLookupService(Func predicate) : base() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Find target classes \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a based on a and, - /// optionally, a default object to return if none is specified. - /// - /// The search condition to use to identify target classes. - public DynamicTypeLookupService(Func predicate) : base() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Find target classes - \-----------------------------------------------------------------------------------------------------------------------*/ - var matchedTypes = AppDomain - .CurrentDomain - .GetAssemblies() - .Where(a => !a.FullName.StartsWith("Microsoft", StringComparison.Ordinal) && !a.FullName.StartsWith("System", StringComparison.Ordinal)) - .SelectMany(t => t.GetTypes()) - .Where(t => t.IsClass && predicate(t)) - .OrderBy(t => t.Namespace?.StartsWith("OnTopic", StringComparison.Ordinal)) - .ToList(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Populate collection - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var type in matchedTypes) { - TryAdd(type); - } + var matchedTypes = AppDomain + .CurrentDomain + .GetAssemblies() + .Where(a => !(a.FullName?.StartsWith("Microsoft", StringComparison.Ordinal) ?? false) && !(a.FullName?.StartsWith("System", StringComparison.Ordinal) ?? false)) + .SelectMany(t => t.GetTypes()) + .Where(t => t.IsClass && predicate(t)) + .OrderBy(t => t.Namespace?.StartsWith("OnTopic", StringComparison.Ordinal)) + .ToList(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Populate collection + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var type in matchedTypes) { + TryAdd(type); } - } //Class -} //Namespace \ No newline at end of file + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/ITypeLookupService.cs b/OnTopic/Lookup/ITypeLookupService.cs index 830a18a5..4467437d 100644 --- a/OnTopic/Lookup/ITypeLookupService.cs +++ b/OnTopic/Lookup/ITypeLookupService.cs @@ -5,42 +5,41 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| INTERFACE: TYPE LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides an interface for looking up s by string. +/// +/// +/// Various areas of the OnTopic library require looking up s dynamically. For instance, the and the both determine whether or not there is a corresponding to the ContentType (though the former is looking for a , and the +/// latter is looking for a data transfer object). The provides a standard interface for +/// libraries capable of providing this functionality, allowing them to be injected into other services. +/// +public interface ITypeLookupService { /*============================================================================================================================ - | INTERFACE: TYPE LOOKUP SERVICE + | METHOD: LOOKUP \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides an interface for looking up s by string. + /// Attempts to retrieve a based on one or more supplied . /// /// - /// Various areas of the OnTopic library require looking up s dynamically. For instance, the and the both determine whether or not there is a corresponding to the ContentType (though the former is looking for a , and the - /// latter is looking for a data transfer object). The provides a standard interface for - /// libraries capable of providing this functionality, allowing them to be injected into other services. + /// No matter how many are entered, at most one will be returned. Each + /// subsequent is treated as a fallback in case the previous one cannot be located. As such, + /// the offers a way for callers to provide a prioritized list of fallbacks. This is useful + /// for scenarios where there are multiple accepted naming conventions, or there's a global default that can be accepted. /// - public interface ITypeLookupService { - - /*========================================================================================================================== - | METHOD: LOOKUP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to retrieve a based on one or more supplied . - /// - /// - /// No matter how many are entered, at most one will be returned. Each - /// subsequent is treated as a fallback in case the previous one cannot be located. As such, - /// the offers a way for callers to provide a prioritized list of fallbacks. This is useful - /// for scenarios where there are multiple accepted naming conventions, or there's a global default that can be accepted. - /// - /// - /// The name of the to retrieve. If multiple names are supplied, then the first match is returned. - /// - /// - /// A corresponding to one of the specified , if available. - /// - Type? Lookup(params string[] typeNames); + /// + /// The name of the to retrieve. If multiple names are supplied, then the first match is returned. + /// + /// + /// A corresponding to one of the specified , if available. + /// + Type? Lookup(params string[] typeNames); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/StaticTypeLookupService.cs b/OnTopic/Lookup/StaticTypeLookupService.cs index 28978bd3..38e46c61 100644 --- a/OnTopic/Lookup/StaticTypeLookupService.cs +++ b/OnTopic/Lookup/StaticTypeLookupService.cs @@ -5,168 +5,167 @@ \=============================================================================================================================*/ using System.Reflection; -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: STATIC TYPE LOOKUP SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The can be configured to provide a lookup of classes based on +/// its name. +/// +public class StaticTypeLookupService: ITypeLookupService { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly TypeCollection _typeCollection = new(); /*============================================================================================================================ - | CLASS: STATIC TYPE LOOKUP SERVICE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The can be configured to provide a lookup of classes based on - /// its name. + /// Establishes a new instance of a . Optionally accepts a list of + /// instances and a default value. /// - public class StaticTypeLookupService: ITypeLookupService { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly TypeCollection _typeCollection = new(); - - /*========================================================================================================================== - | CONSTRUCTOR + /// + /// Any instances submitted via should be unique by ; if they are not, they will be removed. + /// + /// The list of instances to expose as part of this service. + public StaticTypeLookupService( + IEnumerable? types = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Populate collection \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a . Optionally accepts a list of - /// instances and a default value. - /// - /// - /// Any instances submitted via should be unique by ; if they are not, they will be removed. - /// - /// The list of instances to expose as part of this service. - public StaticTypeLookupService( - IEnumerable? types = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Populate collection - \-----------------------------------------------------------------------------------------------------------------------*/ - if (types is not null) { - foreach (var type in types) { - if (!Contains(type)) { - Add(type); - } + if (types is not null) { + foreach (var type in types) { + if (!Contains(type)) { + Add(type); } } - } - /// - /// Establishes a new instance of a . Optionally accepts a list of - /// instances and a default value. - /// - /// - /// Any instances submitted via should be unique by ; if they are not, they will be removed. - /// - /// The list of instances to expose as part of this service. - /// The default type to return if no match can be found. Defaults to object. - [ExcludeFromCodeCoverage] - [Obsolete( - $"The DefaultType property has been removed. Fallbacks types can now be added to {nameof(Lookup)} directly.", - true - )] - public StaticTypeLookupService( - IEnumerable? types, - Type? defaultType - ) { - throw new NotImplementedException(); - } + } - /*========================================================================================================================== - | PROPERTY: DEFAULT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The default type to return in case cannot find a match. - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The DefaultType property has been removed. Fallbacks types can now be added to {nameof(Lookup)} directly.", - true - )] - public Type? DefaultType { get; } - - /*========================================================================================================================== - | METHOD: LOOKUP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public virtual Type? Lookup(params string[] typeNames) { - if (typeNames is not null) { - foreach (var typeName in typeNames) { - if (Contains(typeName)) { - return _typeCollection[typeName]; - } + /// + /// Establishes a new instance of a . Optionally accepts a list of + /// instances and a default value. + /// + /// + /// Any instances submitted via should be unique by ; if they are not, they will be removed. + /// + /// The list of instances to expose as part of this service. + /// The default type to return if no match can be found. Defaults to object. + [ExcludeFromCodeCoverage] + [Obsolete( + $"The DefaultType property has been removed. Fallbacks types can now be added to {nameof(Lookup)} directly.", + true + )] + public StaticTypeLookupService( + IEnumerable? types, + Type? defaultType + ) { + throw new NotImplementedException(); + } + + /*============================================================================================================================ + | PROPERTY: DEFAULT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The default type to return in case cannot find a match. + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"The DefaultType property has been removed. Fallbacks types can now be added to {nameof(Lookup)} directly.", + true + )] + public Type? DefaultType { get; } + + /*============================================================================================================================ + | METHOD: LOOKUP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public virtual Type? Lookup(params string[] typeNames) { + if (typeNames is not null) { + foreach (var typeName in typeNames) { + if (Contains(typeName)) { + return _typeCollection[typeName]; } } - return null; } + return null; + } - /*========================================================================================================================== - | METHOD: ADD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Adds a to the underlying collection. - /// - [ExcludeFromCodeCoverage] - protected void Add(Type type) => _typeCollection.Add(type); - - /*========================================================================================================================== - | METHOD: TRY ADD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if a with the given exists. If it does, returns false - /// ; otherwise, adds the and returns true. - /// - protected bool TryAdd(Type type) { - Contract.Requires(type, nameof(type)); - if (Contains(type.Name)) { - return false; - } - Add(type); - return true; + /*============================================================================================================================ + | METHOD: ADD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Adds a to the underlying collection. + /// + [ExcludeFromCodeCoverage] + protected void Add(Type type) => _typeCollection.Add(type); + + /*============================================================================================================================ + | METHOD: TRY ADD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if a with the given exists. If it does, returns false + /// ; otherwise, adds the and returns true. + /// + protected bool TryAdd(Type type) { + Contract.Requires(type, nameof(type)); + if (Contains(type.Name)) { + return false; } + Add(type); + return true; + } - /*========================================================================================================================== - | METHOD: ADD OR REPLACE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if a with the given exists. If it does, it is replaced. - /// Otherwise, it is added. - /// - protected void AddOrReplace(Type type) { - Contract.Requires(type, nameof(type)); - if (_typeCollection.Contains(type.Name)) { - Remove(type.Name); - } - Add(type); + /*============================================================================================================================ + | METHOD: ADD OR REPLACE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if a with the given exists. If it does, it is replaced. + /// Otherwise, it is added. + /// + protected void AddOrReplace(Type type) { + Contract.Requires(type, nameof(type)); + if (_typeCollection.Contains(type.Name)) { + Remove(type.Name); } + Add(type); + } - /*========================================================================================================================== - | METHOD: CONTAINS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if the underlying collection has a . - /// - /// The to located in the collection. - /// True if the exists in the collection. - [ExcludeFromCodeCoverage] - protected bool Contains(Type type) => _typeCollection.Contains(type); - - /// - /// Determines if the underlying collection has a with the provided . - /// - /// The key of the to located in the collection. - /// True if a with exists in the collection. - [ExcludeFromCodeCoverage] - protected bool Contains(string key) => _typeCollection.Contains(key); - - /*========================================================================================================================== - | METHOD: REMOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes a with the provided . - /// - [ExcludeFromCodeCoverage] - protected void Remove(string key) => _typeCollection.Remove(key); - - } //Class -} //Namespace \ No newline at end of file + /*============================================================================================================================ + | METHOD: CONTAINS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if the underlying collection has a . + /// + /// The to located in the collection. + /// True if the exists in the collection. + [ExcludeFromCodeCoverage] + protected bool Contains(Type type) => _typeCollection.Contains(type); + + /// + /// Determines if the underlying collection has a with the provided . + /// + /// The key of the to located in the collection. + /// True if a with exists in the collection. + [ExcludeFromCodeCoverage] + protected bool Contains(string key) => _typeCollection.Contains(key); + + /*============================================================================================================================ + | METHOD: REMOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes a with the provided . + /// + [ExcludeFromCodeCoverage] + protected void Remove(string key) => _typeCollection.Remove(key); + +} //Class \ No newline at end of file diff --git a/OnTopic/Lookup/TypeCollection.cs b/OnTopic/Lookup/TypeCollection.cs index 53ee0bfc..1b945f02 100644 --- a/OnTopic/Lookup/TypeCollection.cs +++ b/OnTopic/Lookup/TypeCollection.cs @@ -7,53 +7,52 @@ using System.Collections.ObjectModel; using System.Reflection; -namespace OnTopic.Lookup { +namespace OnTopic.Lookup; + +/*============================================================================================================================== +| CLASS: TYPE COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a of instances indexed by . +/// +internal sealed class TypeCollection : KeyedCollection { /*============================================================================================================================ - | CLASS: TYPE COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a of instances indexed by . + /// Instantiates a new . Optionally accepts an of instances to prepopulate the collection. /// - internal class TypeCollection : KeyedCollection { + internal TypeCollection(IEnumerable? types = null) : base(StringComparer.OrdinalIgnoreCase) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Populate collection \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new . Optionally accepts an of instances to prepopulate the collection. - /// - internal TypeCollection(IEnumerable? types = null) : base(StringComparer.OrdinalIgnoreCase) { - - /*---------------------------------------------------------------------------------------------------------------------- - | Populate collection - \---------------------------------------------------------------------------------------------------------------------*/ - if (types is not null) { - foreach (var type in types) { - if (!Contains(type.Name)) { - Add(type); - } + if (types is not null) { + foreach (var type in types) { + if (!Contains(type.Name)) { + Add(type); } } - } - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , returns the value that will act as the key—in this case, the - /// property. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - [ExcludeFromCodeCoverage] - protected override sealed string GetKeyForItem(Type item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Name; - } + } + + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , returns the value that will act as the key—in this case, the + /// property. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + [ExcludeFromCodeCoverage] + protected override sealed string GetKeyForItem(Type item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Name; + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/AssociationTypes.cs b/OnTopic/Mapping/Annotations/AssociationTypes.cs index 76090d96..fa9b92fb 100644 --- a/OnTopic/Mapping/Annotations/AssociationTypes.cs +++ b/OnTopic/Mapping/Annotations/AssociationTypes.cs @@ -5,104 +5,103 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ENUM: ASSOCIATION TYPES +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Allows one or more associations types to be specified. +/// +/// +/// +/// The and use the enum to +/// determine what associations should be mapped—or followed—as part of the mapping process. This helps constrain the +/// scope of the object graph to only include the data needed for a given view, or vice verse. That said, the enum can be used any place where the code needs to model multiple types of associations relevant +/// to the class and its view models. +/// +/// +/// The enum is similar to the enum—and, in fact, they +/// share several members. They differ in that exclusively models collections, +/// whereas also models other types of associations, such as , +/// and allows multiple associations to be selected. +/// +/// +[Flags] +public enum AssociationTypes { /*============================================================================================================================ - | ENUM: ASSOCIATION TYPES + | NONE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Allows one or more associations types to be specified. + /// Do not follow any associations. /// - /// - /// - /// The and use the enum to - /// determine what associations should be mapped—or followed—as part of the mapping process. This helps constrain the - /// scope of the object graph to only include the data needed for a given view, or vice verse. That said, the enum can be used any place where the code needs to model multiple types of associations relevant - /// to the class and its view models. - /// - /// - /// The enum is similar to the enum—and, in fact, they - /// share several members. They differ in that exclusively models collections, - /// whereas also models other types of associations, such as , - /// and allows multiple associations to be selected. - /// - /// - [Flags] - public enum AssociationTypes { + None = 0, - /*========================================================================================================================== - | NONE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Do not follow any associations. - /// - None = 0, - - /*========================================================================================================================== - | PARENTS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map references. - /// - Parents = 1, + /*============================================================================================================================ + | PARENTS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map references. + /// + Parents = 1, - /*========================================================================================================================== - | CHILDREN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map references, or properties marked as . - /// - Children = 1 << 1, + /*============================================================================================================================ + | CHILDREN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map references, or properties marked as . + /// + Children = 1 << 1, - /*========================================================================================================================== - | RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map references, or properties marked as . - /// - Relationships = 1 << 2, + /*============================================================================================================================ + | RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map references, or properties marked as . + /// + Relationships = 1 << 2, - /*========================================================================================================================== - | INCOMING RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map references, or properties marked as . - /// - IncomingRelationships = 1 << 3, + /*============================================================================================================================ + | INCOMING RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map references, or properties marked as . + /// + IncomingRelationships = 1 << 3, - /*========================================================================================================================== - | MAPPED COLLECTIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map to any collection on the with either the same property name, or which corresponds to the . - /// - /// - /// This allows mapping of custom collection, such as . - /// - MappedCollections = 1 << 4, + /*============================================================================================================================ + | MAPPED COLLECTIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map to any collection on the with either the same property name, or which corresponds to the . + /// + /// + /// This allows mapping of custom collection, such as . + /// + MappedCollections = 1 << 4, - /*========================================================================================================================== - | REFERENCES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map topic pointer references, such as . - /// - /// - /// By convention, types refer to a , , or property identifier ending in Id. - /// - References = 1 << 5, + /*============================================================================================================================ + | REFERENCES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map topic pointer references, such as . + /// + /// + /// By convention, types refer to a , , or property identifier ending in Id. + /// + References = 1 << 5, - /*========================================================================================================================== - | ALL - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Map all association types. - /// - All = Parents | Children | Relationships | IncomingRelationships | MappedCollections | References + /*============================================================================================================================ + | ALL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Map all association types. + /// + All = Parents | Children | Relationships | IncomingRelationships | MappedCollections | References - } //Enum -} //Namespace \ No newline at end of file +} //Enum \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/AttributeKeyAttribute.cs b/OnTopic/Mapping/Annotations/AttributeKeyAttribute.cs index dfa5a576..89de1d60 100644 --- a/OnTopic/Mapping/Annotations/AttributeKeyAttribute.cs +++ b/OnTopic/Mapping/Annotations/AttributeKeyAttribute.cs @@ -5,53 +5,52 @@ \=============================================================================================================================*/ using OnTopic.Collections.Specialized; -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: ATTRIBUTE KEY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a property should be mapped to a specific attributeKey in when calling . +/// +/// +/// By default, implementations will attempt to map the property of the target data +/// transfer object to a corresponding attribute of the same name on the source topic. This attribute instructs the +/// to instead look for a specified key. This allows the target property name to be +/// decoupled from the source attribute key. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class AttributeKeyAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: ATTRIBUTE KEY + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Flags that a property should be mapped to a specific attributeKey in when calling . + /// Annotates a property with the class by providing a (required) attribute key. /// - /// - /// By default, implementations will attempt to map the property of the target data - /// transfer object to a corresponding attribute of the same name on the source topic. This attribute instructs the - /// to instead look for a specified key. This allows the target property name to be - /// decoupled from the source attribute key. - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class AttributeKeyAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the class by providing a (required) attribute key. - /// - /// The key value of the attribute associated with the current property. - public AttributeKeyAttribute(string key) { - TopicFactory.ValidateKey(key, false); - Key = key; - } + /// The key value of the attribute associated with the current property. + public AttributeKeyAttribute(string key) { + TopicFactory.ValidateKey(key, false); + Key = key; + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the attribute key. - /// - public string Key { get; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the attribute key. + /// + public string Key { get; } - /*========================================================================================================================== - | PROPERTY: VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the attribute key. - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The Value property has been renamed to {nameof(Key)} for consistency", true)] - public string? Value { get; } + /*============================================================================================================================ + | PROPERTY: VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the attribute key. + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The Value property has been renamed to {nameof(Key)} for consistency", true)] + public string? Value { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/CollectionAttribute.cs b/OnTopic/Mapping/Annotations/CollectionAttribute.cs index 6ce3d9fd..725054f9 100644 --- a/OnTopic/Mapping/Annotations/CollectionAttribute.cs +++ b/OnTopic/Mapping/Annotations/CollectionAttribute.cs @@ -4,68 +4,68 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides the with instructions as to which collection to map to. +/// +/// +/// +/// By default, implementations will attempt to map a collection property to the first +/// collection it finds with a key that matches the property name. For example, if a property is named Categories +/// it will first look in for a relationship named Categories, then it will +/// search , then for a set of nested topics, and finally . +/// +/// +/// This attribute instructs the to instead look for a specified key. This allows the +/// target property name to be decoupled from the source's collection key. In addition, this attribute can be used to +/// specify the type of collection expected, which is useful if there might be ambiguity between collection names (for +/// example, if there is a with the same key as an ), which is not an uncommon scenario. +/// +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class CollectionAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides the with instructions as to which collection to map to. + /// Annotates a property with the by providing an . /// - /// - /// - /// By default, implementations will attempt to map a collection property to the first - /// collection it finds with a key that matches the property name. For example, if a property is named Categories - /// it will first look in for a relationship named Categories, then it will - /// search , then for a set of nested topics, and finally . - /// - /// - /// This attribute instructs the to instead look for a specified key. This allows the - /// target property name to be decoupled from the source's collection key. In addition, this attribute can be used to - /// specify the type of collection expected, which is useful if there might be ambiguity between collection names (for - /// example, if there is a with the same key as an ), which is not an uncommon scenario. - /// - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class CollectionAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the by providing an . - /// - /// The key value of the collection associated with the current property. - public CollectionAttribute(string key) { - TopicFactory.ValidateKey(key, false); - Key = key; - } + /// The key value of the collection associated with the current property. + public CollectionAttribute(string key) { + TopicFactory.ValidateKey(key, false); + Key = key; + } - /// - /// Annotates a property with the by providing the . - /// - /// Optional. The type of collection the collection is associated with. - public CollectionAttribute(CollectionType type = CollectionType.Any) { - Type = type; - } + /// + /// Annotates a property with the by providing the . + /// + /// Optional. The type of collection the collection is associated with. + public CollectionAttribute(CollectionType type = CollectionType.Any) { + Type = type; + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the collection key. - /// - public string? Key { get; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the collection key. + /// + public string? Key { get; } - /*========================================================================================================================== - | PROPERTY: TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the . - /// - public CollectionType Type { get; set; } + /*============================================================================================================================ + | PROPERTY: TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the . + /// + [SuppressMessage("Design", "CA1019:Define accessors for attribute arguments", Justification = "The setter is required to support setting Type via named argument syntax when Key is set via the constructor (e.g. [Collection(\"Key\", Type = CollectionType.Children)]).")] + public CollectionType Type { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/CollectionType.cs b/OnTopic/Mapping/Annotations/CollectionType.cs index 3595c589..d565b5b3 100644 --- a/OnTopic/Mapping/Annotations/CollectionType.cs +++ b/OnTopic/Mapping/Annotations/CollectionType.cs @@ -4,30 +4,29 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; - /*============================================================================================================================ - | ENUM: COLLECTION TYPE - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Enum that allows a collection to be specified. - /// - /// - /// This differs from , which allows multiple collections to be specified, and also - /// includes the as a source. - /// - public enum CollectionType { +/*============================================================================================================================== +| ENUM: COLLECTION TYPE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Enum that allows a collection to be specified. +/// +/// +/// This differs from , which allows multiple collections to be specified, and also +/// includes the as a source. +/// +public enum CollectionType { - #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - Any = 0, - Children = 1, - Relationship = 2, - IncomingRelationship = 3, - NestedTopics = 4, - MappedCollection = 5 + Any = 0, + Children = 1, + Relationship = 2, + IncomingRelationship = 3, + NestedTopics = 4, + MappedCollection = 5 - #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member - } //Enum -} //Namespace \ No newline at end of file +} //Enum \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/DisableMappingAttribute.cs b/OnTopic/Mapping/Annotations/DisableMappingAttribute.cs index 451a47b3..7ae6e436 100644 --- a/OnTopic/Mapping/Annotations/DisableMappingAttribute.cs +++ b/OnTopic/Mapping/Annotations/DisableMappingAttribute.cs @@ -5,30 +5,29 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Reverse; -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: DISABLE MAPPING ATTRIBUTE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Instructs the to ignore the decorated property. +/// +/// +/// The is useful when a property is not supported by the (as in the case of e.g. or ) +/// or is designated for special handling by the caller, and not intended to utilize the default mapping rules. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class DisableMappingAttribute: Attribute { /*============================================================================================================================ - | ATTRIBUTE: DISABLE MAPPING ATTRIBUTE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Instructs the to ignore the decorated property. + /// Annotates a property with the . /// - /// - /// The is useful when a property is not supported by the (as in the case of e.g. or ) - /// or is designated for special handling by the caller, and not intended to utilize the default mapping rules. - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class DisableMappingAttribute: Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the . - /// - public DisableMappingAttribute() { - } + public DisableMappingAttribute() { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/FilterByAttributeAttribute.cs b/OnTopic/Mapping/Annotations/FilterByAttributeAttribute.cs index bcf62974..b8c76e71 100644 --- a/OnTopic/Mapping/Annotations/FilterByAttributeAttribute.cs +++ b/OnTopic/Mapping/Annotations/FilterByAttributeAttribute.cs @@ -4,65 +4,64 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: FILTER BY ATTRIBUTE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a collection property should be filtered by a specified attributeKey and attributeValue. +/// +/// +/// By default, will add any corresponding topics to a collection, assuming they are +/// assignable to the collection's base type. With the [FilterByAttribute(attributeKey, attributeValue)] attribute, +/// the collection will instead be filtered to only those topics that have the specified attribute value assigned. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple=true, Inherited=true)] +public sealed class FilterByAttributeAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: FILTER BY ATTRIBUTE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Flags that a collection property should be filtered by a specified attributeKey and attributeValue. + /// Annotates a property with the class by providing a (required) attribute key + /// and value. /// - /// - /// By default, will add any corresponding topics to a collection, assuming they are - /// assignable to the collection's base type. With the [FilterByAttribute(attributeKey, attributeValue)] attribute, - /// the collection will instead be filtered to only those topics that have the specified attribute value assigned. - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple=true, Inherited=true)] - public sealed class FilterByAttributeAttribute : Attribute { + /// The key of the attribute to filter by. + /// The value of the attribute to filter by. + public FilterByAttributeAttribute(string key, string value) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the class by providing a (required) attribute key - /// and value. - /// - /// The key of the attribute to filter by. - /// The value of the attribute to filter by. - public FilterByAttributeAttribute(string key, string value) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicFactory.ValidateKey(key, false); - Contract.Requires( - !key.Equals("ContentType", StringComparison.OrdinalIgnoreCase), - "The ContentType is not stored as an attribute. To filter by ContentType, use [FilterByContentType] instead." - ); + TopicFactory.ValidateKey(key, false); + Contract.Requires( + !key.Equals("ContentType", StringComparison.OrdinalIgnoreCase), + "The ContentType is not stored as an attribute. To filter by ContentType, use [FilterByContentType] instead." + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Set properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Key = key; - Value = value; + /*-------------------------------------------------------------------------------------------------------------------------- + | Set properties + \-------------------------------------------------------------------------------------------------------------------------*/ + Key = key; + Value = value; - } + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the attribute key. - /// - public string Key { get; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the attribute key. + /// + public string Key { get; } - /*========================================================================================================================== - | PROPERTY: VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the attribute. - /// - public string Value { get; } + /*============================================================================================================================ + | PROPERTY: VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the attribute. + /// + public string Value { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/FilterByContentType.cs b/OnTopic/Mapping/Annotations/FilterByContentType.cs index 95564583..5729a54f 100644 --- a/OnTopic/Mapping/Annotations/FilterByContentType.cs +++ b/OnTopic/Mapping/Annotations/FilterByContentType.cs @@ -4,41 +4,40 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: FILTER BY CONTENT TYPE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a collection property should be filtered by a specified ContentType. +/// +/// +/// By default, will add any corresponding topic to a collection, assuming they are +/// assignable to the collection's base type. With the [FilterByContentType(contentType)] attribute, the collection +/// will instead be filtered to only those topics that have the specified content type. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple=true, Inherited=true)] +public sealed class FilterByContentTypeAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: FILTER BY CONTENT TYPE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Flags that a collection property should be filtered by a specified ContentType. + /// Annotates a property with the class by providing a (required) content type. /// - /// - /// By default, will add any corresponding topic to a collection, assuming they are - /// assignable to the collection's base type. With the [FilterByContentType(contentType)] attribute, the collection - /// will instead be filtered to only those topics that have the specified content type. - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple=true, Inherited=true)] - public sealed class FilterByContentTypeAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the class by providing a (required) content type. - /// - /// The content type to filter by. - public FilterByContentTypeAttribute(string contentType) { - TopicFactory.ValidateKey(contentType, false); - ContentType = contentType; - } + /// The content type to filter by. + public FilterByContentTypeAttribute(string contentType) { + TopicFactory.ValidateKey(contentType, false); + ContentType = contentType; + } - /*========================================================================================================================== - | PROPERTY: CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the content type. - /// - public string ContentType { get; } + /*============================================================================================================================ + | PROPERTY: CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the content type. + /// + public string ContentType { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/FlattenAttribute.cs b/OnTopic/Mapping/Annotations/FlattenAttribute.cs index 1ff72d49..86718cdf 100644 --- a/OnTopic/Mapping/Annotations/FlattenAttribute.cs +++ b/OnTopic/Mapping/Annotations/FlattenAttribute.cs @@ -4,35 +4,34 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: FLATTEN +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Instructs the to include all children of topics in a collection into a single, flat +/// list. +/// +/// +/// +/// By default, will populate all items in a collection—and, if the is defined, then also include their specified associations. The allows all subsequent children to not only be included, but to be elevated to a single list. This can be especially +/// useful when combined with e.g. as well as strongly-typed collections (e.g., +/// of a specific view model type), as it allows a list to provide, effectively, search results. +/// +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class FlattenAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: FLATTEN + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Instructs the to include all children of topics in a collection into a single, flat - /// list. + /// Annotates a property with the . /// - /// - /// - /// By default, will populate all items in a collection—and, if the is defined, then also include their specified associations. The allows all subsequent children to not only be included, but to be elevated to a single list. This can be especially - /// useful when combined with e.g. as well as strongly-typed collections (e.g., - /// of a specific view model type), as it allows a list to provide, effectively, search results. - /// - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class FlattenAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the . - /// - public FlattenAttribute() { - } + public FlattenAttribute() { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/IncludeAttribute.cs b/OnTopic/Mapping/Annotations/IncludeAttribute.cs index 7a0f6108..fb06d3d0 100644 --- a/OnTopic/Mapping/Annotations/IncludeAttribute.cs +++ b/OnTopic/Mapping/Annotations/IncludeAttribute.cs @@ -4,47 +4,46 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: INCLUDE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Instructs the to include the specified on that property. +/// +/// +/// +/// By default, will populate all associations on the initial data transfer object, +/// but won't continue to do so on associated objects. So, for instance, a Children collection will cause all +/// children to be loaded, but the mapper won't populate their Children (assuming that property is +/// available). +/// +/// +/// The overrides this behavior. If set, the will +/// populate the specified on the associated topics. +/// +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class IncludeAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: INCLUDE + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Instructs the to include the specified on that property. + /// Annotates a property with the by providing an . /// - /// - /// - /// By default, will populate all associations on the initial data transfer object, - /// but won't continue to do so on associated objects. So, for instance, a Children collection will cause all - /// children to be loaded, but the mapper won't populate their Children (assuming that property is - /// available). - /// - /// - /// The overrides this behavior. If set, the will - /// populate the specified on the associated topics. - /// - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class IncludeAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the by providing an . - /// - /// The specific associations that should be crawled. - public IncludeAttribute(AssociationTypes associations) { - Associations = associations; - } + /// The specific associations that should be crawled. + public IncludeAttribute(AssociationTypes associations) { + Associations = associations; + } - /*========================================================================================================================== - | PROPERTY: ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the type(s) of associations that should be recursed over. - /// - public AssociationTypes Associations { get; } + /*============================================================================================================================ + | PROPERTY: ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the type(s) of associations that should be recursed over. + /// + public AssociationTypes Associations { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/InheritAttribute.cs b/OnTopic/Mapping/Annotations/InheritAttribute.cs index b2f8f9a6..bad100ab 100644 --- a/OnTopic/Mapping/Annotations/InheritAttribute.cs +++ b/OnTopic/Mapping/Annotations/InheritAttribute.cs @@ -5,24 +5,23 @@ \=============================================================================================================================*/ using OnTopic.Collections.Specialized; -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; - /*============================================================================================================================ - | ATTRIBUTE: INHERIT - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Flags that a property should be inherit its value from when calling . - /// - /// - /// By default, implementations will call with the inheritFromParent parameter set to its default of - /// false. This attribute instructs it to instead set that parameter to true, which in turn causes the to crawl up the tree until a value is - /// found. This is useful when an attribute is expected to be inherited by all child topics. - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class InheritAttribute : Attribute { +/*============================================================================================================================== +| ATTRIBUTE: INHERIT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a property should be inherit its value from when calling . +/// +/// +/// By default, implementations will call with the inheritFromParent parameter set to its default of +/// false. This attribute instructs it to instead set that parameter to true, which in turn causes the to crawl up the tree until a value is +/// found. This is useful when an attribute is expected to be inherited by all child topics. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class InheritAttribute : Attribute { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/MapAsAttribute.cs b/OnTopic/Mapping/Annotations/MapAsAttribute.cs index 7fc3adaa..b4794b85 100644 --- a/OnTopic/Mapping/Annotations/MapAsAttribute.cs +++ b/OnTopic/Mapping/Annotations/MapAsAttribute.cs @@ -4,53 +4,52 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: MAP AS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides the with instructions as to which type to map an association to. +/// +/// +/// +/// By default, implementations will attempt to map an association—such as children, a +/// set of relationships, or a topic reference—to the view model associated with the of +/// the target topic. So, for example, if a Parent property points to a with a of Page, then it will look for a PageTopicViewModel or PageViewModel. If that +/// type cannot be found, or is incompatible with the property type, it will be ignored. +/// +/// +/// This attribute instead instructs the to map the association to a specific type, +/// independent of its . This can be useful if a model only needs a limited set of +/// attributes, and doesn't need to map the full list of properties on the default view model. It can also be useful if +/// e.g. a collection should have multiple unrelated types bound by a common interface. Both of these scenarios are common +/// when modeling a list of related topics, which may only require e.g. the Title and WebPath for each one. +/// It can also have a notable impact on performance by limiting the number of unnecessary properties that get mapped as +/// part of the request. +/// +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class MapAsAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: MAP AS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides the with instructions as to which type to map an association to. + /// Annotates a property with the by providing an . /// - /// - /// - /// By default, implementations will attempt to map an association—such as children, a - /// set of relationships, or a topic reference—to the view model associated with the of - /// the target topic. So, for example, if a Parent property points to a with a of Page, then it will look for a PageTopicViewModel or PageViewModel. If that - /// type cannot be found, or is incompatible with the property type, it will be ignored. - /// - /// - /// This attribute instead instructs the to map the association to a specific type, - /// independent of its . This can be useful if a model only needs a limited set of - /// attributes, and doesn't need to map the full list of properties on the default view model. It can also be useful if - /// e.g. a collection should have multiple unrelated types bound by a common interface. Both of these scenarios are common - /// when modeling a list of related topics, which may only require e.g. the Title and WebPath for each one. - /// It can also have a notable impact on performance by limiting the number of unnecessary properties that get mapped as - /// part of the request. - /// - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class MapAsAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the by providing an . - /// - /// The view model to map the association to. - public MapAsAttribute(Type type) { - Type = type; - } + /// The view model to map the association to. + public MapAsAttribute(Type type) { + Type = type; + } - /*========================================================================================================================== - | PROPERTY: TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the that the association should be mapped to. - /// - public Type Type { get; } + /*============================================================================================================================ + | PROPERTY: TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the that the association should be mapped to. + /// + public Type Type { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/MapToParentAttribute.cs b/OnTopic/Mapping/Annotations/MapToParentAttribute.cs index 6bbb95f9..63a80404 100644 --- a/OnTopic/Mapping/Annotations/MapToParentAttribute.cs +++ b/OnTopic/Mapping/Annotations/MapToParentAttribute.cs @@ -5,61 +5,55 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Reverse; -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: MAP TO PARENT +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Denotes that the properties on a view model should be mapped to the parent , optionally prefixed by +/// the provided key. +/// +/// +/// By default, complex property objects that don't map to known attributes (e.g., a compatible property) or associations +/// are bypassed. The informs the to treat the +/// properties of such complex objects as members of the parent . By default, these will be prefixed by +/// the name of the property that the complex object is assigned to. Optionally, however, this may be overwritten—including +/// by an empty string, if no prefix is desired. +/// +/// +/// As an example, imagine that a view model has a property BillingContact which is of type Contact. By +/// default, this will be ignored, since there's no obvious way to map it back to a . If it is annotated +/// with the , however, then its properties will be mapped to the parent topic. So, for +/// example, if the Contact class has a property named FirstName, then that will be saved to an attribute +/// named BillingContactFirstName. Alternatively, if a prefix of were provided, then that +/// same property would instead be mapped to FirstName—which could potentially introduce conflicts if there is also a +/// FirstName property on the parent object. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, Inherited=true)] +public sealed class MapToParentAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: MAP TO PARENT + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Denotes that the properties on a view model should be mapped to the parent , optionally prefixed by - /// the provided key. + /// Annotates a property with the class. /// - /// - /// By default, complex property objects that don't map to known attributes (e.g., a compatible property) or associations - /// are bypassed. The informs the to treat the - /// properties of such complex objects as members of the parent . By default, these will be prefixed by - /// the name of the property that the complex object is assigned to. Optionally, however, this may be overwritten—including - /// by an empty string, if no prefix is desired. - /// - /// - /// As an example, imagine that a view model has a property BillingContact which is of type Contact. By - /// default, this will be ignored, since there's no obvious way to map it back to a . If it is annotated - /// with the , however, then its properties will be mapped to the parent topic. So, for - /// example, if the Contact class has a property named FirstName, then that will be saved to an attribute - /// named BillingContactFirstName. Alternatively, if a prefix of were provided, then that - /// same property would instead be mapped to FirstName—which could potentially introduce conflicts if there is also a - /// FirstName property on the parent object. - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, Inherited=true)] - public sealed class MapToParentAttribute : Attribute { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private string? _attributePrefix; + public MapToParentAttribute() { } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the class. - /// - public MapToParentAttribute() { } - - /*========================================================================================================================== - | PROPERTY: ATTRIBUTE PREFIX - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The string that will be prepended to each property name when mapping to topic attributes. Defaults to the name of the - /// property being annotated. - /// - public string? AttributePrefix { - get => _attributePrefix; - set { - TopicFactory.ValidateKey(value, true); - _attributePrefix = value; - } + /*============================================================================================================================ + | PROPERTY: ATTRIBUTE PREFIX + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The string that will be prepended to each property name when mapping to topic attributes. Defaults to the name of the + /// property being annotated. + /// + public string? AttributePrefix { + get => field; + set { + TopicFactory.ValidateKey(value, true); + field = value; } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Annotations/MetadataAttribute.cs b/OnTopic/Mapping/Annotations/MetadataAttribute.cs index 1cfbfe0e..95e32b9a 100644 --- a/OnTopic/Mapping/Annotations/MetadataAttribute.cs +++ b/OnTopic/Mapping/Annotations/MetadataAttribute.cs @@ -4,42 +4,41 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: METADATA +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Flags that a property should be mapped to a list of metadata available in the Configuration namespace. +/// +/// +/// In the Topic Editor, the TopicLookup allows editors to select values from drop-down lists representing topics. +/// Those topics, by default, are stored in the Configuration:Metadata namespace. The metadata attribute allows a +/// strongly-typed reference to be created, thus pulling either a reference to a specific topic (in the case of a single +/// value property) or a collection of the metadata (in the case of a collection). +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] +public sealed class MetadataAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: METADATA + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Flags that a property should be mapped to a list of metadata available in the Configuration namespace. + /// Annotates a property with the class by providing a (required) key. /// - /// - /// In the Topic Editor, the TopicLookup allows editors to select values from drop-down lists representing topics. - /// Those topics, by default, are stored in the Configuration:Metadata namespace. The metadata attribute allows a - /// strongly-typed reference to be created, thus pulling either a reference to a specific topic (in the case of a single - /// value property) or a collection of the metadata (in the case of a collection). - /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] - public sealed class MetadataAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the class by providing a (required) key. - /// - /// The key represents the name of the Metadata topic that should be mapped to. - public MetadataAttribute(string key) { - TopicFactory.ValidateKey(key, false); - Key = key; - } + /// The key represents the name of the Metadata topic that should be mapped to. + public MetadataAttribute(string key) { + TopicFactory.ValidateKey(key, false); + Key = key; + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the key. - /// - public string Key { get; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the key. + /// + public string Key { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/CachedTopicMappingService.cs b/OnTopic/Mapping/CachedTopicMappingService.cs index 14f8965a..4b161207 100644 --- a/OnTopic/Mapping/CachedTopicMappingService.cs +++ b/OnTopic/Mapping/CachedTopicMappingService.cs @@ -6,212 +6,203 @@ using System.Collections.Concurrent; using OnTopic.Mapping.Annotations; -namespace OnTopic.Mapping { +namespace OnTopic.Mapping; + +/*============================================================================================================================== +| CLASS: CACHED TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a caching interface for an underlying , by caching entire mapped object +/// graphs based on the of the root topic. +/// +/// +/// The underlying to delegate topic mapping to. +/// +public class CachedTopicMappingService(ITopicMappingService topicMappingService) : ITopicMappingService { /*============================================================================================================================ - | CLASS: CACHED TOPIC MAPPING SERVICE + | PRIVATE VARIABLES \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a caching interface for an underlying , by caching entire mapped object - /// graphs based on the of the root topic. - /// - public class CachedTopicMappingService : ITopicMappingService { + private readonly ITopicMappingService _topicMappingService = Contract.Requires(topicMappingService); - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITopicMappingService _topicMappingService; + /*============================================================================================================================ + | ESTABLISH CACHE + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ConcurrentDictionary<(int, Type?, AssociationTypes), object> _cache = new(); - /*========================================================================================================================== - | ESTABLISH CACHE + /*============================================================================================================================ + | METHOD: MAP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ConcurrentDictionary<(int, Type?, AssociationTypes), object> _cache = new(); + if (topic is null) return null; - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure cache is populated \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a with required dependencies. - /// - public CachedTopicMappingService(ITopicMappingService topicMappingService) { - Contract.Requires(topicMappingService, "An instance of topicMappingService is required."); - _topicMappingService = topicMappingService; + var cacheKey = (topic.Id, (Type?)null, associations); + if(_cache.TryGetValue(cacheKey, out var viewModel)) { + return viewModel; } - /*========================================================================================================================== - | METHOD: MAP + /*-------------------------------------------------------------------------------------------------------------------------- + | Process result \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) return null; - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure cache is populated - \-----------------------------------------------------------------------------------------------------------------------*/ - var cacheKey = (topic.Id, (Type?)null, associations); - if(_cache.TryGetValue(cacheKey, out var viewModel)) { - return viewModel; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Process result - \-----------------------------------------------------------------------------------------------------------------------*/ - viewModel = await _topicMappingService.MapAsync(topic, associations).ConfigureAwait(false); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return (cached) result - \-----------------------------------------------------------------------------------------------------------------------*/ - if (viewModel is null) { - return null; - } - return CacheViewModel( - topic.ContentType, - viewModel, - cacheKey - ); + viewModel = await _topicMappingService.MapAsync(topic, associations).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return (cached) result + \-------------------------------------------------------------------------------------------------------------------------*/ + if (viewModel is null) { + return null; } + return CacheViewModel( + topic.ContentType, + viewModel, + cacheKey + ); - /*========================================================================================================================== - | METHOD: MAP (T) + } + + /*============================================================================================================================ + | METHOD: MAP (T) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class { - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) return null; - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure cache is populated - \-----------------------------------------------------------------------------------------------------------------------*/ - var cacheKey = (topic.Id, typeof(T), associations); - if (_cache.TryGetValue(cacheKey, out var viewModel)) { - return (T)viewModel; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Process result - \-----------------------------------------------------------------------------------------------------------------------*/ - viewModel = await _topicMappingService.MapAsync(topic, associations).ConfigureAwait(false); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return (cached) result - \-----------------------------------------------------------------------------------------------------------------------*/ - if (viewModel is null) { - return null; - } - return CacheViewModel( - topic.ContentType, - viewModel, - cacheKey - ) as T; + if (topic is null) return null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure cache is populated + \-------------------------------------------------------------------------------------------------------------------------*/ + var cacheKey = (topic.Id, typeof(T), associations); + if (_cache.TryGetValue(cacheKey, out var viewModel)) { + return (T)viewModel; } - /*========================================================================================================================== - | METHOD: MAP (OBJECTS) + /*-------------------------------------------------------------------------------------------------------------------------- + | Process result \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) return null; - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(target, nameof(target)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure cache is populated - \-----------------------------------------------------------------------------------------------------------------------*/ - var cacheKey = (topic.Id, target.GetType(), associations); - if (_cache.TryGetValue(cacheKey, out var viewModel)) { - return viewModel; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Process result - \-----------------------------------------------------------------------------------------------------------------------*/ - viewModel = await _topicMappingService.MapAsync(topic, associations).ConfigureAwait(false); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return (cached) result - \-----------------------------------------------------------------------------------------------------------------------*/ - if (viewModel is null) { - return null; - } - return CacheViewModel( - topic.ContentType, - viewModel, - cacheKey - ); + viewModel = await _topicMappingService.MapAsync(topic, associations).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return (cached) result + \-------------------------------------------------------------------------------------------------------------------------*/ + if (viewModel is null) { + return null; } + return CacheViewModel( + topic.ContentType, + viewModel, + cacheKey + ) as T; + + } + + /*============================================================================================================================ + | METHOD: MAP (OBJECTS) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic is null) return null; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(target, nameof(target)); - /*========================================================================================================================== - | METHOD: CACHE VIEW MODEL + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure cache is populated \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a view model, determines if it is appropriate to cache and, if so, adds it to the cache. Regardless, returns the - /// view model back to the consumer. - /// - /// - /// The internal will potentially add two entries to the cache for every view model. - /// - /// - /// The first will be bound to the , view model , and the mapped. - /// - /// - /// The second will assume a null , and can be used for scenarios where the is - /// not known—and, thus, assumed to be the default mapping. - /// - /// - /// In all cases, the must be greater than zero, to ensure that it's a saved entity (otherwise, - /// multiple distinct entities will have the default of -1). In addition, the following - /// conditions apply, respectively, to each of the caches: - /// - /// - /// The first must have a view model type that is not an , since it is meant to map to a specific - /// view model type. - /// - /// - /// The second will assume that the view model type of the naming convention {ContentType}TopicViewModel—i.e., - /// it is the default implementation for the given view model type, and not a specially cast version such as e.g., - /// NavigationTopicViewModel or TopicViewModel. - /// - /// - /// - /// The content type associated with the associated . - /// The view model object to cache; can be any POCO object. - /// A Tuple{T1, T2, T3} representing the cache key. - /// The . - private object? CacheViewModel(string contentType, object viewModel, (int, Type?, AssociationTypes) cacheKey) { - if (cacheKey.Item1 > 0 && cacheKey.Item2 is not null && !viewModel.GetType().Equals(typeof(object))) { - _cache.TryAdd(cacheKey, viewModel); - } - if (cacheKey.Item2 is not null) { - cacheKey = (cacheKey.Item1, null, cacheKey.Item3); - } - if ( - cacheKey.Item1 > 0 && ( - viewModel.GetType().Name == $"{contentType}ViewModel" || - viewModel.GetType().Name == $"{contentType}TopicViewModel" - ) - ) { - _cache.TryAdd(cacheKey, viewModel); - } + var cacheKey = (topic.Id, target.GetType(), associations); + if (_cache.TryGetValue(cacheKey, out var viewModel)) { return viewModel; } - } //Class -} //Namespace \ No newline at end of file + /*-------------------------------------------------------------------------------------------------------------------------- + | Process result + \-------------------------------------------------------------------------------------------------------------------------*/ + viewModel = await _topicMappingService.MapAsync(topic, associations).ConfigureAwait(false); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return (cached) result + \-------------------------------------------------------------------------------------------------------------------------*/ + if (viewModel is null) { + return null; + } + return CacheViewModel( + topic.ContentType, + viewModel, + cacheKey + ); + + } + + /*============================================================================================================================ + | METHOD: CACHE VIEW MODEL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a view model, determines if it is appropriate to cache and, if so, adds it to the cache. Regardless, returns the + /// view model back to the consumer. + /// + /// + /// The internal will potentially add two entries to the cache for every view model. + /// + /// + /// The first will be bound to the , view model , and the mapped. + /// + /// + /// The second will assume a null , and can be used for scenarios where the is + /// not known—and, thus, assumed to be the default mapping. + /// + /// + /// In all cases, the must be greater than zero, to ensure that it's a saved entity (otherwise, + /// multiple distinct entities will have the default of -1). In addition, the following + /// conditions apply, respectively, to each of the caches: + /// + /// + /// The first must have a view model type that is not an , since it is meant to map to a specific + /// view model type. + /// + /// + /// The second will assume that the view model type of the naming convention {ContentType}TopicViewModel—i.e., + /// it is the default implementation for the given view model type, and not a specially cast version such as e.g., + /// NavigationTopicViewModel or TopicViewModel. + /// + /// + /// + /// The content type associated with the associated . + /// The view model object to cache; can be any POCO object. + /// A Tuple{T1, T2, T3} representing the cache key. + /// The . + private object? CacheViewModel(string contentType, object viewModel, (int, Type?, AssociationTypes) cacheKey) { + if (cacheKey.Item1 > 0 && cacheKey.Item2 is not null && !viewModel.GetType().Equals(typeof(object))) { + _cache.TryAdd(cacheKey, viewModel); + } + if (cacheKey.Item2 is not null) { + cacheKey = (cacheKey.Item1, null, cacheKey.Item3); + } + if ( + cacheKey.Item1 > 0 && ( + viewModel.GetType().Name == $"{contentType}ViewModel" || + viewModel.GetType().Name == $"{contentType}TopicViewModel" + ) + ) { + _cache.TryAdd(cacheKey, viewModel); + } + return viewModel; + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Hierarchical/CachedHierarchicalTopicMappingService{T}.cs b/OnTopic/Mapping/Hierarchical/CachedHierarchicalTopicMappingService{T}.cs index bf769275..0b62d1c4 100644 --- a/OnTopic/Mapping/Hierarchical/CachedHierarchicalTopicMappingService{T}.cs +++ b/OnTopic/Mapping/Hierarchical/CachedHierarchicalTopicMappingService{T}.cs @@ -6,98 +6,97 @@ using System.Collections.Concurrent; using OnTopic.Models; -namespace OnTopic.Mapping.Hierarchical { +namespace OnTopic.Mapping.Hierarchical; + +/*============================================================================================================================== +| CLASS: CACHED HIERARCHICAL TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a wrapper to a implementation with support for caching. +/// +/// +/// By comparison to the , the will automatically cache the graph for each action that uses the protected method to construct +/// the graph. This is preferable over using e.g. the since the requires tight control over the shape of the graph. For instance, using a generic caching decorator for the mapping might +/// result in the edges of the graph being expanded due to other actions reusing cached instances (e.g., for page-level +/// navigation). To mitigate this, the handles top-level caching at +/// the level of the hierarchy's root. +/// +public class CachedHierarchicalTopicMappingService : IHierarchicalTopicMappingService + where T : class, IHierarchicalTopicViewModel, new() { /*============================================================================================================================ - | CLASS: CACHED HIERARCHICAL TOPIC MAPPING SERVICE + | STATIC VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ConcurrentDictionary _cache = new(); + private readonly IHierarchicalTopicMappingService _hierarchicalTopicMappingService; + + /*============================================================================================================================ + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a wrapper to a implementation with support for caching. + /// Initializes a new instance of a based on an underlying + /// implementation of a . /// - /// - /// By comparison to the , the will automatically cache the graph for each action that uses the protected method to construct - /// the graph. This is preferable over using e.g. the since the requires tight control over the shape of the graph. For instance, using a generic caching decorator for the mapping might - /// result in the edges of the graph being expanded due to other actions reusing cached instances (e.g., for page-level - /// navigation). To mitigate this, the handles top-level caching at - /// the level of the hierarchy's root. - /// - public class CachedHierarchicalTopicMappingService : IHierarchicalTopicMappingService - where T : class, IHierarchicalTopicViewModel, new() { + /// An instance of a . + public CachedHierarchicalTopicMappingService( + IHierarchicalTopicMappingService hierarchicalTopicMappingService + ) { + _hierarchicalTopicMappingService = hierarchicalTopicMappingService; + } - /*========================================================================================================================== - | STATIC VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ConcurrentDictionary _cache = new(); - private readonly IHierarchicalTopicMappingService _hierarchicalTopicMappingService; + /*============================================================================================================================ + | GET HIERARCHICAL ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Web") => + _hierarchicalTopicMappingService.GetHierarchicalRoot(currentTopic, fromRoot, defaultRoot); + + /*============================================================================================================================ + | GET ROOT VIEW MODEL (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task GetRootViewModelAsync( + Topic? sourceTopic, + int tiers = 1, + Func? validationDelegate = null + ) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle empty results \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a based on an underlying - /// implementation of a . - /// - /// An instance of a . - public CachedHierarchicalTopicMappingService( - IHierarchicalTopicMappingService hierarchicalTopicMappingService - ) { - _hierarchicalTopicMappingService = hierarchicalTopicMappingService; + if (sourceTopic is null) { + return await Task.FromResult(null).ConfigureAwait(false); } - /*========================================================================================================================== - | GET HIERARCHICAL ROOT + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle cache hits \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Web") => - _hierarchicalTopicMappingService.GetHierarchicalRoot(currentTopic, fromRoot, defaultRoot); + if (_cache.TryGetValue(sourceTopic.Id, out var dto)) { + return await Task.FromResult(dto).ConfigureAwait(false); + } - /*========================================================================================================================== - | GET ROOT VIEW MODEL (ASYNC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Cache and return new version \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task GetRootViewModelAsync( - Topic? sourceTopic, - int tiers = 1, - Func? validationDelegate = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle empty results - \-----------------------------------------------------------------------------------------------------------------------*/ - if (sourceTopic is null) { - return await Task.FromResult(null).ConfigureAwait(false); - } + var viewModel = await GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false); + return _cache.GetOrAdd(sourceTopic.Id, viewModel); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle cache hits - \-----------------------------------------------------------------------------------------------------------------------*/ - if (_cache.TryGetValue(sourceTopic.Id, out var dto)) { - return await Task.FromResult(dto).ConfigureAwait(false); - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Cache and return new version - \-----------------------------------------------------------------------------------------------------------------------*/ - var viewModel = await GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false); - return _cache.GetOrAdd(sourceTopic.Id, viewModel); - - } - - /*========================================================================================================================== - | GET VIEW MODEL (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task GetViewModelAsync( - Topic? sourceTopic, - int tiers = 1, - Func? validationDelegate = null - ) => - await _hierarchicalTopicMappingService.GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false); + /*============================================================================================================================ + | GET VIEW MODEL (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task GetViewModelAsync( + Topic? sourceTopic, + int tiers = 1, + Func? validationDelegate = null + ) => + await _hierarchicalTopicMappingService.GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Hierarchical/HierarchicalTopicMappingService{T}.cs b/OnTopic/Mapping/Hierarchical/HierarchicalTopicMappingService{T}.cs index 130d74c2..ed66124e 100644 --- a/OnTopic/Mapping/Hierarchical/HierarchicalTopicMappingService{T}.cs +++ b/OnTopic/Mapping/Hierarchical/HierarchicalTopicMappingService{T}.cs @@ -7,209 +7,199 @@ using OnTopic.Models; using OnTopic.Repositories; -namespace OnTopic.Mapping.Hierarchical { +namespace OnTopic.Mapping.Hierarchical; + +/*============================================================================================================================== +| CLASS: NAVIGATION MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Implements a service that maps a limited-hierarchy of topics to a generic class representing the core properties +/// associated with a navigation item. +/// +/// +/// +/// Ideally, this functionality would be baked directly into the implementations, but +/// this introduces a number of technical issues that make this unfeasible for now. Instead, the handles this functionality for special cases, such as navigation, where +/// e.g. the full recursion of the is not preferrable for functional or performance +/// reasons. +/// +/// +/// In order to remain view model agnostic, the does not assume that a +/// particular view model will be used, and instead accepts a generic argument for any view model that implements the +/// interface . +/// +/// +/// A view model implementing the interface. +/// +/// The for loading topics to map. +/// +/// +/// The for mapping individual instances. +/// +public class HierarchicalTopicMappingService(ITopicRepository topicRepository, ITopicMappingService topicMappingService) + : IHierarchicalTopicMappingService + where T : class, IHierarchicalTopicViewModel, new() +{ /*============================================================================================================================ - | CLASS: NAVIGATION MAPPING SERVICE + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ITopicMappingService _topicMappingService = topicMappingService; + + /*============================================================================================================================ + | TOPIC REPOSITORY \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Implements a service that maps a limited-hierarchy of topics to a generic class representing the core properties - /// associated with a navigation item. + /// Provides a reference to the Topic Repository in order to gain arbitrary access to the entire topic graph. /// - /// - /// - /// Ideally, this functionality would be baked directly into the implementations, but - /// this introduces a number of technical issues that make this unfeasible for now. Instead, the handles this functionality for special cases, such as navigation, where - /// e.g. the full recursion of the is not preferrable for functional or performance - /// reasons. - /// - /// - /// In order to remain view model agnostic, the does not assume that a - /// particular view model will be used, and instead accepts a generic argument for any view model that implements the - /// interface . - /// - /// - /// A view model implementing the interface. - public class HierarchicalTopicMappingService - : IHierarchicalTopicMappingService - where T : class, IHierarchicalTopicViewModel, new() - { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// The TopicRepository associated with the controller. + private ITopicRepository TopicRepository { get; } = topicRepository; + + /*============================================================================================================================ + | GET HIERARCHICAL ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Root:Web") { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ITopicMappingService _topicMappingService; + var navigationRootTopic = currentTopic; - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle default, if necessary \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a with necessary dependencies. - /// - /// A topic controller for loading OnTopic views. - public HierarchicalTopicMappingService( - ITopicRepository topicRepository, - ITopicMappingService topicMappingService - ) { - TopicRepository = topicRepository; - _topicMappingService = topicMappingService; + if (navigationRootTopic is null) { + Contract.Assume(!String.IsNullOrEmpty(defaultRoot), nameof(defaultRoot)); + navigationRootTopic = TopicRepository.Load(defaultRoot, currentTopic); } - /*========================================================================================================================== - | TOPIC REPOSITORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the Topic Repository in order to gain arbitrary access to the entire topic graph. - /// - /// The TopicRepository associated with the controller. - private ITopicRepository TopicRepository { get; } - - /*========================================================================================================================== - | GET HIERARCHICAL ROOT + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle error state \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Root:Web") { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var navigationRootTopic = currentTopic; - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle default, if necessary - \-----------------------------------------------------------------------------------------------------------------------*/ - if (navigationRootTopic is null) { - Contract.Assume(!String.IsNullOrEmpty(defaultRoot), nameof(defaultRoot)); - navigationRootTopic = TopicRepository.Load(defaultRoot, currentTopic); - } + if (navigationRootTopic is null) { + throw new ArgumentOutOfRangeException( + $"Neither the current route nor the {nameof(defaultRoot)} parameter of {defaultRoot} could be resolved to a topic." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle error state - \-----------------------------------------------------------------------------------------------------------------------*/ - if (navigationRootTopic is null) { - throw new ArgumentOutOfRangeException( - $"Neither the current route nor the {nameof(defaultRoot)} parameter of {defaultRoot} could be resolved to a topic." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Find navigation root + \-------------------------------------------------------------------------------------------------------------------------*/ + while (navigationRootTopic is not null && DistanceFromRoot(navigationRootTopic) > fromRoot) { + navigationRootTopic = navigationRootTopic.Parent; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Find navigation root - \-----------------------------------------------------------------------------------------------------------------------*/ - while (navigationRootTopic is not null && DistanceFromRoot(navigationRootTopic) > fromRoot) { - navigationRootTopic = navigationRootTopic.Parent; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return navigation root + \-------------------------------------------------------------------------------------------------------------------------*/ + return navigationRootTopic; - /*------------------------------------------------------------------------------------------------------------------------ - | Return navigation root - \-----------------------------------------------------------------------------------------------------------------------*/ - return navigationRootTopic; + } + /*============================================================================================================================ + | DISTANCE FROM ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A helper function that will determine how far a given topic is from the root of a tree. + /// + /// The to pull the values from. + private static int DistanceFromRoot(Topic sourceTopic) { + var distance = 1; + while (sourceTopic.Parent is not null) { + sourceTopic = sourceTopic.Parent; + distance++; } + return distance; + } - /*========================================================================================================================== - | DISTANCE FROM ROOT + /*============================================================================================================================ + | GET ROOT VIEW MODEL (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public virtual async Task GetRootViewModelAsync( + Topic? sourceTopic, + int tiers = 1, + Func? validationDelegate = null + ) => await GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false); + + /*============================================================================================================================ + | GET VIEW MODEL (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task GetViewModelAsync( + Topic? sourceTopic, + int tiers = 1, + Func? validationDelegate = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate preconditions \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A helper function that will determine how far a given topic is from the root of a tree. - /// - /// The to pull the values from. - private static int DistanceFromRoot(Topic sourceTopic) { - var distance = 1; - while (sourceTopic.Parent is not null) { - sourceTopic = sourceTopic.Parent; - distance++; - } - return distance; + tiers--; + if (sourceTopic is null) { + return null; } - /*========================================================================================================================== - | GET ROOT VIEW MODEL (ASYNC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public virtual async Task GetRootViewModelAsync( - Topic? sourceTopic, - int tiers = 1, - Func? validationDelegate = null - ) => await GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false); - - /*========================================================================================================================== - | GET VIEW MODEL (ASYNC) + var taskQueue = new List>(); + var children = new List(); + var viewModel = (T?)null; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish default delegate \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task GetViewModelAsync( - Topic? sourceTopic, - int tiers = 1, - Func? validationDelegate = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate preconditions - \-----------------------------------------------------------------------------------------------------------------------*/ - tiers--; - if (sourceTopic is null) { - return null; - } + validationDelegate ??= (Topic) => true; - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var taskQueue = new List>(); - var children = new List(); - var viewModel = (T?)null; - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish default delegate - \-----------------------------------------------------------------------------------------------------------------------*/ - validationDelegate ??= (Topic) => true; - - /*------------------------------------------------------------------------------------------------------------------------ - | Map object - \-----------------------------------------------------------------------------------------------------------------------*/ - viewModel = await _topicMappingService.MapAsync(sourceTopic, AssociationTypes.None).ConfigureAwait(false); - - Contract.Assume( - viewModel, - $"The 'ITopicMappingService' failed to return a {typeof(T)} model for the '{sourceTopic.GetUniqueKey()}' topic." - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Map object + \-------------------------------------------------------------------------------------------------------------------------*/ + viewModel = await _topicMappingService.MapAsync(sourceTopic, AssociationTypes.None).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Request mapping of children - \-----------------------------------------------------------------------------------------------------------------------*/ - if (tiers >= 0 && viewModel.Children.Count == 0) { - foreach (var topic in sourceTopic.Children.Where(t => t.IsVisible() && validationDelegate(t))) { - taskQueue.Add(GetViewModelAsync(topic, tiers, validationDelegate)); - } + Contract.Assume( + viewModel, + $"The 'ITopicMappingService' failed to return a {typeof(T)} model for the '{sourceTopic.GetUniqueKey()}' topic." + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Request mapping of children + \-------------------------------------------------------------------------------------------------------------------------*/ + if (tiers >= 0 && viewModel.Children.Count == 0) { + foreach (var topic in sourceTopic.Children.Where(t => t.IsVisible() && validationDelegate(t))) { + taskQueue.Add(GetViewModelAsync(topic, tiers, validationDelegate)); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Process children - \-----------------------------------------------------------------------------------------------------------------------*/ - while (taskQueue.Count > 0 && viewModel.Children.Count == 0) { - var dtoTask = await Task.WhenAny(taskQueue).ConfigureAwait(false); - var dto = await dtoTask.ConfigureAwait(false); - taskQueue.Remove(dtoTask); - if (dto is not null) { - children.Add(dto); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Process children + \-------------------------------------------------------------------------------------------------------------------------*/ + while (taskQueue.Count > 0 && viewModel.Children.Count == 0) { + var dtoTask = await Task.WhenAny(taskQueue).ConfigureAwait(false); + var dto = await dtoTask.ConfigureAwait(false); + taskQueue.Remove(dtoTask); + if (dto is not null) { + children.Add(dto); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Add children to view model - \-----------------------------------------------------------------------------------------------------------------------*/ - if (viewModel.Children.Count == 0) { - lock (viewModel) { - if (viewModel.Children.Count == 0) { - children.ForEach(c => viewModel.Children.Add(c)); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Add children to view model + \-------------------------------------------------------------------------------------------------------------------------*/ + if (viewModel.Children.Count == 0) { + lock (viewModel) { + if (viewModel.Children.Count == 0) { + children.ForEach(c => viewModel.Children.Add(c)); } } - - /*------------------------------------------------------------------------------------------------------------------------ - | Return view model - \-----------------------------------------------------------------------------------------------------------------------*/ - return viewModel; } - } //Class -} //Namespace \ No newline at end of file + /*-------------------------------------------------------------------------------------------------------------------------- + | Return view model + \-------------------------------------------------------------------------------------------------------------------------*/ + return viewModel; + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Hierarchical/IHierarchicalTopicMappingService{T}.cs b/OnTopic/Mapping/Hierarchical/IHierarchicalTopicMappingService{T}.cs index cd907c1d..550f3c71 100644 --- a/OnTopic/Mapping/Hierarchical/IHierarchicalTopicMappingService{T}.cs +++ b/OnTopic/Mapping/Hierarchical/IHierarchicalTopicMappingService{T}.cs @@ -5,98 +5,98 @@ \=============================================================================================================================*/ using OnTopic.Models; -namespace OnTopic.Mapping.Hierarchical { +namespace OnTopic.Mapping.Hierarchical; + +/*============================================================================================================================== +| INTERFACE: HIERARCHICAL TOPIC MAPPING SERVICE +\=============================================================================================================================*/ +/// +/// Provides an interface for a service that maps a limited-hierarchy of topics to a generic class representing the core +/// properties associated with a navigation item. +/// +/// +/// +/// Ideally, this functionality would be baked directly into the implementations, but +/// this introduces a number of technical issues that make this unfeasible for now. Instead, the handles this functionality for special cases, such as navigation, where +/// e.g. the full recursion of the is not preferrable for functional or performance +/// reasons. +/// +/// +/// In order to remain view model agnostic, the does not assume that a +/// particular view model will be used, and instead accepts a generic argument for any view model that implements the +/// interface . +/// +/// +/// A view model implementing the interface. +public interface IHierarchicalTopicMappingService where T : class, IHierarchicalTopicViewModel, new() { /*============================================================================================================================ - | INTERFACE: HIERARCHICAL TOPIC MAPPING SERVICE - \===========================================================================================================================*/ + | GET HIERARCHICAL ROOT + \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides an interface for a service that maps a limited-hierarchy of topics to a generic class representing the core - /// properties associated with a navigation item. + /// Given a , will crawl up the current tree and retrieve the topic that is tiers down from the root of the topic graph. /// /// - /// - /// Ideally, this functionality would be baked directly into the implementations, but - /// this introduces a number of technical issues that make this unfeasible for now. Instead, the handles this functionality for special cases, such as navigation, where - /// e.g. the full recursion of the is not preferrable for functional or performance - /// reasons. - /// - /// - /// In order to remain view model agnostic, the does not assume that a - /// particular view model will be used, and instead accepts a generic argument for any view model that implements the - /// interface . - /// + /// Often, a will need a reference to a topic at a certain level, which + /// represents the root of the the site. For instance, if the hierarchy represents a site's navigation, and the navigation + /// starts at Root:Web, then the navigation is one level from the root (i.e., =1). This, + /// however, should not be hard-coded in case a site has multiple roots. For instance, if a page is under Root:Library + /// then that should be the navigation root. This method provides support for these scenarios. /// - /// A view model implementing the interface. - public interface IHierarchicalTopicMappingService where T : class, IHierarchicalTopicViewModel, new() { - - /*========================================================================================================================== - | GET HIERARCHICAL ROOT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , will crawl up the current tree and retrieve the topic that is tiers down from the root of the topic graph. - /// - /// - /// Often, a will need a reference to a topic at a certain level, which - /// represents the root of the the site. For instance, if the hierarchy represents a site's navigation, and the navigation - /// starts at Root:Web, then the navigation is one level from the root (i.e., =1). This, - /// however, should not be hard-coded in case a site has multiple roots. For instance, if a page is under Root:Library - /// then that should be the navigation root. This method provides support for these scenarios. - /// - /// The to start from. - /// The distance that the navigation root should be from the root of the topic graph. - /// If a root cannot be identified, the default root that should be returned. - Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Web"); + /// The to start from. + /// The distance that the navigation root should be from the root of the topic graph. + /// If a root cannot be identified, the default root that should be returned. + Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Web"); - /*========================================================================================================================== - | GET ROOT VIEW MODEL (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , maps a , as well as of - /// . Optionally excludes instance with the - /// ContentType of PageGroup. - /// - /// - /// In the out-of-the-box implementation, and provide the same functionality. It is recommended that - /// actions call , however, as it allows - /// implementers the flexibility to differentiate between the root view model (which the client application will be - /// binding to) and any child view models (which the client application may optionally iterate over). - /// - /// The to pull the values from. - /// Determines how many tiers of children should be included in the graph. - /// - /// A delegate for validating whether a (and it's descendants) should be included in the returned - /// hierarchy. - /// - Task GetRootViewModelAsync( - Topic? sourceTopic, - int tiers = 1, - Func? validationDelegate = null - ); + /*============================================================================================================================ + | GET ROOT VIEW MODEL (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , maps a , as well as of + /// . Optionally excludes instance with the + /// ContentType of PageGroup. + /// + /// + /// In the out-of-the-box implementation, and provide the same functionality. It is recommended that + /// actions call , however, as it allows + /// implementers the flexibility to differentiate between the root view model (which the client application will be + /// binding to) and any child view models (which the client application may optionally iterate over). + /// + /// The to pull the values from. + /// Determines how many tiers of children should be included in the graph. + /// + /// A delegate for validating whether a (and it's descendants) should be included in the returned + /// hierarchy. + /// + Task GetRootViewModelAsync( + Topic? sourceTopic, + int tiers = 1, + Func? validationDelegate = null + ); - /*========================================================================================================================== - | GET VIEW MODEL (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , maps a , as well as of - /// . Optionally excludes instance with the - /// ContentType of PageGroup. - /// - /// The to pull the values from. - /// Determines how many tiers of children should be included in the graph. - /// - /// A delegate for validating whether a (and it's descendants) should be included in the returned - /// hierarchy. - /// - Task GetViewModelAsync( - Topic? sourceTopic, - int tiers = 1, - Func? validationDelegate = null - ); + /*============================================================================================================================ + | GET VIEW MODEL (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , maps a , as well as of + /// . Optionally excludes instance with the + /// ContentType of PageGroup. + /// + /// The to pull the values from. + /// Determines how many tiers of children should be included in the graph. + /// + /// A delegate for validating whether a (and it's descendants) should be included in the returned + /// hierarchy. + /// + Task GetViewModelAsync( + Topic? sourceTopic, + int tiers = 1, + Func? validationDelegate = null + ); - } //Interface -} //Class \ No newline at end of file +} //Interface +//Class \ No newline at end of file diff --git a/OnTopic/Mapping/ITopicMappingService.cs b/OnTopic/Mapping/ITopicMappingService.cs index 70e5a6c3..24e39a4a 100644 --- a/OnTopic/Mapping/ITopicMappingService.cs +++ b/OnTopic/Mapping/ITopicMappingService.cs @@ -5,74 +5,73 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Annotations; -namespace OnTopic.Mapping { +namespace OnTopic.Mapping; + +/*============================================================================================================================== +| INTERFACE: TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The interface provides an abstraction for mapping instances to +/// Data Transfer Objects, such as View Models. +/// +public interface ITopicMappingService { /*============================================================================================================================ - | INTERFACE: TOPIC MAPPING SERVICE + | METHOD: MAP (DYNAMIC) \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The interface provides an abstraction for mapping instances to - /// Data Transfer Objects, such as View Models. + /// Given a topic, will identify any View Models named, by convention, "{ContentType}ViewModel" and populate them + /// according to the rules of the mapping implementation. /// - public interface ITopicMappingService { - - /*========================================================================================================================== - | METHOD: MAP (DYNAMIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a topic, will identify any View Models named, by convention, "{ContentType}ViewModel" and populate them - /// according to the rules of the mapping implementation. - /// - /// - /// - /// Because the class is using reflection to determine the target View Models, the return type is . - /// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views - /// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known - /// upfront, and it's imperative that it be strongly typed, then prefer . - /// - /// - /// Because the target object is being dynamically constructed, it must implement a default constructor. - /// - /// - /// The entity to derive the data from. - /// Determines what associations the mapping should include, if any. - /// An instance of the dynamically determined View Model with properties appropriately mapped. - Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All); + /// + /// + /// Because the class is using reflection to determine the target View Models, the return type is . + /// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views + /// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known + /// upfront, and it's imperative that it be strongly typed, then prefer . + /// + /// + /// Because the target object is being dynamically constructed, it must implement a default constructor. + /// + /// + /// The entity to derive the data from. + /// Determines what associations the mapping should include, if any. + /// An instance of the dynamically determined View Model with properties appropriately mapped. + Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All); - /*========================================================================================================================== - | METHOD: MAP (GENERIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a topic and a generic type, will instantiate a new instance of the generic type and populate it according to the - /// rules of the mapping implementation. - /// - /// - /// - /// Because the target object is being dynamically constructed, it must implement a default constructor. - /// - /// - /// The entity to derive the data from. - /// Determines what associations the mapping should include, if any. - /// - /// An instance of the requested View Model with properties appropriately mapped. - /// - Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class; + /*============================================================================================================================ + | METHOD: MAP (GENERIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a topic and a generic type, will instantiate a new instance of the generic type and populate it according to the + /// rules of the mapping implementation. + /// + /// + /// + /// Because the target object is being dynamically constructed, it must implement a default constructor. + /// + /// + /// The entity to derive the data from. + /// Determines what associations the mapping should include, if any. + /// + /// An instance of the requested View Model with properties appropriately mapped. + /// + Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class; - /*========================================================================================================================== - | METHOD: MAP (INSTANCES) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a topic and an instance of a data transfer object, will populate the latter according to the rules of the - /// mapping implementation. - /// - /// The entity to derive the data from. - /// The data transfer object to populate. - /// Determines what associations the mapping should include, if any. - /// - /// An instance of the requested View Model instance with properties appropriately mapped. - /// - Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All); + /*============================================================================================================================ + | METHOD: MAP (INSTANCES) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a topic and an instance of a data transfer object, will populate the latter according to the rules of the + /// mapping implementation. + /// + /// The entity to derive the data from. + /// The data transfer object to populate. + /// Determines what associations the mapping should include, if any. + /// + /// An instance of the requested View Model instance with properties appropriately mapped. + /// + Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All); - } //Interface -} //Namespace \ No newline at end of file +} //Interface \ No newline at end of file diff --git a/OnTopic/Mapping/Internal/AssociationMap.cs b/OnTopic/Mapping/Internal/AssociationMap.cs index a4a49569..54826e68 100644 --- a/OnTopic/Mapping/Internal/AssociationMap.cs +++ b/OnTopic/Mapping/Internal/AssociationMap.cs @@ -5,43 +5,42 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Annotations; -namespace OnTopic.Mapping.Internal { +namespace OnTopic.Mapping.Internal; + +/*============================================================================================================================== +| CLASS: ASSOCIATION MAP +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a mapping of the relationship between and . +/// +/// +/// While the and enumerations are distinct, there are times +/// when a single needs to be related to an item in the collection of . This mapping makes that feasible. +/// +static internal class AssociationMap { /*============================================================================================================================ - | CLASS: ASSOCIATION MAP + | CONSTRUCTOR (STATIC) \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a mapping of the relationship between and . - /// - /// - /// While the and enumerations are distinct, there are times - /// when a single needs to be related to an item in the collection of . This mapping makes that feasible. - /// - static internal class AssociationMap { - - /*========================================================================================================================== - | CONSTRUCTOR (STATIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - static AssociationMap() { - - var mappings = new Dictionary { - { CollectionType.Any, AssociationTypes.None }, - { CollectionType.Children, AssociationTypes.Children }, - { CollectionType.Relationship, AssociationTypes.Relationships }, - { CollectionType.NestedTopics, AssociationTypes.None }, - { CollectionType.MappedCollection, AssociationTypes.MappedCollections }, - { CollectionType.IncomingRelationship, AssociationTypes.IncomingRelationships } - }; - - Mappings = mappings; - - } - - /*========================================================================================================================== - | PROPERTY: MAPPINGS - \-------------------------------------------------------------------------------------------------------------------------*/ - static internal Dictionary Mappings { get; } - - } //Class -} //Namespace \ No newline at end of file + static AssociationMap() { + + var mappings = new Dictionary { + { CollectionType.Any, AssociationTypes.None }, + { CollectionType.Children, AssociationTypes.Children }, + { CollectionType.Relationship, AssociationTypes.Relationships }, + { CollectionType.NestedTopics, AssociationTypes.None }, + { CollectionType.MappedCollection, AssociationTypes.MappedCollections }, + { CollectionType.IncomingRelationship, AssociationTypes.IncomingRelationships } + }; + + Mappings = mappings; + + } + + /*============================================================================================================================ + | PROPERTY: MAPPINGS + \---------------------------------------------------------------------------------------------------------------------------*/ + static internal Dictionary Mappings { get; } + +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Internal/ItemConfiguration.cs b/OnTopic/Mapping/Internal/ItemConfiguration.cs index 00cacb95..06a6da48 100644 --- a/OnTopic/Mapping/Internal/ItemConfiguration.cs +++ b/OnTopic/Mapping/Internal/ItemConfiguration.cs @@ -10,469 +10,468 @@ using OnTopic.Internal.Reflection; using OnTopic.Mapping.Annotations; -namespace OnTopic.Mapping.Internal { +namespace OnTopic.Mapping.Internal; + +/*============================================================================================================================== +| CLASS: ITEM CONFIGURATION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Evaluates the of a given instance for a or , and exposes known s through a set of property values. +/// +/// +/// +/// The class is utilized by implementations of to +/// facilitate the mapping of source instances to Data Transfer Objects (DTOs), such as View Models. +/// The attribute values provide hints to the mapping service that help manage how the mapping occurs. +/// +/// +/// For example, by default a property on a DTO class will be mapped to a property or attribute of the same name on the +/// source . If the is attached to a property on the DTO, however, +/// then the will instead use the value defined by that attribute, thus allowing a +/// property on the DTO to be aliased to a different property or attribute name on the source . +/// +/// +internal sealed class ItemConfiguration { /*============================================================================================================================ - | CLASS: ITEM CONFIGURATION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Evaluates the of a given instance for a or , and exposes known s through a set of property values. + /// Given an instance, exposes a set of properties associated with known + /// instances. /// - /// - /// - /// The class is utilized by implementations of to - /// facilitate the mapping of source instances to Data Transfer Objects (DTOs), such as View Models. - /// The attribute values provide hints to the mapping service that help manage how the mapping occurs. - /// - /// - /// For example, by default a property on a DTO class will be mapped to a property or attribute of the same name on the - /// source . If the is attached to a property on the DTO, however, - /// then the will instead use the value defined by that attribute, thus allowing a - /// property on the DTO to be aliased to a different property or attribute name on the source . - /// - /// - internal class ItemConfiguration { + /// + /// The instance associated with this . + /// + internal ItemConfiguration(ItemMetadata itemMetadata) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Set backing properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given an instance, exposes a set of properties associated with known - /// instances. - /// - /// - /// The instance associated with this . - /// - internal ItemConfiguration(ItemMetadata itemMetadata) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Set backing properties - \-----------------------------------------------------------------------------------------------------------------------*/ - CustomAttributes = itemMetadata.CustomAttributes; - - /*------------------------------------------------------------------------------------------------------------------------ - | Set default values - \-----------------------------------------------------------------------------------------------------------------------*/ - AttributeKey = itemMetadata.Name; - AttributePrefix = ""; - DefaultValue = null; - InheritValue = false; - CollectionKey = AttributeKey; - CollectionType = CollectionType.Any; - IncludeAssociations = AssociationTypes.None; - MetadataKey = null; - DisableMapping = false; - AttributeFilters = new(); - FlattenChildren = false; + CustomAttributes = itemMetadata.CustomAttributes; - /*------------------------------------------------------------------------------------------------------------------------ - | Attributes: Retrieve basic attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - GetAttributeValue( a => MapAs = a.Type); - GetAttributeValue( a => DefaultValue = a.Value); - GetAttributeValue( a => InheritValue = true); - GetAttributeValue( a => AttributeKey = a.Key); - GetAttributeValue( a => MapToParent = true); - GetAttributeValue( a => AttributePrefix += (a.AttributePrefix?? AttributeKey)); - GetAttributeValue( a => IncludeAssociations = a.Associations); - GetAttributeValue( a => FlattenChildren = true); - GetAttributeValue( a => MetadataKey = a.Key); - GetAttributeValue( a => DisableMapping = true); - GetAttributeValue( a => ContentTypeFilter = a.ContentType); - - /*------------------------------------------------------------------------------------------------------------------------ - | Attributes: Determine collection key and type - \-----------------------------------------------------------------------------------------------------------------------*/ - GetAttributeValue( - a => { - CollectionKey = a.Key ?? CollectionKey; - CollectionType = a.Type; - } - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Set default values + \-------------------------------------------------------------------------------------------------------------------------*/ + AttributeKey = itemMetadata.Name; + AttributePrefix = ""; + DefaultValue = null; + InheritValue = false; + CollectionKey = AttributeKey; + CollectionType = CollectionType.Any; + IncludeAssociations = AssociationTypes.None; + MetadataKey = null; + DisableMapping = false; + AttributeFilters = new(); + FlattenChildren = false; - if (CollectionKey.Equals("Children", StringComparison.OrdinalIgnoreCase)) { - CollectionType = CollectionType.Children; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Attributes: Retrieve basic attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + GetAttributeValue( a => MapAs = a.Type); + GetAttributeValue( a => DefaultValue = a.Value); + GetAttributeValue( a => InheritValue = true); + GetAttributeValue( a => AttributeKey = a.Key); + GetAttributeValue( a => MapToParent = true); + GetAttributeValue( a => AttributePrefix += (a.AttributePrefix?? AttributeKey)); + GetAttributeValue( a => IncludeAssociations = a.Associations); + GetAttributeValue( a => FlattenChildren = true); + GetAttributeValue( a => MetadataKey = a.Key); + GetAttributeValue( a => DisableMapping = true); + GetAttributeValue( a => ContentTypeFilter = a.ContentType); - /*------------------------------------------------------------------------------------------------------------------------ - | Attributes: Set attribute filters - \-----------------------------------------------------------------------------------------------------------------------*/ - var filterByAttributes = CustomAttributes.OfType(); - if (filterByAttributes is not null && filterByAttributes.Any()) { - foreach (var filter in filterByAttributes) { - AttributeFilters.Add(filter.Key, filter.Value); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Attributes: Determine collection key and type + \-------------------------------------------------------------------------------------------------------------------------*/ + GetAttributeValue( + a => { + CollectionKey = a.Key ?? CollectionKey; + CollectionType = a.Type; } + ); + if (CollectionKey.Equals("Children", StringComparison.OrdinalIgnoreCase)) { + CollectionType = CollectionType.Children; } - /*========================================================================================================================== - | PROPERTY: CUSTOM ATTRIBUTES + /*-------------------------------------------------------------------------------------------------------------------------- + | Attributes: Set attribute filters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The that the current is associated with. - /// - protected IEnumerable CustomAttributes { get; } + var filterByAttributes = CustomAttributes.OfType().ToArray(); + if (filterByAttributes.Length > 0) { + foreach (var filter in filterByAttributes) { + AttributeFilters.Add(filter.Key, filter.Value); + } + } - /*========================================================================================================================== - | PROPERTY: ATTRIBUTE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The name of the corresponding attribute in the instance. Defaults to the property name - /// on DTO. - /// - /// - /// - /// By default, a property on a DTO class will be mapped to a property or attribute of the same name on the source . If the is attached to a property on the DTO, however, then the - /// will instead use the value defined by that attribute, thus allowing a property on - /// the DTO to be aliased to a different property or attribute name on the source . - /// - /// - /// The property corresponds to the property. It - /// can be assigned by decorating a DTO property with e.g. [AttributeKey("AlternateAttributeKey")]. - /// - /// - internal string AttributeKey { get; set; } + } - /*========================================================================================================================== - | PROPERTY: MAP AS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The type of the DTO that an association should be mapped to. - /// - /// - /// By default, the will map associations to a view model corresponding to the target - /// 's . E.g., if the target is Page - /// , then it will map the association to a PageTopicViewModel or PageViewModel. The - /// configuration allows this type to be overridden for a specific association. This can be useful if the current model - /// only needs a few attributes from the associated topic, or for scenarios where multiple different content types might - /// be included in a collection, but should be unified via a common interface. Both are common, for instance, when a view - /// needs to display a list of links to related pages, and thus just needs e.g. the Title and WebPath for - /// each association. - /// - internal Type? MapAs { get; set; } + /*============================================================================================================================ + | PROPERTY: CUSTOM ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The that the current is associated with. + /// + protected IEnumerable CustomAttributes { get; } - /*========================================================================================================================== - | PROPERTY: MAP TO PARENT? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not a complex object's properties should be mapped to the topic's attributes. - /// - /// - /// - /// By default, properties representing complex classes won't be mapped unless they correspond to a narrow set of types - /// (such as ). The allows this behavior to be overwritten. - /// When this occurs, the properties of the referenced object are treated as attributes on the topic. - /// - /// - /// The property corresponds to the attribute. It can be - /// assigned by decorating a DTO property with e.g. [MapToParent]. Optionally, an attribute prefix can be - /// provided; see for details. - /// - /// - internal bool MapToParent { get; set; } + /*============================================================================================================================ + | PROPERTY: ATTRIBUTE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The name of the corresponding attribute in the instance. Defaults to the property name + /// on DTO. + /// + /// + /// + /// By default, a property on a DTO class will be mapped to a property or attribute of the same name on the source . If the is attached to a property on the DTO, however, then the + /// will instead use the value defined by that attribute, thus allowing a property on + /// the DTO to be aliased to a different property or attribute name on the source . + /// + /// + /// The property corresponds to the property. It + /// can be assigned by decorating a DTO property with e.g. [AttributeKey("AlternateAttributeKey")]. + /// + /// + internal string AttributeKey { get; set; } - /*========================================================================================================================== - | PROPERTY: ATTRIBUTE PREFIX - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The prefix to apply to the ; used when mapping complex objects. - /// - /// - /// - /// By default, properties representing complex classes won't be mapped unless they correspond to a narrow set of types - /// (such as ). The allows this behavior to be overwritten. - /// When this occurs, the properties of the referenced object are treated as attributes on the topic. To distinguish - /// them from properties on the parent topic, they are (by default) prefixed with the name of the property that the - /// complex object is assigned to. Optionally, however, this can be overridden, or even set to . In the latter case, the properties on the child object will be treated as synonymous with the - /// properties on the parent object. And, in fact, the same property could even be applied to both the child - /// object and the parent object—though this probably doesn't make much sense from a modeling perspective. - /// - /// - /// Be aware that the should only apply to actual attributes on the mapped entity; it is not intended to be applied to e.g. collections or associations. - /// - /// - /// The property corresponds to the - /// property. It can be assigned by decorating a DTO property with e.g. [MapToParent(AttributePrefix - /// = "AlternateAttributeKey")]. - /// - /// - /// The can be compounded. That is, if a complex object is added to another complex object - /// using , then the will reflect the combination of - /// those two prefixes. This allows potentially very deep object models. - /// - /// - internal string? AttributePrefix { get; set; } + /*============================================================================================================================ + | PROPERTY: MAP AS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The type of the DTO that an association should be mapped to. + /// + /// + /// By default, the will map associations to a view model corresponding to the target + /// 's . E.g., if the target is Page + /// , then it will map the association to a PageTopicViewModel or PageViewModel. The + /// configuration allows this type to be overridden for a specific association. This can be useful if the current model + /// only needs a few attributes from the associated topic, or for scenarios where multiple different content types might + /// be included in a collection, but should be unified via a common interface. Both are common, for instance, when a view + /// needs to display a list of links to related pages, and thus just needs e.g. the Title and WebPath for + /// each association. + /// + internal Type? MapAs { get; set; } - /*========================================================================================================================== - | PROPERTY: DEFAULT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The default value to use if no corresponding value can be determined from the source . - /// - /// - /// The property corresponds to the property. It can - /// be assigned by decorating a DTO property with e.g. [DefaultValue("DefaultValue")]. - /// - internal object? DefaultValue { get; set; } + /*============================================================================================================================ + | PROPERTY: MAP TO PARENT? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not a complex object's properties should be mapped to the topic's attributes. + /// + /// + /// + /// By default, properties representing complex classes won't be mapped unless they correspond to a narrow set of types + /// (such as ). The allows this behavior to be overwritten. + /// When this occurs, the properties of the referenced object are treated as attributes on the topic. + /// + /// + /// The property corresponds to the attribute. It can be + /// assigned by decorating a DTO property with e.g. [MapToParent]. Optionally, an attribute prefix can be + /// provided; see for details. + /// + /// + internal bool MapToParent { get; set; } - /*========================================================================================================================== - | PROPERTY: INHERIT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether the value should be inherited from if the value cannot be identified - /// on the source . - /// - /// - /// - /// The configuration is only applicable if the value is pulled from the collection. This is the equivalent to calling the method with an InheritFromParent parameter set to - /// True. - /// - /// - /// The property corresponds to the being set on a given - /// property. It can be assigned by decorating a model property with e.g. [Inherit]. - /// - /// - internal bool InheritValue { get; set; } + /*============================================================================================================================ + | PROPERTY: ATTRIBUTE PREFIX + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The prefix to apply to the ; used when mapping complex objects. + /// + /// + /// + /// By default, properties representing complex classes won't be mapped unless they correspond to a narrow set of types + /// (such as ). The allows this behavior to be overwritten. + /// When this occurs, the properties of the referenced object are treated as attributes on the topic. To distinguish + /// them from properties on the parent topic, they are (by default) prefixed with the name of the property that the + /// complex object is assigned to. Optionally, however, this can be overridden, or even set to . In the latter case, the properties on the child object will be treated as synonymous with the + /// properties on the parent object. And, in fact, the same property could even be applied to both the child + /// object and the parent object—though this probably doesn't make much sense from a modeling perspective. + /// + /// + /// Be aware that the should only apply to actual attributes on the mapped entity; it is not intended to be applied to e.g. collections or associations. + /// + /// + /// The property corresponds to the + /// property. It can be assigned by decorating a DTO property with e.g. [MapToParent(AttributePrefix + /// = "AlternateAttributeKey")]. + /// + /// + /// The can be compounded. That is, if a complex object is added to another complex object + /// using , then the will reflect the combination of + /// those two prefixes. This allows potentially very deep object models. + /// + /// + internal string? AttributePrefix { get; set; } - /*========================================================================================================================== - | PROPERTY: COLLECTION KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The name of the collection that a collection should map to. Defaults to the property name on DTO. - /// - /// - /// - /// By default, a collection property on a model class will be mapped to a corresponding collection of the same name. - /// So, for instance, if the property on the model class is called Cousins then the will search , , , and, finally, for an object named Cousins. If - /// the is set, however, then that value is used instead, thus allowing the property on the - /// model to be aliased to a different collection name on the source . - /// - /// - /// The property corresponds to the property. It - /// can be assigned by decorating a model property with e.g. [Collection("AlternateCollectionKey")]. - /// - /// - internal string CollectionKey { get; set; } + /*============================================================================================================================ + | PROPERTY: DEFAULT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The default value to use if no corresponding value can be determined from the source . + /// + /// + /// The property corresponds to the property. It can + /// be assigned by decorating a DTO property with e.g. [DefaultValue("DefaultValue")]. + /// + internal object? DefaultValue { get; set; } - /*========================================================================================================================== - | PROPERTY: COLLECTION TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines the type of collection that a collection property corresponds to. - /// - /// - /// - /// By default, a collection property on a model class will attempt to find a match from, in order, , , , and, finally, . If the is set, however, then the will only map the collection to a collection of that type. This can be valuable when the might be ambiguous between multiple collections. - /// - /// - /// The property corresponds to the property. It - /// can be assigned by decorating a model property with e.g. [Collection("AlternateCollectionKey", CollectionType. - /// Children)]. - /// - /// - internal CollectionType CollectionType { get; set; } + /*============================================================================================================================ + | PROPERTY: INHERIT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether the value should be inherited from if the value cannot be identified + /// on the source . + /// + /// + /// + /// The configuration is only applicable if the value is pulled from the collection. This is the equivalent to calling the method with an InheritFromParent parameter set to + /// True. + /// + /// + /// The property corresponds to the being set on a given + /// property. It can be assigned by decorating a model property with e.g. [Inherit]. + /// + /// + internal bool InheritValue { get; set; } - /*========================================================================================================================== - | PROPERTY: INCLUDE ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines which associations, if any, the service should be included for the current - /// property. - /// - /// - /// - /// By default, the all associations will be mapped on the target model, unless the caller specifies otherwise. On any - /// associated models, however, only will be mapped. So, if a mapped model has - /// a collection for children, relationships, or even a parent property then any associations on those models - /// will not be mapped. This behavior can be changed by specifying the flag, which - /// allows one or multiple associations to be specified for a given property. - /// - /// - /// The property corresponds to the - /// property. It can be assigned by decorating a model property with e.g. [Include(Relationships.Children)]. - /// - /// - internal AssociationTypes IncludeAssociations { get; set; } + /*============================================================================================================================ + | PROPERTY: COLLECTION KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The name of the collection that a collection should map to. Defaults to the property name on DTO. + /// + /// + /// + /// By default, a collection property on a model class will be mapped to a corresponding collection of the same name. + /// So, for instance, if the property on the model class is called Cousins then the will search , , , and, finally, for an object named Cousins. If + /// the is set, however, then that value is used instead, thus allowing the property on the + /// model to be aliased to a different collection name on the source . + /// + /// + /// The property corresponds to the property. It + /// can be assigned by decorating a model property with e.g. [Collection("AlternateCollectionKey")]. + /// + /// + internal string CollectionKey { get; set; } - /*========================================================================================================================== - | PROPERTY: METADATA KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instructs the to pull in a collection of mapped topics from a corresponding - /// collection in the Root:Configuration:Metadata namespace of the Topic graph. - /// - /// - /// - /// Sometimes, a value will be associated with lookup s found in the - /// Root:Configuration:Metadata namespace of the Topic graph. In these cases, it can be useful to include the - /// full set of metadata on the mapped DTO so the view has access to it. For instance, a DTO may include a States - /// property which includes a full list of all states potentially associated with a , which might be - /// used in the user interface to provide filtering of e.g. child s. - /// - /// - /// The property corresponds to the property. It can be - /// assigned by decorating a DTO property with e.g. [Metadata("States")]. - /// - /// - internal string? MetadataKey { get; set; } + /*============================================================================================================================ + | PROPERTY: COLLECTION TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines the type of collection that a collection property corresponds to. + /// + /// + /// + /// By default, a collection property on a model class will attempt to find a match from, in order, , , , and, finally, . If the is set, however, then the will only map the collection to a collection of that type. This can be valuable when the might be ambiguous between multiple collections. + /// + /// + /// The property corresponds to the property. It + /// can be assigned by decorating a model property with e.g. [Collection("AlternateCollectionKey", CollectionType. + /// Children)]. + /// + /// + internal CollectionType CollectionType { get; set; } - /*========================================================================================================================== - | PROPERTY: FLATTEN CHILDREN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether all descendants in a collection should be included in the collection. - /// - /// - /// - /// By default, only stored directly in a source collection will be included in the target - /// collection on a DTO class. If the property is set, however, then all descendants of - /// those s are also included. So, for instance, if a Children property is decorated - /// with the , then not only will the be included, but any - /// grandchildren, great-grandchildren, etc. will be included. - /// - /// - /// When is specified, implementations are expected to - /// apply all other constraints. For instance, if the target collection is strongly typed, then only DTOs that exhibit - /// polymorphic compatibility with that type will be included (i.e., DTOs of the same or a derived type as the target - /// collection). Similarly, any will be applied to each of the descendants. Finally, if - /// the target collection has a unique constraint (e.g., due to implementing ) - /// then any items that would constitute a duplicate will be filtered out without raising an exception. This - /// can thus allow the method to be used to represent unique search results within a - /// graph. - /// - /// - /// The property corresponds to the being set on a given - /// property. It can be assigned by decorating a DTO property with e.g. [Flatten]. - /// - /// - internal bool FlattenChildren { get; set; } + /*============================================================================================================================ + | PROPERTY: INCLUDE ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines which associations, if any, the service should be included for the current + /// property. + /// + /// + /// + /// By default, the all associations will be mapped on the target model, unless the caller specifies otherwise. On any + /// associated models, however, only will be mapped. So, if a mapped model has + /// a collection for children, relationships, or even a parent property then any associations on those models + /// will not be mapped. This behavior can be changed by specifying the flag, which + /// allows one or multiple associations to be specified for a given property. + /// + /// + /// The property corresponds to the + /// property. It can be assigned by decorating a model property with e.g. [Include(Relationships.Children)]. + /// + /// + internal AssociationTypes IncludeAssociations { get; set; } - /*========================================================================================================================== - | PROPERTY: DISABLE MAPPING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether the property is intended to be mapped to the corresponding . - /// - /// - /// - /// The property corresponds to the being set on a - /// given property. It can be assigned by decorating a DTO property with e.g. [DisableMapping]. - /// - /// - internal bool DisableMapping { get; set; } + /*============================================================================================================================ + | PROPERTY: METADATA KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Instructs the to pull in a collection of mapped topics from a corresponding + /// collection in the Root:Configuration:Metadata namespace of the Topic graph. + /// + /// + /// + /// Sometimes, a value will be associated with lookup s found in the + /// Root:Configuration:Metadata namespace of the Topic graph. In these cases, it can be useful to include the + /// full set of metadata on the mapped DTO so the view has access to it. For instance, a DTO may include a States + /// property which includes a full list of all states potentially associated with a , which might be + /// used in the user interface to provide filtering of e.g. child s. + /// + /// + /// The property corresponds to the property. It can be + /// assigned by decorating a DTO property with e.g. [Metadata("States")]. + /// + /// + internal string? MetadataKey { get; set; } - /*========================================================================================================================== - | PROPERTY: CONTENT TYPE FILTER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a ContentType which can optionally be used to filter a collection. - /// - /// - /// - /// By default, all s in a source collection (e.g., ) will be included in - /// a corresponding collection on the DTO (assuming the mapped DTO is compatible with the collection type). If the - /// is set, however, then each will be evaluated to confirm that - /// it is of that content type. - /// - /// - /// The property corresponds to the property. It can be assigned by decorating a DTO property with e.g. [FilterByContentType("Page")] - /// . - /// - /// - internal string? ContentTypeFilter { get; set; } + /*============================================================================================================================ + | PROPERTY: FLATTEN CHILDREN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether all descendants in a collection should be included in the collection. + /// + /// + /// + /// By default, only stored directly in a source collection will be included in the target + /// collection on a DTO class. If the property is set, however, then all descendants of + /// those s are also included. So, for instance, if a Children property is decorated + /// with the , then not only will the be included, but any + /// grandchildren, great-grandchildren, etc. will be included. + /// + /// + /// When is specified, implementations are expected to + /// apply all other constraints. For instance, if the target collection is strongly typed, then only DTOs that exhibit + /// polymorphic compatibility with that type will be included (i.e., DTOs of the same or a derived type as the target + /// collection). Similarly, any will be applied to each of the descendants. Finally, if + /// the target collection has a unique constraint (e.g., due to implementing ) + /// then any items that would constitute a duplicate will be filtered out without raising an exception. This + /// can thus allow the method to be used to represent unique search results within a + /// graph. + /// + /// + /// The property corresponds to the being set on a given + /// property. It can be assigned by decorating a DTO property with e.g. [Flatten]. + /// + /// + internal bool FlattenChildren { get; set; } - /*========================================================================================================================== - | PROPERTY: ATTRIBUTE FILTERS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a list of Key/Value pairs corresponding to which can optionally - /// be used to filter a collection. - /// - /// - /// - /// By default, all s in a source collection (e.g., ) will be included in - /// a corresponding collection on the DTO (assuming the mapped DTO is compatible with the collection type). If any - /// are set, however, then each will be evaluated to confirm that it - /// satisfies the conditions of those filters. - /// - /// - /// The property corresponds to the and - /// properties. It can be assigned by decorating a DTO property with e.g. - /// [FilterByAttribute("Company", "Ignia")]. Multiple s can be assigned - /// to a single property, thus allowing each item in a collection to be filtered by multiple values. - /// - /// - internal Dictionary AttributeFilters { get; } + /*============================================================================================================================ + | PROPERTY: DISABLE MAPPING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether the property is intended to be mapped to the corresponding . + /// + /// + /// + /// The property corresponds to the being set on a + /// given property. It can be assigned by decorating a DTO property with e.g. [DisableMapping]. + /// + /// + internal bool DisableMapping { get; set; } - /*========================================================================================================================== - | METHOD: GET COMPOSITE ATTRIBUTE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the current , and, optionally, the supplied . - /// - /// - /// The current mapping operation's attribute prefix to be prepended to the . - /// - /// - /// The composite attribute key, based on and, optionally, the supplied . - /// - internal string GetCompositeAttributeKey(string? attributePrefix) => $"{attributePrefix}{AttributeKey}"; + /*============================================================================================================================ + | PROPERTY: CONTENT TYPE FILTER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a ContentType which can optionally be used to filter a collection. + /// + /// + /// + /// By default, all s in a source collection (e.g., ) will be included in + /// a corresponding collection on the DTO (assuming the mapped DTO is compatible with the collection type). If the + /// is set, however, then each will be evaluated to confirm that + /// it is of that content type. + /// + /// + /// The property corresponds to the property. It can be assigned by decorating a DTO property with e.g. [FilterByContentType("Page")] + /// . + /// + /// + internal string? ContentTypeFilter { get; set; } - /*========================================================================================================================== - | METHOD: SATISFIES ATTRIBUTE FILTERS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , determines whether or not the satisfy all defined on the property. - /// - /// - /// - internal bool SatisfiesAttributeFilters(Topic source) => - AttributeFilters.All(f => - source?.Attributes?.GetValue(f.Key, "")?.Equals(f.Value, StringComparison.OrdinalIgnoreCase)?? false - ); + /*============================================================================================================================ + | PROPERTY: ATTRIBUTE FILTERS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a list of Key/Value pairs corresponding to which can optionally + /// be used to filter a collection. + /// + /// + /// + /// By default, all s in a source collection (e.g., ) will be included in + /// a corresponding collection on the DTO (assuming the mapped DTO is compatible with the collection type). If any + /// are set, however, then each will be evaluated to confirm that it + /// satisfies the conditions of those filters. + /// + /// + /// The property corresponds to the and + /// properties. It can be assigned by decorating a DTO property with e.g. + /// [FilterByAttribute("Company", "Ignia")]. Multiple s can be assigned + /// to a single property, thus allowing each item in a collection to be filtered by multiple values. + /// + /// + internal Dictionary AttributeFilters { get; } - /*========================================================================================================================== - | PRIVATE: GET ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function identifies whether a exists in the and, if so, - /// returns the value. - /// - /// An type to evaluate. - private T? GetAttribute() where T : Attribute => - CustomAttributes.OfType().FirstOrDefault(); + /*============================================================================================================================ + | METHOD: GET COMPOSITE ATTRIBUTE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves the current , and, optionally, the supplied . + /// + /// + /// The current mapping operation's attribute prefix to be prepended to the . + /// + /// + /// The composite attribute key, based on and, optionally, the supplied . + /// + internal string GetCompositeAttributeKey(string? attributePrefix) => $"{attributePrefix}{AttributeKey}"; - /*========================================================================================================================== - | PRIVATE: GET ATTRIBUTE VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function evaluates an attribute and then, if it exists, executes an to process the - /// results. - /// - /// An type to evaluate. - /// The to execute on the attribute. - private void GetAttributeValue(Action action) where T : Attribute { - var attribute = GetAttribute(); - if (attribute is not null) { - action(attribute); - } + /*============================================================================================================================ + | METHOD: SATISFIES ATTRIBUTE FILTERS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , determines whether or not the satisfy all defined on the property. + /// + /// + /// + internal bool SatisfiesAttributeFilters(Topic source) => + AttributeFilters.All(f => + source?.Attributes?.GetValue(f.Key, "")?.Equals(f.Value, StringComparison.OrdinalIgnoreCase)?? false + ); + + /*============================================================================================================================ + | PRIVATE: GET ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function identifies whether a exists in the and, if so, + /// returns the value. + /// + /// An type to evaluate. + private T? GetAttribute() where T : Attribute => + CustomAttributes.OfType().FirstOrDefault(); + + /*============================================================================================================================ + | PRIVATE: GET ATTRIBUTE VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function evaluates an attribute and then, if it exists, executes an to process the + /// results. + /// + /// An type to evaluate. + /// The to execute on the attribute. + private void GetAttributeValue(Action action) where T : Attribute { + var attribute = GetAttribute(); + if (attribute is not null) { + action(attribute); } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Internal/MappedTopicCache.cs b/OnTopic/Mapping/Internal/MappedTopicCache.cs index a08001e0..6cd48313 100644 --- a/OnTopic/Mapping/Internal/MappedTopicCache.cs +++ b/OnTopic/Mapping/Internal/MappedTopicCache.cs @@ -6,124 +6,123 @@ using System.Collections.Concurrent; using OnTopic.Mapping.Annotations; -namespace OnTopic.Mapping.Internal { +namespace OnTopic.Mapping.Internal; + +/*============================================================================================================================== +| CLASS: MAPPED TOPIC CACHE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a collection intended to track local caching of objects mapped using the . +/// +internal sealed class MappedTopicCache { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private readonly ConcurrentDictionary<(int, Type), MappedTopicCacheEntry> _cache = new(); /*============================================================================================================================ - | CLASS: MAPPED TOPIC CACHE + | METHOD: TRY GET VALUE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a collection intended to track local caching of objects mapped using the . + /// Overload of the which accepts a + /// and to construct a cache key, and then outputs a , if available. /// - internal class MappedTopicCache { + /// The associated with the cache entry. + /// The that the has been mapped to. + /// The containing the cached instance and metadata. + /// Returns true if a cached entry could be found, and otherwise false. + internal bool TryGetValue(int topicId, Type type, [NotNullWhen(true)] out MappedTopicCacheEntry? cacheEntry) { + if (_cache.TryGetValue(GetCacheKey(topicId, type), out var existingCacheEntry) && !existingCacheEntry.IsInitializing) { + cacheEntry = existingCacheEntry; + return true; + }; + cacheEntry = null; + return false; + } - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ConcurrentDictionary<(int, Type), MappedTopicCacheEntry> _cache = new(); + /*============================================================================================================================ + | METHOD: REGISTER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to add a new to the collection based on the , + /// , and . If one already exists, it is returned. + /// + /// The associated with the cache entry. + /// The used to map the current view model. + /// The mapped view model associated with the . + internal void Register(int topicId, AssociationTypes associations, object viewModel) { - /*========================================================================================================================== - | METHOD: TRY GET VALUE + /*-------------------------------------------------------------------------------------------------------------------------- + | Construct cache entry \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Overload of the which accepts a - /// and to construct a cache key, and then outputs a , if available. - /// - /// The associated with the cache entry. - /// The that the has been mapped to. - /// The containing the cached instance and metadata. - /// Returns true if a cached entry could be found, and otherwise false. - internal bool TryGetValue(int topicId, Type type, [NotNullWhen(true)] out MappedTopicCacheEntry? cacheEntry) { - if (_cache.TryGetValue(GetCacheKey(topicId, type), out var existingCacheEntry) && !existingCacheEntry.IsInitializing) { - cacheEntry = existingCacheEntry; - return true; - }; - cacheEntry = null; - return false; - } + var type = viewModel.GetType(); + var cacheKey = GetCacheKey(topicId, type); + var cacheEntry = new MappedTopicCacheEntry() { + MappedTopic = viewModel, + Associations = associations + }; - /*========================================================================================================================== - | METHOD: REGISTER + /*-------------------------------------------------------------------------------------------------------------------------- + | Get or add entry \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to add a new to the collection based on the , - /// , and . If one already exists, it is returned. - /// - /// The associated with the cache entry. - /// The used to map the current view model. - /// The mapped view model associated with the . - internal void Register(int topicId, AssociationTypes associations, object viewModel) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Construct cache entry - \-----------------------------------------------------------------------------------------------------------------------*/ - var type = viewModel.GetType(); - var cacheKey = GetCacheKey(topicId, type); - var cacheEntry = new MappedTopicCacheEntry() { - MappedTopic = viewModel, - Associations = associations - }; - - /*------------------------------------------------------------------------------------------------------------------------ - | Get or add entry - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topicId > 0 && !type.Equals(typeof(object))) { - cacheEntry = _cache.GetOrAdd(cacheKey, cacheEntry); - if (cacheEntry.IsInitializing) { - cacheEntry.IsInitializing = false; - cacheEntry.MappedTopic = viewModel; - cacheEntry.Associations = associations; - } + if (topicId > 0 && !type.Equals(typeof(object))) { + cacheEntry = _cache.GetOrAdd(cacheKey, cacheEntry); + if (cacheEntry.IsInitializing) { + cacheEntry.IsInitializing = false; + cacheEntry.MappedTopic = viewModel; + cacheEntry.Associations = associations; } - } - /*========================================================================================================================== - | METHOD: PREREGISTER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to preregister a for a that is in the process of - /// being mapped to . - /// - /// The associated with the cache entry. - /// The that the is being mapped to. - internal MappedTopicCacheEntry Preregister(int topicId, Type type) { + } - /*------------------------------------------------------------------------------------------------------------------------ - | Construct cache entry - \-----------------------------------------------------------------------------------------------------------------------*/ - var cacheKey = GetCacheKey(topicId, type); - var cacheEntry = new MappedTopicCacheEntry() { - IsInitializing = true - }; + /*============================================================================================================================ + | METHOD: PREREGISTER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to preregister a for a that is in the process of + /// being mapped to . + /// + /// The associated with the cache entry. + /// The that the is being mapped to. + internal MappedTopicCacheEntry Preregister(int topicId, Type type) { - /*------------------------------------------------------------------------------------------------------------------------ - | Get or add entry - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topicId > 0 && !type.Equals(typeof(object))) { - var existingCacheEntry = _cache.GetOrAdd(cacheKey, cacheEntry); - if (existingCacheEntry != cacheEntry) { - throw new TopicMappingException( - $"An attempt has been made to map '{topicId}' to a {type.Name} has resulted in a circular reference during the " + - $"construction of the {type.Name} instance. This is not allowed. Circular must be be mapped as properties, not " + - $"as constructor parameters, so that cached entries can be returned." - ); - } - } - return cacheEntry; + /*-------------------------------------------------------------------------------------------------------------------------- + | Construct cache entry + \-------------------------------------------------------------------------------------------------------------------------*/ + var cacheKey = GetCacheKey(topicId, type); + var cacheEntry = new MappedTopicCacheEntry() { + IsInitializing = true + }; + /*-------------------------------------------------------------------------------------------------------------------------- + | Get or add entry + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topicId > 0 && !type.Equals(typeof(object))) { + var existingCacheEntry = _cache.GetOrAdd(cacheKey, cacheEntry); + if (existingCacheEntry != cacheEntry) { + throw new TopicMappingException( + $"An attempt has been made to map '{topicId}' to a {type.Name} has resulted in a circular reference during the " + + $"construction of the {type.Name} instance. This is not allowed. Circular must be be mapped as properties, not " + + $"as constructor parameters, so that cached entries can be returned." + ); + } } + return cacheEntry; - /*========================================================================================================================== - | METHOD: GET CACHE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Constructs a new cache key from the supplied and . - /// - /// The associated with the source topic. - /// The that the has been mapped to. - /// - internal static (int, Type) GetCacheKey(int topicId, Type type) => new(topicId, type); + } + + /*============================================================================================================================ + | METHOD: GET CACHE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Constructs a new cache key from the supplied and . + /// + /// The associated with the source topic. + /// The that the has been mapped to. + /// + internal static (int, Type) GetCacheKey(int topicId, Type type) => new(topicId, type); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Internal/MappedTopicCacheEntry.cs b/OnTopic/Mapping/Internal/MappedTopicCacheEntry.cs index d976fbf0..51f8eeb8 100644 --- a/OnTopic/Mapping/Internal/MappedTopicCacheEntry.cs +++ b/OnTopic/Mapping/Internal/MappedTopicCacheEntry.cs @@ -5,72 +5,71 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Annotations; -namespace OnTopic.Mapping.Internal { +namespace OnTopic.Mapping.Internal; + +/*============================================================================================================================== +| CLASS: MAPPED TOPIC CACHE ENTRY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides an entry to tracking an object mapped using the . +/// +/// +/// In addition to the actual , this also includes a property for +/// tracking what associations were mapped to the . This allows the to be update the cached object with any missing associations, which can be identified using the method. In turn, the cache can then be updated to reflect those new +/// associations by using . This ensures that even if a topic has +/// already been mapped, its scope can be expanded without duplicating effort. +/// +internal sealed class MappedTopicCacheEntry { + + /*============================================================================================================================ + | PROPERTY: MAPPED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the mapped object. + /// + internal object MappedTopic { get; set; } = null!; /*============================================================================================================================ - | CLASS: MAPPED TOPIC CACHE ENTRY + | PROPERTY: IS INITIALIZING \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides an entry to tracking an object mapped using the . + /// Notes that the target type is currently being initialized. /// /// - /// In addition to the actual , this also includes a property for - /// tracking what associations were mapped to the . This allows the to be update the cached object with any missing associations, which can be identified using the method. In turn, the cache can then be updated to reflect those new - /// associations by using . This ensures that even if a topic has - /// already been mapped, its scope can be expanded without duplicating effort. + /// The property allows an entry to be pre-cached prior to the object being completed. This + /// allows the to detect circular references within the object initialization sequence. + /// This is important because, unlikely property mapping where a cached reference can be returned, a circular reference + /// in constructor mapping is expected to throw an exception. By registering that an object is being initialized, the + /// is able to detect circuluar references during constructor mapping. /// - internal class MappedTopicCacheEntry { - - /*========================================================================================================================== - | PROPERTY: MAPPED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the mapped object. - /// - internal object MappedTopic { get; set; } = null!; - - /*========================================================================================================================== - | PROPERTY: IS INITIALIZING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Notes that the target type is currently being initialized. - /// - /// - /// The property allows an entry to be pre-cached prior to the object being completed. This - /// allows the to detect circular references within the object initialization sequence. - /// This is important because, unlikely property mapping where a cached reference can be returned, a circular reference - /// in constructor mapping is expected to throw an exception. By registering that an object is being initialized, the - /// is able to detect circuluar references during constructor mapping. - /// - internal bool IsInitializing { get; set; } + internal bool IsInitializing { get; set; } - /*========================================================================================================================== - | PROPERTY: ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a reference to the associations that the was mapped with. - /// - internal AssociationTypes Associations { get; set; } = AssociationTypes.None; + /*============================================================================================================================ + | PROPERTY: ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a reference to the associations that the was mapped with. + /// + internal AssociationTypes Associations { get; set; } = AssociationTypes.None; - /*========================================================================================================================== - | METHOD: GET MISSING ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a target , identifies any associations not covered by - /// and returns them as a new instance. - /// - internal AssociationTypes GetMissingAssociations(AssociationTypes associations) => Associations ^ (associations | Associations); + /*============================================================================================================================ + | METHOD: GET MISSING ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a target , identifies any associations not covered by + /// and returns them as a new instance. + /// + internal AssociationTypes GetMissingAssociations(AssociationTypes associations) => Associations ^ (associations | Associations); - /*========================================================================================================================== - | METHOD: ADD MISSING ASSOCIATIONS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a target , adds any missing to the property. - /// - internal void AddMissingAssociations(AssociationTypes associations) => Associations = associations | Associations; + /*============================================================================================================================ + | METHOD: ADD MISSING ASSOCIATIONS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a target , adds any missing to the property. + /// + internal void AddMissingAssociations(AssociationTypes associations) => Associations = associations | Associations; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Reverse/BindingModelValidator.cs b/OnTopic/Mapping/Reverse/BindingModelValidator.cs index d915472c..9d124a11 100644 --- a/OnTopic/Mapping/Reverse/BindingModelValidator.cs +++ b/OnTopic/Mapping/Reverse/BindingModelValidator.cs @@ -12,338 +12,337 @@ using OnTopic.Models; using OnTopic.Repositories; -namespace OnTopic.Mapping.Reverse { +namespace OnTopic.Mapping.Reverse; + +/*============================================================================================================================== +| CLASS: BINDING MODEL VALIDATOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The model validator is responsible for identifying issues with tyopic view or binding models by evaluating their types +/// against a +/// +/// +/// +/// Technically, there is no reason for this code not to be in , which it is +/// specific to. The main reason it is separated out into a separate internal class is due to the size. The length is not +/// due to the code being especially complicated; it just has detailed documentation and exception messages. If this were +/// intended to be used by other classes, it'd be configured as an injectible public dependency; as an internal helper +/// class, however, it is adequate as a set of static methods. +/// +/// +/// There may be value to providing a comparable class for in the future. That said, it +/// is both easier to validate binding models (since they rely on interfaces, and aren't POCOs) and more critical (since +/// errors in mapping don't just result in missing data in the user interface, but potentially corrupt the database). As a +/// result, this class is provided to help developers avoid coding errors by validating design time decisions (the +/// binding model) against runtime behavior (the type of content type it is being utilized against). +/// +/// +static internal class BindingModelValidator { /*============================================================================================================================ - | CLASS: BINDING MODEL VALIDATOR + | PRIVATE FIELDS + \---------------------------------------------------------------------------------------------------------------------------*/ + static readonly ConcurrentBag<(Type, string)> _modelsValidated = new(); + + /*============================================================================================================================ + | INTERNAL: VALIDATE MODEL \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The model validator is responsible for identifying issues with tyopic view or binding models by evaluating their types - /// against a + /// Helper function that evaluates the binding model against the associated content type to identify any potential + /// mapping errors relative to the schema. /// /// /// - /// Technically, there is no reason for this code not to be in , which it is - /// specific to. The main reason it is separated out into a separate internal class is due to the size. The length is not - /// due to the code being especially complicated; it just has detailed documentation and exception messages. If this were - /// intended to be used by other classes, it'd be configured as an injectible public dependency; as an internal helper - /// class, however, it is adequate as a set of static methods. + /// This helper function is intended to provide reporting to developers about errors in their model. As a result, it + /// will exclusively throw exceptions, as opposed to populating validation object for rendering to the view. Because + /// it's only evaluating the compiled model, which will not change during the application's life cycle, the and are stored as a in a static + /// once a particular combination has passed validation—that way, this check only needs + /// to be executed once for any combination, at least for the current application life cycle. /// /// - /// There may be value to providing a comparable class for in the future. That said, it - /// is both easier to validate binding models (since they rely on interfaces, and aren't POCOs) and more critical (since - /// errors in mapping don't just result in missing data in the user interface, but potentially corrupt the database). As a - /// result, this class is provided to help developers avoid coding errors by validating design time decisions (the - /// binding model) against runtime behavior (the type of content type it is being utilized against). + /// Nested s from e.g. Nested Topics, relationships, and topic references will not be evaluated until + /// they are called from (or one if its + /// overloads). This could be problematic since any downstream errors could leave the + /// in an invalid state. That said, since this is identifying what are effectively bugs in the implementation, it is hoped that these will be identified during development, and never + /// make it to a production environment. To be safe, however, developers should be cautious when running mapping + /// existing instances from the when the may not have undergone explicit testing. /// /// - static internal class BindingModelValidator { + /// + /// The of the binding model to validate. + /// + /// + /// The object against which to validate the model. + /// + /// The prefix to apply to the attributes. + static internal void ValidateModel( + [AllowNull]TypeAccessor typeAccessor, + [AllowNull]ContentTypeDescriptor contentTypeDescriptor, + [AllowNull]string attributePrefix = "" + ) { - /*========================================================================================================================== - | PRIVATE FIELDS + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - static readonly ConcurrentBag<(Type, string)> _modelsValidated = new(); + Contract.Requires(typeAccessor, nameof(typeAccessor)); + Contract.Requires(contentTypeDescriptor, nameof(contentTypeDescriptor)); - /*========================================================================================================================== - | INTERNAL: VALIDATE MODEL + /*-------------------------------------------------------------------------------------------------------------------------- + | Skip validation if this type has already been validated for this content type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function that evaluates the binding model against the associated content type to identify any potential - /// mapping errors relative to the schema. - /// - /// - /// - /// This helper function is intended to provide reporting to developers about errors in their model. As a result, it - /// will exclusively throw exceptions, as opposed to populating validation object for rendering to the view. Because - /// it's only evaluating the compiled model, which will not change during the application's life cycle, the and are stored as a in a static - /// once a particular combination has passed validation—that way, this check only needs - /// to be executed once for any combination, at least for the current application life cycle. - /// - /// - /// Nested s from e.g. Nested Topics, relationships, and topic references will not be evaluated until - /// they are called from (or one if its - /// overloads). This could be problematic since any downstream errors could leave the - /// in an invalid state. That said, since this is identifying what are effectively bugs in the implementation, it is hoped that these will be identified during development, and never - /// make it to a production environment. To be safe, however, developers should be cautious when running mapping - /// existing instances from the when the may not have undergone explicit testing. - /// - /// - /// - /// The of the binding model to validate. - /// - /// - /// The object against which to validate the model. - /// - /// The prefix to apply to the attributes. - static internal void ValidateModel( - [AllowNull]TypeAccessor typeAccessor, - [AllowNull]ContentTypeDescriptor contentTypeDescriptor, - [AllowNull]string attributePrefix = "" - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(typeAccessor, nameof(typeAccessor)); - Contract.Requires(contentTypeDescriptor, nameof(contentTypeDescriptor)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Skip validation if this type has already been validated for this content type - \-----------------------------------------------------------------------------------------------------------------------*/ - if (_modelsValidated.Contains((typeAccessor.Type, contentTypeDescriptor.Key))) { - return; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { - ValidateProperty(typeAccessor.Type, property, contentTypeDescriptor, attributePrefix); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Add type, content type to model validation cache so it isn't checked again - \-----------------------------------------------------------------------------------------------------------------------*/ - _modelsValidated.Add((typeAccessor.Type, contentTypeDescriptor.Key)); - + if (_modelsValidated.Contains((typeAccessor.Type, contentTypeDescriptor.Key))) { return; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { + ValidateProperty(typeAccessor.Type, property, contentTypeDescriptor, attributePrefix); } - /*========================================================================================================================== - | INTERNAL: VALIDATE PROPERTY + /*-------------------------------------------------------------------------------------------------------------------------- + | Add type, content type to model validation cache so it isn't checked again \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function that evaluates a property of the binding model against the associated content type to identify any - /// potential mapping errors relative to the schema. - /// - /// - /// The binding model to validate. - /// - /// - /// A describing a specific property of the . - /// - /// - /// The object against which to validate the model. - /// - /// The prefix to apply to the attributes. - static internal void ValidateProperty( - [AllowNull]Type sourceType, - [AllowNull]MemberAccessor propertyAccessor, - [AllowNull]ContentTypeDescriptor contentTypeDescriptor, - [AllowNull]string attributePrefix = "" - ) { + _modelsValidated.Add((typeAccessor.Type, contentTypeDescriptor.Key)); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(sourceType, nameof(sourceType)); - Contract.Requires(propertyAccessor, nameof(propertyAccessor)); - Contract.Requires(contentTypeDescriptor, nameof(contentTypeDescriptor)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Define variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = propertyAccessor.Configuration; - var compositeAttributeKey = configuration.GetCompositeAttributeKey(attributePrefix); - var attributeDescriptor = contentTypeDescriptor.AttributeDescriptors.GetValue(compositeAttributeKey); - var childCollections = new[] { CollectionType.Children, CollectionType.NestedTopics }; - var relationships = new[] { CollectionType.Relationship, CollectionType.IncomingRelationship }; - var listType = typeof(object); - - /*------------------------------------------------------------------------------------------------------------------------ - | Skip properties decorated as [DisableMapping] - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.DisableMapping) { - return; - } + return; - /*------------------------------------------------------------------------------------------------------------------------ - | Skip properties injected by the compiler for record types - \-----------------------------------------------------------------------------------------------------------------------*/ - if (propertyAccessor.Name is "EqualityContract") { - return; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle mapping properties from referenced objects - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.MapToParent) { - var typeAccessor = TypeAccessorCache.GetTypeAccessor(propertyAccessor.Type); - - ValidateModel( - typeAccessor, - contentTypeDescriptor, - configuration.AttributePrefix - ); - return; - } + /*============================================================================================================================ + | INTERNAL: VALIDATE PROPERTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function that evaluates a property of the binding model against the associated content type to identify any + /// potential mapping errors relative to the schema. + /// + /// + /// The binding model to validate. + /// + /// + /// A describing a specific property of the . + /// + /// + /// The object against which to validate the model. + /// + /// The prefix to apply to the attributes. + static internal void ValidateProperty( + [AllowNull]Type sourceType, + [AllowNull]MemberAccessor propertyAccessor, + [AllowNull]ContentTypeDescriptor contentTypeDescriptor, + [AllowNull]string attributePrefix = "" + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(sourceType, nameof(sourceType)); + Contract.Requires(propertyAccessor, nameof(propertyAccessor)); + Contract.Requires(contentTypeDescriptor, nameof(contentTypeDescriptor)); - /*------------------------------------------------------------------------------------------------------------------------ - | Define list type (if it's a list) - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var type in propertyAccessor.Type.GetInterfaces()) { - if (type.IsGenericType && typeof(IList<>) == type.GetGenericTypeDefinition()) { - //Uses last argument in case it's a KeyedCollection; in that case, we want the TItem type - listType = type.GetGenericArguments().Last(); - } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Define variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = propertyAccessor.Configuration; + var compositeAttributeKey = configuration.GetCompositeAttributeKey(attributePrefix); + var attributeDescriptor = contentTypeDescriptor.AttributeDescriptors.GetValue(compositeAttributeKey); + var childCollections = new[] { CollectionType.Children, CollectionType.NestedTopics }; + var relationships = new[] { CollectionType.Relationship, CollectionType.IncomingRelationship }; + var listType = typeof(object); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Skip properties decorated as [DisableMapping] + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.DisableMapping) { + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle children - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.CollectionType is CollectionType.Children) { - throw new MappingModelValidationException( - $"The {nameof(ReverseTopicMappingService)} does not support mapping child topics. This property should be " + - $"removed from the binding model, or otherwise decorated with the {nameof(DisableMappingAttribute)} to prevent " + - $"it from being evaluated by the {nameof(ReverseTopicMappingService)}. If children must be mapped, then the " + - $"caller should handle this on a per child basis, where it can better validate the merge logic given the current " + - $"context of the target topic." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Skip properties injected by the compiler for record types + \-------------------------------------------------------------------------------------------------------------------------*/ + if (propertyAccessor.Name is "EqualityContract") { + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle parent - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.GetCompositeAttributeKey(attributePrefix) is "Parent") { - throw new MappingModelValidationException( - $"The {nameof(ReverseTopicMappingService)} does not support mapping Parent topics. This property should be " + - $"removed from the binding model, or otherwise decorated with the {nameof(DisableMappingAttribute)} to prevent " + - $"it from being evaluated by the {nameof(ReverseTopicMappingService)}." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle mapping properties from referenced objects + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.MapToParent) { + var typeAccessor = TypeAccessorCache.GetTypeAccessor(propertyAccessor.Type); + + ValidateModel( + typeAccessor, + contentTypeDescriptor, + configuration.AttributePrefix + ); + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate attribute type - \-----------------------------------------------------------------------------------------------------------------------*/ - if (attributeDescriptor is null) { - throw new MappingModelValidationException( - $"A '{nameof(sourceType)}' object was provided with a content type set to '{contentTypeDescriptor.Key}'. This " + - $"content type does not contain an attribute named '{compositeAttributeKey}', as requested by the " + - $"'{propertyAccessor.Name}' property. If this property is not intended to be mapped by the " + - $"{nameof(ReverseTopicMappingService)}, then it should be decorated with {nameof(DisableMappingAttribute)}." - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Define list type (if it's a list) + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var type in propertyAccessor.Type.GetInterfaces()) { + if (type.IsGenericType && typeof(IList<>) == type.GetGenericTypeDefinition()) { + //Uses last argument in case it's a KeyedCollection; in that case, we want the TItem type + listType = type.GetGenericArguments().Last(); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Detect non-mapped relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - if (attributeDescriptor.ModelType is ModelType.Relationship) { - ValidateRelationship(sourceType, propertyAccessor, attributeDescriptor, listType); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle children + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.CollectionType is CollectionType.Children) { + throw new MappingModelValidationException( + $"The {nameof(ReverseTopicMappingService)} does not support mapping child topics. This property should be " + + $"removed from the binding model, or otherwise decorated with the {nameof(DisableMappingAttribute)} to prevent " + + $"it from being evaluated by the {nameof(ReverseTopicMappingService)}. If children must be mapped, then the " + + $"caller should handle this on a per child basis, where it can better validate the merge logic given the current " + + $"context of the target topic." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate the correct base class for nested topics - \-----------------------------------------------------------------------------------------------------------------------*/ - if ( - attributeDescriptor.ModelType is ModelType.NestedTopic && - !typeof(ITopicBindingModel).IsAssignableFrom(listType) - ) { - throw new MappingModelValidationException( - $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class has been determined to be a " + - $"{configuration.CollectionType}, but the generic type '{listType.Name}' does not implement the " + - $"{nameof(ITopicBindingModel)} interface. This is required for binding models. If this collection is not intended " + - $"to be mapped as a {ModelType.NestedTopic} then update the definition in the associated " + - $"{nameof(ContentTypeDescriptor)}. If this collection is not intended to be mapped at all, include the " + - $"{nameof(DisableMappingAttribute)} to exclude it from mapping." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle parent + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.GetCompositeAttributeKey(attributePrefix) is "Parent") { + throw new MappingModelValidationException( + $"The {nameof(ReverseTopicMappingService)} does not support mapping Parent topics. This property should be " + + $"removed from the binding model, or otherwise decorated with the {nameof(DisableMappingAttribute)} to prevent " + + $"it from being evaluated by the {nameof(ReverseTopicMappingService)}." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate the correct base class for reference - \-----------------------------------------------------------------------------------------------------------------------*/ - if ( - attributeDescriptor.ModelType is ModelType.Reference && - !typeof(IAssociatedTopicBindingModel).IsAssignableFrom(propertyAccessor.Type) - ) { - throw new MappingModelValidationException( - $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class has been determined to be a " + - $"{ModelType.Reference}, but the generic type '{propertyAccessor.Type.Name}' does not implement the " + - $"{nameof(IAssociatedTopicBindingModel)} interface. This is required for references. If this property is not " + - $"intended to be mapped as a {ModelType.Reference} then update the definition in the associated " + - $"{nameof(ContentTypeDescriptor)}. If this property is not intended to be mapped at all, include the " + - $"{nameof(DisableMappingAttribute)} to exclude it from mapping." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate attribute type + \-------------------------------------------------------------------------------------------------------------------------*/ + if (attributeDescriptor is null) { + throw new MappingModelValidationException( + $"A '{nameof(sourceType)}' object was provided with a content type set to '{contentTypeDescriptor.Key}'. This " + + $"content type does not contain an attribute named '{compositeAttributeKey}', as requested by the " + + $"'{propertyAccessor.Name}' property. If this property is not intended to be mapped by the " + + $"{nameof(ReverseTopicMappingService)}, then it should be decorated with {nameof(DisableMappingAttribute)}." + ); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Detect non-mapped relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + if (attributeDescriptor.ModelType is ModelType.Relationship) { + ValidateRelationship(sourceType, propertyAccessor, attributeDescriptor, listType); } - /*========================================================================================================================== - | INTERNAL: VALIDATE RELATIONSHIP + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate the correct base class for nested topics \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function that evaluates a relationship property on the binding model against the associated content type to - /// identify any potential mapping errors relative to the schema. - /// - /// - /// The binding model to validate. - /// - /// - /// A describing a specific property of the . - /// - /// - /// The object against which to validate the model. - /// - /// The generic used for the corresponding . - static internal void ValidateRelationship( - [AllowNull]Type sourceType, - [AllowNull]MemberAccessor propertyAccessor, - [AllowNull]AttributeDescriptor attributeDescriptor, - [DisallowNull]Type listType + if ( + attributeDescriptor.ModelType is ModelType.NestedTopic && + !typeof(ITopicBindingModel).IsAssignableFrom(listType) ) { + throw new MappingModelValidationException( + $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class has been determined to be a " + + $"{configuration.CollectionType}, but the generic type '{listType.Name}' does not implement the " + + $"{nameof(ITopicBindingModel)} interface. This is required for binding models. If this collection is not intended " + + $"to be mapped as a {ModelType.NestedTopic} then update the definition in the associated " + + $"{nameof(ContentTypeDescriptor)}. If this collection is not intended to be mapped at all, include the " + + $"{nameof(DisableMappingAttribute)} to exclude it from mapping." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(sourceType, nameof(sourceType)); - Contract.Requires(propertyAccessor, nameof(propertyAccessor)); - Contract.Requires(attributeDescriptor, nameof(attributeDescriptor)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Define variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = propertyAccessor.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate list - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!typeof(IList).IsAssignableFrom(propertyAccessor.Type)) { - throw new MappingModelValidationException( - $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class maps to a relationship attribute " + - $"'{attributeDescriptor.Key}', but does not implement {nameof(IList)}. Relationships must implement " + - $"{nameof(IList)} or derive from a collection that does." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate the correct base class for reference + \-------------------------------------------------------------------------------------------------------------------------*/ + if ( + attributeDescriptor.ModelType is ModelType.Reference && + !typeof(IAssociatedTopicBindingModel).IsAssignableFrom(propertyAccessor.Type) + ) { + throw new MappingModelValidationException( + $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class has been determined to be a " + + $"{ModelType.Reference}, but the generic type '{propertyAccessor.Type.Name}' does not implement the " + + $"{nameof(IAssociatedTopicBindingModel)} interface. This is required for references. If this property is not " + + $"intended to be mapped as a {ModelType.Reference} then update the definition in the associated " + + $"{nameof(ContentTypeDescriptor)}. If this property is not intended to be mapped at all, include the " + + $"{nameof(DisableMappingAttribute)} to exclude it from mapping." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate relationship type - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!new[] { CollectionType.Any, CollectionType.Relationship }.Contains(configuration.CollectionType)) { - throw new MappingModelValidationException( - $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class maps to a relationship attribute " + - $"'{attributeDescriptor.Key}', but is configured as a {configuration.CollectionType}. The property should be " + - $"flagged as either {nameof(CollectionType.Any)} or {nameof(CollectionType.Relationship)}." - ); - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate the correct base class for relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!typeof(IAssociatedTopicBindingModel).IsAssignableFrom(listType)) { - throw new MappingModelValidationException( - $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class has been determined to be a " + - $"{configuration.CollectionType}, but the generic type '{listType.Name}' does not implement the " + - $"{nameof(IAssociatedTopicBindingModel)} interface. This is required for binding models. If this collection is not " + - $"intended to be mapped as a {configuration.CollectionType} then update the definition in the associated " + - $"{nameof(ContentTypeDescriptor)}. If this collection is not intended to be mapped at all, include the " + - $"{nameof(DisableMappingAttribute)} to exclude it from mapping." - ); - } + /*============================================================================================================================ + | INTERNAL: VALIDATE RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function that evaluates a relationship property on the binding model against the associated content type to + /// identify any potential mapping errors relative to the schema. + /// + /// + /// The binding model to validate. + /// + /// + /// A describing a specific property of the . + /// + /// + /// The object against which to validate the model. + /// + /// The generic used for the corresponding . + static internal void ValidateRelationship( + [AllowNull]Type sourceType, + [AllowNull]MemberAccessor propertyAccessor, + [AllowNull]AttributeDescriptor attributeDescriptor, + [DisallowNull]Type listType + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(sourceType, nameof(sourceType)); + Contract.Requires(propertyAccessor, nameof(propertyAccessor)); + Contract.Requires(attributeDescriptor, nameof(attributeDescriptor)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Define variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = propertyAccessor.Configuration; + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate list + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!typeof(IList).IsAssignableFrom(propertyAccessor.Type)) { + throw new MappingModelValidationException( + $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class maps to a relationship attribute " + + $"'{attributeDescriptor.Key}', but does not implement {nameof(IList)}. Relationships must implement " + + $"{nameof(IList)} or derive from a collection that does." + ); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate relationship type + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!new[] { CollectionType.Any, CollectionType.Relationship }.Contains(configuration.CollectionType)) { + throw new MappingModelValidationException( + $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class maps to a relationship attribute " + + $"'{attributeDescriptor.Key}', but is configured as a {configuration.CollectionType}. The property should be " + + $"flagged as either {nameof(CollectionType.Any)} or {nameof(CollectionType.Relationship)}." + ); } - } //Class -} //Namespace \ No newline at end of file + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate the correct base class for relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!typeof(IAssociatedTopicBindingModel).IsAssignableFrom(listType)) { + throw new MappingModelValidationException( + $"The '{propertyAccessor.Name}' property on the '{sourceType.Name}' class has been determined to be a " + + $"{configuration.CollectionType}, but the generic type '{listType.Name}' does not implement the " + + $"{nameof(IAssociatedTopicBindingModel)} interface. This is required for binding models. If this collection is not " + + $"intended to be mapped as a {configuration.CollectionType} then update the definition in the associated " + + $"{nameof(ContentTypeDescriptor)}. If this collection is not intended to be mapped at all, include the " + + $"{nameof(DisableMappingAttribute)} to exclude it from mapping." + ); + } + + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/Reverse/IReverseTopicMappingService.cs b/OnTopic/Mapping/Reverse/IReverseTopicMappingService.cs index 276795e1..1b9e6bde 100644 --- a/OnTopic/Mapping/Reverse/IReverseTopicMappingService.cs +++ b/OnTopic/Mapping/Reverse/IReverseTopicMappingService.cs @@ -8,92 +8,91 @@ using OnTopic.Models; using OnTopic.Repositories; -namespace OnTopic.Mapping.Reverse { +namespace OnTopic.Mapping.Reverse; + +/*============================================================================================================================== +| INTERFACE: REVERSE TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The interface provides an abstraction for mapping Data Transfer Objects +/// (DTOs), such as View Models or, more likely, Binding Models, back to instances. +/// +/// +/// +/// Unlike something like e.g. AutoMapper, the reverse mapping scenario isn't simply a matter of "flipping the script" on +/// the . A binding model should not be relied upon to be an accurate description of the +/// (even though, ideally, it should be). Therefore, the will instead rely upon the to define the +/// model and use that to selectively pull in property values accordingly. At the same time, however, it must honor hints +/// from the binding model regarding what properties are intended for—especially in terms of e.g aliased relationships. +/// +/// +/// The current design of is not intended to support mapping associations, as +/// this overlaps with a broader concern of merging topics with an existing graph (e.g., as part of an +/// . It will map the associations to those topics, but not those topics themselves. +/// +/// +/// Despite the differences between the and s, +/// many attributes are able to be reused between them. For instance, the can still +/// map a property on a binding model to an attribute of a different name on a , just as the can with collections. Other attributes, however, provde no benefit in the reverse +/// scenario, such as or , which really only make +/// sense in creating a "produced view" that is a subset of the original model. That is valuable when creating a view +/// model, but isn't a useful use case when working with binding models. +/// +/// +public interface IReverseTopicMappingService { /*============================================================================================================================ - | INTERFACE: REVERSE TOPIC MAPPING SERVICE + | METHOD: MAP (DYNAMIC) \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The interface provides an abstraction for mapping Data Transfer Objects - /// (DTOs), such as View Models or, more likely, Binding Models, back to instances. + /// Given a binding model, will create a new instance of (or the appropriate subclass), and will map + /// the properties of the binding model to attributes on the . /// /// /// - /// Unlike something like e.g. AutoMapper, the reverse mapping scenario isn't simply a matter of "flipping the script" on - /// the . A binding model should not be relied upon to be an accurate description of the - /// (even though, ideally, it should be). Therefore, the will instead rely upon the to define the - /// model and use that to selectively pull in property values accordingly. At the same time, however, it must honor hints - /// from the binding model regarding what properties are intended for—especially in terms of e.g aliased relationships. - /// - /// - /// The current design of is not intended to support mapping associations, as - /// this overlaps with a broader concern of merging topics with an existing graph (e.g., as part of an - /// . It will map the associations to those topics, but not those topics themselves. - /// - /// - /// Despite the differences between the and s, - /// many attributes are able to be reused between them. For instance, the can still - /// map a property on a binding model to an attribute of a different name on a , just as the can with collections. Other attributes, however, provde no benefit in the reverse - /// scenario, such as or , which really only make - /// sense in creating a "produced view" that is a subset of the original model. That is valuable when creating a view - /// model, but isn't a useful use case when working with binding models. + /// Because the class is using reflection to determine the target View Models, the return type is . + /// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views + /// should be able to cast the object to the appropriate View Model type. If the type of the Topic is known + /// upfront, and it is imperative that it be strongly-typed, then prefer . /// /// - public interface IReverseTopicMappingService { - - /*========================================================================================================================== - | METHOD: MAP (DYNAMIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a binding model, will create a new instance of (or the appropriate subclass), and will map - /// the properties of the binding model to attributes on the . - /// - /// - /// - /// Because the class is using reflection to determine the target View Models, the return type is . - /// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views - /// should be able to cast the object to the appropriate View Model type. If the type of the Topic is known - /// upfront, and it is imperative that it be strongly-typed, then prefer . - /// - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// An instance of the dynamically determined with attributes appropriately mapped. - Task MapAsync(ITopicBindingModel source); + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// An instance of the dynamically determined with attributes appropriately mapped. + Task MapAsync(ITopicBindingModel source); - /*========================================================================================================================== - | METHOD: MAP (GENERIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a binding model, will instantiate a new instance of the generic type and map the properties of the binding model - /// to attributes on the . - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// - /// An instance of the requested Topc with attributes appropriately mapped. - /// - Task MapAsync(ITopicBindingModel source) where T : Topic; + /*============================================================================================================================ + | METHOD: MAP (GENERIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a binding model, will instantiate a new instance of the generic type and map the properties of the binding model + /// to attributes on the . + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// + /// An instance of the requested Topc with attributes appropriately mapped. + /// + Task MapAsync(ITopicBindingModel source) where T : Topic; - /*========================================================================================================================== - | METHOD: MAP (INSTANCES) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a binding model and an existing , will map the properties of the binding model to attributes - /// on the . - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// - /// An instance of provided with attributes appropriately mapped. - /// - Task MapAsync(ITopicBindingModel source, Topic target); + /*============================================================================================================================ + | METHOD: MAP (INSTANCES) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a binding model and an existing , will map the properties of the binding model to attributes + /// on the . + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// + /// An instance of provided with attributes appropriately mapped. + /// + Task MapAsync(ITopicBindingModel source, Topic target); - } //Interface -} //Namespace \ No newline at end of file +} //Interface \ No newline at end of file diff --git a/OnTopic/Mapping/Reverse/ReverseTopicMappingService.cs b/OnTopic/Mapping/Reverse/ReverseTopicMappingService.cs index 66e9107f..723f686b 100644 --- a/OnTopic/Mapping/Reverse/ReverseTopicMappingService.cs +++ b/OnTopic/Mapping/Reverse/ReverseTopicMappingService.cs @@ -13,576 +13,571 @@ using OnTopic.Models; using OnTopic.Repositories; -namespace OnTopic.Mapping.Reverse { +namespace OnTopic.Mapping.Reverse; + +/*============================================================================================================================== +| CLASS: REVERSE TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +public class ReverseTopicMappingService : IReverseTopicMappingService { /*============================================================================================================================ - | CLASS: REVERSE TOPIC MAPPING SERVICE + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository; + readonly ContentTypeDescriptorCollection _contentTypeDescriptors; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new instance of a with required dependencies. + /// + public ReverseTopicMappingService(ITopicRepository topicRepository) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topicRepository, "An instance of an ITopicRepository is required."); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set dependencies + \-------------------------------------------------------------------------------------------------------------------------*/ + _topicRepository = topicRepository; + _contentTypeDescriptors = topicRepository.GetContentTypeDescriptors(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate dependencies + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Assume( + _contentTypeDescriptors, + $"The {nameof(ITopicRepository.GetContentTypeDescriptors)}() method returned null. This could indicate a corrupt " + + $"or data source." + ); + + } + + /*============================================================================================================================ + | METHOD: MAP (ASYNC) \---------------------------------------------------------------------------------------------------------------------------*/ /// - public class ReverseTopicMappingService : IReverseTopicMappingService { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ContentTypeDescriptorCollection _contentTypeDescriptors; - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a with required dependencies. - /// - public ReverseTopicMappingService(ITopicRepository topicRepository) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicRepository, "An instance of an ITopicRepository is required."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - _topicRepository = topicRepository; - _contentTypeDescriptors = topicRepository.GetContentTypeDescriptors(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Assume( - _contentTypeDescriptors, - $"The {nameof(ITopicRepository.GetContentTypeDescriptors)}() method returned null. This could indicate a corrupt " + - $"or data source." - ); + public async Task MapAsync(ITopicBindingModel source) { - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source + \-------------------------------------------------------------------------------------------------------------------------*/ + if (source is null) return null; - /*========================================================================================================================== - | METHOD: MAP (ASYNC) + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(ITopicBindingModel source) { + Contract.Requires(source.Key, $"The 'source' ITopicBindingModel must contain a 'Key' value."); + Contract.Requires(source.ContentType, $"The 'source' ITopicBindingModel must contain a 'ContentType' value."); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (source is null) return null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Instantiate target + \-------------------------------------------------------------------------------------------------------------------------*/ + var topic = TopicFactory.Create(source.Key, source.ContentType); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(source.Key, $"The 'source' ITopicBindingModel must contain a 'Key' value."); - Contract.Requires(source.ContentType, $"The 'source' ITopicBindingModel must contain a 'ContentType' value."); + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide mapping + \-------------------------------------------------------------------------------------------------------------------------*/ + return await MapAsync(source, topic).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Instantiate target - \-----------------------------------------------------------------------------------------------------------------------*/ - var topic = TopicFactory.Create(source.Key, source.ContentType); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Provide mapping - \-----------------------------------------------------------------------------------------------------------------------*/ - return await MapAsync(source, topic).ConfigureAwait(false); + /*============================================================================================================================ + | METHOD: MAP (T) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(ITopicBindingModel? source) where T : Topic { + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source + \-------------------------------------------------------------------------------------------------------------------------*/ + if (source is null) { + return null; } - /*========================================================================================================================== - | METHOD: MAP (T) + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(ITopicBindingModel? source) where T : Topic { + Contract.Requires(source.Key, $"The 'source' ITopicBindingModel must contain a 'Key' value."); + Contract.Requires(source.ContentType, $"The 'source' ITopicBindingModel must contain a 'ContentType' value."); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (source is null) { - return null; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Map source + \-------------------------------------------------------------------------------------------------------------------------*/ + return (T?)await MapAsync( + source, + TopicFactory.Create(source.Key, source.ContentType) + ).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(source.Key, $"The 'source' ITopicBindingModel must contain a 'Key' value."); - Contract.Requires(source.ContentType, $"The 'source' ITopicBindingModel must contain a 'ContentType' value."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Map source - \-----------------------------------------------------------------------------------------------------------------------*/ - return (T?)await MapAsync( - source, - TopicFactory.Create(source.Key, source.ContentType) - ).ConfigureAwait(false); + } + /*============================================================================================================================ + | METHOD: MAP (TOPIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(ITopicBindingModel? source, Topic target) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source + \-------------------------------------------------------------------------------------------------------------------------*/ + if (source is null) return target; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(target, nameof(target)); + Contract.Assume(source.ContentType, nameof(source.ContentType)); + + //Ensure the content type is valid + if (!_contentTypeDescriptors.Contains(source.ContentType)) { + throw new MappingModelValidationException( + $"The {nameof(source)} object (with the key '{source.Key}') has a content type of '{source.ContentType}'. There " + + $"are no matching content types in the ITopicRepository provided. This suggests that the binding model is invalid. " + + $"If this is expected—e.g., if the content type is being added as part of this operation—then it needs to be added " + + $"to the same ITopicRepository instance prior to creating any instances of it." + ); } - /*========================================================================================================================== - | METHOD: MAP (TOPIC) + //Ensure the content types match + if (source.ContentType != target.ContentType) { + throw new MappingModelValidationException( + $"The {nameof(source)} object (with the key '{source.Key}') has a content type of '{source.ContentType}', while " + + $"the {nameof(target)} object (with the key '{target.Key}') has a content type of '{target.ContentType}'. It is not" + + $"permitted to change the topic's content type during a mapping operation, as this interferes with the validation. " + + $"If this is by design, change the content type on the target topic prior to invoking MapAsync()." + ); + } + + //Ensure the keys match + if (source.Key != target.Key && !String.IsNullOrEmpty(source.Key)) { + throw new MappingModelValidationException( + $"The {nameof(source)} object has a key of '{source.Key}', while the {nameof(target)} object has a key of " + + $"'{target.Key}'. It is not permitted to change the topic's key during a mapping operation, as this suggests an " + + $"invalid target. If this is by design, change the key on the target topic prior to invoking MapAsync()." + ); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Map source to target \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(ITopicBindingModel? source, Topic target) { + return await MapAsync(source, target, null).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (source is null) return target; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(target, nameof(target)); - Contract.Assume(source.ContentType, nameof(source.ContentType)); + /*============================================================================================================================ + | PRIVATE: MAP (TOPIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a binding model and an existing , will map the properties of the binding model to attributes + /// on the , optionally prefixing the attributes with the . + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// The prefix to apply to the attributes. + /// + /// An instance of provided with attributes appropriately mapped. + /// + private async Task MapAsync(object? source, Topic target, string? attributePrefix) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle null source + \-------------------------------------------------------------------------------------------------------------------------*/ + if (source is null) return target; - //Ensure the content type is valid - if (!_contentTypeDescriptors.Contains(source.ContentType)) { - throw new MappingModelValidationException( - $"The {nameof(source)} object (with the key '{source.Key}') has a content type of '{source.ContentType}'. There " + - $"are no matching content types in the ITopicRepository provided. This suggests that the binding model is invalid. " + - $"If this is expected—e.g., if the content type is being added as part of this operation—then it needs to be added " + - $"to the same ITopicRepository instance prior to creating any instances of it." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate model + \-------------------------------------------------------------------------------------------------------------------------*/ + var typeAccessor = TypeAccessorCache.GetTypeAccessor(source.GetType()); + var contentTypeDescriptor = _contentTypeDescriptors.GetValue(target.ContentType); - //Ensure the content types match - if (source.ContentType != target.ContentType) { - throw new MappingModelValidationException( - $"The {nameof(source)} object (with the key '{source.Key}') has a content type of '{source.ContentType}', while " + - $"the {nameof(target)} object (with the key '{target.Key}') has a content type of '{target.ContentType}'. It is not" + - $"permitted to change the topic's content type during a mapping operation, as this interferes with the validation. " + - $"If this is by design, change the content type on the target topic prior to invoking MapAsync()." - ); - } + BindingModelValidator.ValidateModel(typeAccessor, contentTypeDescriptor, attributePrefix); - //Ensure the keys match - if (source.Key != target.Key && !String.IsNullOrEmpty(source.Key)) { - throw new MappingModelValidationException( - $"The {nameof(source)} object has a key of '{source.Key}', while the {nameof(target)} object has a key of " + - $"'{target.Key}'. It is not permitted to change the topic's key during a mapping operation, as this suggests an " + - $"invalid target. If this is by design, change the key on the target topic prior to invoking MapAsync()." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Loop through properties, mapping each one + \-------------------------------------------------------------------------------------------------------------------------*/ + var taskQueue = new List(); + foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { + taskQueue.Add(SetPropertyAsync(source, target, property, attributePrefix)); + } + await Task.WhenAll([.. taskQueue]).ConfigureAwait(false); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return result + \-------------------------------------------------------------------------------------------------------------------------*/ + return target; - /*---------------------------------------------------------------------------------------------------------------------- - | Map source to target - \---------------------------------------------------------------------------------------------------------------------*/ - return await MapAsync(source, target, null).ConfigureAwait(false); + } + /*============================================================================================================================ + | PRIVATE: SET PROPERTY (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function that evaluates each property on the source and then attempts to + /// locate and set the associated attribute, collection, or property on the target based on + /// predetermined conventions. + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// Information related to the current property. + /// The prefix to apply to the attributes. + private async Task SetPropertyAsync( + object source, + Topic target, + MemberAccessor memberAccessor, + string? attributePrefix = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish per-property variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = memberAccessor.Configuration; + var contentTypeDescriptor = _contentTypeDescriptors.GetValue(target.ContentType); + var compositeAttributeKey = configuration.GetCompositeAttributeKey(attributePrefix); + + Contract.Assume(contentTypeDescriptor, nameof(contentTypeDescriptor)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Skip properties decorated with [DisableMapping] + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.DisableMapping) { + return; } - /*========================================================================================================================== - | PRIVATE: MAP (TOPIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a binding model and an existing , will map the properties of the binding model to attributes - /// on the , optionally prefixing the attributes with the . - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// The prefix to apply to the attributes. - /// - /// An instance of provided with attributes appropriately mapped. - /// - private async Task MapAsync(object? source, Topic target, string? attributePrefix) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle null source - \-----------------------------------------------------------------------------------------------------------------------*/ - if (source is null) return target; - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate model - \-----------------------------------------------------------------------------------------------------------------------*/ - var typeAccessor = TypeAccessorCache.GetTypeAccessor(source.GetType()); - var contentTypeDescriptor = _contentTypeDescriptors.GetValue(target.ContentType); - - BindingModelValidator.ValidateModel(typeAccessor, contentTypeDescriptor, attributePrefix); - - /*------------------------------------------------------------------------------------------------------------------------ - | Loop through properties, mapping each one - \-----------------------------------------------------------------------------------------------------------------------*/ - var taskQueue = new List(); - foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { - taskQueue.Add(SetPropertyAsync(source, target, property, attributePrefix)); - } - await Task.WhenAll(taskQueue.ToArray()).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Skip properties injected by the compiler for record types + \-------------------------------------------------------------------------------------------------------------------------*/ + if (memberAccessor.Name is "EqualityContract") { + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return result - \-----------------------------------------------------------------------------------------------------------------------*/ - return target; + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle mapping properties from referenced objects + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.MapToParent) { + await MapAsync( + memberAccessor.GetValue(source), + target, + configuration.AttributePrefix + ).ConfigureAwait(false); + return; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve attribute descriptor + \-------------------------------------------------------------------------------------------------------------------------*/ + var attributeType = contentTypeDescriptor.AttributeDescriptors.GetValue(compositeAttributeKey); + if (attributeType is null) { + throw new MappingModelValidationException( + $"The attribute '{configuration.GetCompositeAttributeKey(attributePrefix)}' mapped by the {source.GetType()} could not be found on the " + + $"'{contentTypeDescriptor.Key}' content type."); } - /*========================================================================================================================== - | PRIVATE: SET PROPERTY (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function that evaluates each property on the source and then attempts to - /// locate and set the associated attribute, collection, or property on the target based on - /// predetermined conventions. - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// Information related to the current property. - /// The prefix to apply to the attributes. - private async Task SetPropertyAsync( - object source, - Topic target, - MemberAccessor memberAccessor, - string? attributePrefix = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish per-property variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = memberAccessor.Configuration; - var contentTypeDescriptor = _contentTypeDescriptors.GetValue(target.ContentType); - var compositeAttributeKey = configuration.GetCompositeAttributeKey(attributePrefix); - - Contract.Assume(contentTypeDescriptor, nameof(contentTypeDescriptor)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Skip properties decorated with [DisableMapping] - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.DisableMapping) { - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate fields + \-------------------------------------------------------------------------------------------------------------------------*/ + memberAccessor.Validate(source); - /*------------------------------------------------------------------------------------------------------------------------ - | Skip properties injected by the compiler for record types - \-----------------------------------------------------------------------------------------------------------------------*/ - if (memberAccessor.Name is "EqualityContract") { + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle property by type + \-------------------------------------------------------------------------------------------------------------------------*/ + switch (attributeType.ModelType) { + case ModelType.ScalarValue: + SetScalarValue(source, target, memberAccessor, attributePrefix); return; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle mapping properties from referenced objects - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.MapToParent) { - await MapAsync( - memberAccessor.GetValue(source), - target, - configuration.AttributePrefix - ).ConfigureAwait(false); + case ModelType.Relationship: + SetRelationships(source, target, memberAccessor, attributePrefix); return; - } + case ModelType.NestedTopic: + await SetNestedTopicsAsync(source, target, memberAccessor, attributePrefix).ConfigureAwait(false); + return; + case ModelType.Reference: + SetReference(source, target, memberAccessor, attributePrefix); + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve attribute descriptor - \-----------------------------------------------------------------------------------------------------------------------*/ - var attributeType = contentTypeDescriptor.AttributeDescriptors.GetValue(compositeAttributeKey); + } - if (attributeType is null) { - throw new MappingModelValidationException( - $"The attribute '{configuration.GetCompositeAttributeKey(attributePrefix)}' mapped by the {source.GetType()} could not be found on the " + - $"'{contentTypeDescriptor.Key}' content type."); - } + /*============================================================================================================================ + | PRIVATE: SET SCALAR VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Sets an attribute on the target with a scalar value from the source binding model. + /// + /// + /// Assuming the 's property is of the type , , , or , the method will attempt to set the property on the . + /// If the value is not set on the then the will be + /// evaluated as a fallback. If the property is not of a settable type then the property is not set. If the value is + /// empty, then it will be treated as null in the 's . + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// The with details about the property's attributes. + /// The prefix to apply to the attributes. + /// + private static void SetScalarValue( + object source, + Topic target, + MemberAccessor memberAccessor, + string? attributePrefix + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to retrieve value from the binding model property + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = memberAccessor.Configuration; + var attributeValue = memberAccessor.GetValue(source)?.ToString(); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate fields - \-----------------------------------------------------------------------------------------------------------------------*/ - memberAccessor.Validate(source); - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle property by type - \-----------------------------------------------------------------------------------------------------------------------*/ - switch (attributeType.ModelType) { - case ModelType.ScalarValue: - SetScalarValue(source, target, memberAccessor, attributePrefix); - return; - case ModelType.Relationship: - SetRelationships(source, target, memberAccessor, attributePrefix); - return; - case ModelType.NestedTopic: - await SetNestedTopicsAsync(source, target, memberAccessor, attributePrefix).ConfigureAwait(false); - return; - case ModelType.Reference: - SetReference(source, target, memberAccessor, attributePrefix); - return; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Fall back to default, if configured + \-------------------------------------------------------------------------------------------------------------------------*/ + if (String.IsNullOrEmpty(attributeValue) && configuration.DefaultValue is not null) { + attributeValue = configuration.DefaultValue.ToString(); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle type conversion + \-------------------------------------------------------------------------------------------------------------------------*/ + if (attributeValue is not null && memberAccessor.Type.Name is nameof(Boolean)) { + attributeValue = attributeValue is "True" ? "1" : "0"; } - /*========================================================================================================================== - | PRIVATE: SET SCALAR VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Sets an attribute on the target with a scalar value from the source binding model. - /// - /// - /// Assuming the 's property is of the type , , , or , the method will attempt to set the property on the . - /// If the value is not set on the then the will be - /// evaluated as a fallback. If the property is not of a settable type then the property is not set. If the value is - /// empty, then it will be treated as null in the 's . - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// The with details about the property's attributes. - /// The prefix to apply to the attributes. - /// - private static void SetScalarValue( - object source, - Topic target, - MemberAccessor memberAccessor, - string? attributePrefix - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to retrieve value from the binding model property - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = memberAccessor.Configuration; - var attributeValue = memberAccessor.GetValue(source)?.ToString(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Fall back to default, if configured - \-----------------------------------------------------------------------------------------------------------------------*/ - if (String.IsNullOrEmpty(attributeValue) && configuration.DefaultValue is not null) { - attributeValue = configuration.DefaultValue.ToString(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Set the value (to null, if appropriate) + \-------------------------------------------------------------------------------------------------------------------------*/ + target.Attributes.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), attributeValue); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle type conversion - \-----------------------------------------------------------------------------------------------------------------------*/ - if (attributeValue is not null) { - switch (memberAccessor.Type.Name) { - case nameof(Boolean): - attributeValue = attributeValue is "True" ? "1" : "0"; - break; - } - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Set the value (to null, if appropriate) - \-----------------------------------------------------------------------------------------------------------------------*/ - target.Attributes.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), attributeValue); + /*============================================================================================================================ + | PRIVATE: SET RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a relationship property, identifies the target for each related item, and sets it on the + /// source 's collection. + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// The with details about the property's attributes. + /// The prefix to apply to the attributes. + private void SetRelationships( + object source, + Topic target, + MemberAccessor memberAccessor, + string? attributePrefix + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = memberAccessor.Configuration; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve source list + \-------------------------------------------------------------------------------------------------------------------------*/ + var sourceList = (IList?)memberAccessor.GetValue(source); + + sourceList ??= new List(); - /*========================================================================================================================== - | PRIVATE: SET RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a relationship property, identifies the target for each related item, and sets it on the - /// source 's collection. - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// The with details about the property's attributes. - /// The prefix to apply to the attributes. - private void SetRelationships( - object source, - Topic target, - MemberAccessor memberAccessor, - string? attributePrefix - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = memberAccessor.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve source list - \-----------------------------------------------------------------------------------------------------------------------*/ - var sourceList = (IList?)memberAccessor.GetValue(source); - - sourceList ??= new List(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Clear existing relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - target.Relationships.Clear(configuration.GetCompositeAttributeKey(attributePrefix)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set relationships for each - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (IAssociatedTopicBindingModel relationship in sourceList) { - var targetTopic = _topicRepository.Load(relationship.UniqueKey, target); - if (targetTopic is null) { - throw new MappingModelValidationException( - $"The relationship '{relationship.UniqueKey}' mapped in the '{memberAccessor.Name}' property could not be " + - $"located in the repository." - ); - } - target.Relationships.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), targetTopic); + /*-------------------------------------------------------------------------------------------------------------------------- + | Clear existing relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + target.Relationships.Clear(configuration.GetCompositeAttributeKey(attributePrefix)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set relationships for each + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (IAssociatedTopicBindingModel relationship in sourceList) { + var targetTopic = _topicRepository.Load(relationship.UniqueKey, target); + if (targetTopic is null) { + throw new MappingModelValidationException( + $"The relationship '{relationship.UniqueKey}' mapped in the '{memberAccessor.Name}' property could not be " + + $"located in the repository." + ); } + target.Relationships.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), targetTopic); + } + + } + + /*============================================================================================================================ + | PRIVATE: SET NESTED TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a nested topic property, serializes a topic for each property, and sets it on the target 's + /// collection. + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// The with details about the property's attributes. + /// The prefix to apply to the attributes. + private async Task SetNestedTopicsAsync( + object source, + Topic target, + MemberAccessor memberAccessor, + string? attributePrefix + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = memberAccessor.Configuration; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve source list + \-------------------------------------------------------------------------------------------------------------------------*/ + var sourceList = (IList?)memberAccessor.GetValue(source) ?? new List(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish target collection to store mapped topics + \-------------------------------------------------------------------------------------------------------------------------*/ + var container = target.Children.GetValue(configuration.GetCompositeAttributeKey(attributePrefix)); + if (container is null) { + container = TopicFactory.Create(configuration.GetCompositeAttributeKey(attributePrefix), "List", target); + container.IsHidden = true; } - /*========================================================================================================================== - | PRIVATE: SET NESTED TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a nested topic property, serializes a topic for each property, and sets it on the target 's - /// collection. - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// The with details about the property's attributes. - /// The prefix to apply to the attributes. - private async Task SetNestedTopicsAsync( - object source, - Topic target, - MemberAccessor memberAccessor, - string? attributePrefix - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = memberAccessor.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve source list - \-----------------------------------------------------------------------------------------------------------------------*/ - var sourceList = (IList?)memberAccessor.GetValue(source) ?? new List(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish target collection to store mapped topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var container = target.Children.GetValue(configuration.GetCompositeAttributeKey(attributePrefix)); - if (container is null) { - container = TopicFactory.Create(configuration.GetCompositeAttributeKey(attributePrefix), "List", target); - container.IsHidden = true; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Map the topics from the source collection, and add them to the target collection + \-------------------------------------------------------------------------------------------------------------------------*/ + await PopulateTargetCollectionAsync(sourceList, container.Children).ConfigureAwait(false); + + } + + /*============================================================================================================================ + | PRIVATE: SET REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a reference property, lookup the associated topic and set its on the 's collection. + /// + /// + /// The binding model from which to derive the data. Must inherit from . + /// + /// The entity to map the data to. + /// The with details about the property's attributes. + /// The prefix to apply to the attributes. + private void SetReference( + object source, + Topic target, + MemberAccessor memberAccessor, + string? attributePrefix + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = memberAccessor.Configuration; - /*------------------------------------------------------------------------------------------------------------------------ - | Map the topics from the source collection, and add them to the target collection - \-----------------------------------------------------------------------------------------------------------------------*/ - await PopulateTargetCollectionAsync(sourceList, container.Children).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve source value + \-------------------------------------------------------------------------------------------------------------------------*/ + var modelReference = (IAssociatedTopicBindingModel?)memberAccessor.GetValue(source); + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide error handling + \-------------------------------------------------------------------------------------------------------------------------*/ + if (modelReference is null || modelReference.UniqueKey is null) { + throw new MappingModelValidationException( + $"The {memberAccessor.Name} property must reference an object with its `UniqueKey` property set The " + + $"value may be empty, but it should not be null." + ); } - /*========================================================================================================================== - | PRIVATE: SET REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a reference property, lookup the associated topic and set its on the 's collection. - /// - /// - /// The binding model from which to derive the data. Must inherit from . - /// - /// The entity to map the data to. - /// The with details about the property's attributes. - /// The prefix to apply to the attributes. - private void SetReference( - object source, - Topic target, - MemberAccessor memberAccessor, - string? attributePrefix - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = memberAccessor.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve source value - \-----------------------------------------------------------------------------------------------------------------------*/ - var modelReference = (IAssociatedTopicBindingModel?)memberAccessor.GetValue(source); - - /*------------------------------------------------------------------------------------------------------------------------ - | Provide error handling - \-----------------------------------------------------------------------------------------------------------------------*/ - if (modelReference is null || modelReference.UniqueKey is null) { - throw new MappingModelValidationException( - $"The {memberAccessor.Name} property must reference an object with its `UniqueKey` property set The " + - $"value may be empty, but it should not be null." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify target value + \-------------------------------------------------------------------------------------------------------------------------*/ + var topicReference = _topicRepository.Load(modelReference.UniqueKey, target); - /*------------------------------------------------------------------------------------------------------------------------ - | Identify target value - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicReference = _topicRepository.Load(modelReference.UniqueKey, target); + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide error handling + \-------------------------------------------------------------------------------------------------------------------------*/ + if (modelReference.UniqueKey.Length > 0 && topicReference is null) { + throw new MappingModelValidationException( + $"The topic '{modelReference.UniqueKey}' referenced by the '{source.GetType()}' model's " + + $"'{memberAccessor.Name}' property could not be found." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Provide error handling - \-----------------------------------------------------------------------------------------------------------------------*/ - if (modelReference.UniqueKey.Length > 0 && topicReference is null) { - throw new MappingModelValidationException( - $"The topic '{modelReference.UniqueKey}' referenced by the '{source.GetType()}' model's " + - $"'{memberAccessor.Name}' property could not be found." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Set target attribute + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.GetCompositeAttributeKey(attributePrefix).EndsWith("Id", StringComparison.Ordinal)) { + target.Attributes.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), topicReference?.Id.ToString(CultureInfo.InvariantCulture)); + } + else { + target.References.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), topicReference); + } + + } + + /*============================================================================================================================ + | PRIVATE: POPULATE TARGET COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a source list, will populate a target list based on the configured behavior of the source property. + /// + /// The to pull the binding models from. + /// The target to add the mapped objects to. + private async Task PopulateTargetCollectionAsync( + IList sourceList, + KeyedTopicCollection targetList + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Queue up mapping tasks + \-------------------------------------------------------------------------------------------------------------------------*/ + var taskQueue = new List>(); - /*------------------------------------------------------------------------------------------------------------------------ - | Set target attribute - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.GetCompositeAttributeKey(attributePrefix).EndsWith("Id", StringComparison.Ordinal)) { - target.Attributes.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), topicReference?.Id.ToString(CultureInfo.InvariantCulture)); + //Map child binding model to target collection on the target + foreach (ITopicBindingModel childBindingModel in sourceList) { + Contract.Assume(childBindingModel.Key); + if (targetList.Contains(childBindingModel.Key)) { + taskQueue.Add(MapAsync(childBindingModel, targetList.GetValue(childBindingModel.Key)!)); } else { - target.References.SetValue(configuration.GetCompositeAttributeKey(attributePrefix), topicReference); + taskQueue.Add(MapAsync(childBindingModel)); } - } - /*========================================================================================================================== - | PRIVATE: POPULATE TARGET COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a source list, will populate a target list based on the configured behavior of the source property. - /// - /// The to pull the binding models from. - /// The target to add the mapped objects to. - private async Task PopulateTargetCollectionAsync( - IList sourceList, - KeyedTopicCollection targetList - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Queue up mapping tasks - \-----------------------------------------------------------------------------------------------------------------------*/ - var taskQueue = new List>(); - - //Map child binding model to target collection on the target - foreach (ITopicBindingModel childBindingModel in sourceList) { - Contract.Assume(childBindingModel.Key); - if (targetList.Contains(childBindingModel.Key)) { - taskQueue.Add(MapAsync(childBindingModel, targetList.GetValue(childBindingModel.Key)!)); - } - else { - taskQueue.Add(MapAsync(childBindingModel)); - } - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Remove orphaned topics - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var childTopic in targetList.ToArray()) { - if (sourceList.Cast().Any(model => model.Key == childTopic.Key)) { - continue; - } - targetList.Remove(childTopic); + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove orphaned topics + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var childTopic in targetList.ToArray()) { + if (sourceList.Cast().Any(model => model.Key == childTopic.Key)) { + continue; } + targetList.Remove(childTopic); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Process mapping tasks - \-----------------------------------------------------------------------------------------------------------------------*/ - while (taskQueue.Count > 0) { - var topicTask = await Task.WhenAny(taskQueue).ConfigureAwait(false); - taskQueue.Remove(topicTask); - var topic = await topicTask.ConfigureAwait(false); - if (topic is not null && !targetList.Contains(topic.Key)) { - targetList.Add(topic); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Process mapping tasks + \-------------------------------------------------------------------------------------------------------------------------*/ + while (taskQueue.Count > 0) { + var topicTask = await Task.WhenAny(taskQueue).ConfigureAwait(false); + taskQueue.Remove(topicTask); + var topic = await topicTask.ConfigureAwait(false); + if (topic is not null && !targetList.Contains(topic.Key)) { + targetList.Add(topic); } - } - } //Class -} //Namespace \ No newline at end of file + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/TopicMappingService.cs b/OnTopic/Mapping/TopicMappingService.cs index 3f4ed412..4e10ec5a 100644 --- a/OnTopic/Mapping/TopicMappingService.cs +++ b/OnTopic/Mapping/TopicMappingService.cs @@ -13,1168 +13,1160 @@ using OnTopic.Models; using OnTopic.Repositories; -namespace OnTopic.Mapping { +namespace OnTopic.Mapping; + +/*============================================================================================================================== +| CLASS: TOPIC MAPPING SERVICE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a concrete implementation of the for mapping instances +/// to data transfer objects (such as view models) based on set conventions and attribute-based hints. +/// +/// +/// An instance of an for looking up associated topics during mapping. +/// +/// +/// An instance of an for resolving view model types by name. +/// +public class TopicMappingService(ITopicRepository topicRepository, ITypeLookupService typeLookupService) : ITopicMappingService { /*============================================================================================================================ - | CLASS: TOPIC MAPPING SERVICE + | PRIVATE VARIABLES \---------------------------------------------------------------------------------------------------------------------------*/ + readonly ITopicRepository _topicRepository = Contract.Requires(topicRepository); + readonly ITypeLookupService _typeLookupService = Contract.Requires(typeLookupService); + static readonly TypeAccessor _topicTypeAccessor = TypeAccessorCache.GetTypeAccessor(); + + /*============================================================================================================================ + | METHOD: MAP (DYNAMIC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [return: NotNullIfNotNull(nameof(topic))] + public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) => + await MapAsync(topic, associations, new()).ConfigureAwait(false); + /// - /// Provides a concrete implementation of the for mapping instances - /// to data transfer objects (such as view models) based on set conventions and attribute-based hints. + /// Given a topic, will identify any View Models named, by convention, "{ContentType}TopicViewModel" and populate them + /// according to the rules of the mapping implementation. /// - public class TopicMappingService : ITopicMappingService { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - readonly ITopicRepository _topicRepository; - readonly ITypeLookupService _typeLookupService; - static readonly TypeAccessor _topicTypeAccessor = TypeAccessorCache.GetTypeAccessor(); - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new instance of a with required dependencies. - /// - public TopicMappingService(ITopicRepository topicRepository, ITypeLookupService typeLookupService) { - Contract.Requires(topicRepository, "An instance of an ITopicRepository is required."); - Contract.Requires(typeLookupService, "An instance of an ITypeLookupService is required."); - _topicRepository = topicRepository; - _typeLookupService = typeLookupService; + /// + /// + /// Because the class is using reflection to determine the target View Models, the return type is . + /// These results may need to be cast to a specific type, depending on the context. That said, strongly typed views + /// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known + /// upfront, and it is imperative that it be strongly typed, prefer . + /// + /// + /// Because the target object is being dynamically constructed, it must implement a default constructor. + /// + /// + /// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with + /// recursion in case is referred to multiple times (e.g., a Children collection with + /// set to include ). + /// + /// + /// The entity to derive the data from. + /// Determines what associations the mapping should include, if any. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + /// An instance of the dynamically determined View Model with properties appropriately mapped. + private async Task MapAsync( + Topic? topic, + AssociationTypes associations, + MappedTopicCache cache, + string? attributePrefix = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic is null) { + return null; } - /*========================================================================================================================== - | METHOD: MAP (DYNAMIC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [return: NotNullIfNotNull(nameof(topic))] - public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) => - await MapAsync(topic, associations, new()).ConfigureAwait(false); - - /// - /// Given a topic, will identify any View Models named, by convention, "{ContentType}TopicViewModel" and populate them - /// according to the rules of the mapping implementation. - /// - /// - /// - /// Because the class is using reflection to determine the target View Models, the return type is . - /// These results may need to be cast to a specific type, depending on the context. That said, strongly typed views - /// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known - /// upfront, and it is imperative that it be strongly typed, prefer . - /// - /// - /// Because the target object is being dynamically constructed, it must implement a default constructor. - /// - /// - /// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with - /// recursion in case is referred to multiple times (e.g., a Children collection with - /// set to include ). - /// - /// - /// The entity to derive the data from. - /// Determines what associations the mapping should include, if any. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - /// An instance of the dynamically determined View Model with properties appropriately mapped. - private async Task MapAsync( - Topic? topic, - AssociationTypes associations, - MappedTopicCache cache, - string? attributePrefix = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) { - return null; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Lookup type + \-------------------------------------------------------------------------------------------------------------------------*/ + var viewModelType = _typeLookupService.Lookup($"{topic.ContentType}TopicViewModel", $"{topic.ContentType}ViewModel"); - /*------------------------------------------------------------------------------------------------------------------------ - | Lookup type - \-----------------------------------------------------------------------------------------------------------------------*/ - var viewModelType = _typeLookupService.Lookup($"{topic.ContentType}TopicViewModel", $"{topic.ContentType}ViewModel"); + if (viewModelType is null) { + throw new InvalidTypeException( + $"No class named '{topic.ContentType}TopicViewModel' could be located in any loaded assemblies. This is required " + + $"to map the topic '{topic.GetUniqueKey()}'." + ); + } - if (viewModelType is null) { - throw new InvalidTypeException( - $"No class named '{topic.ContentType}TopicViewModel' could be located in any loaded assemblies. This is required " + - $"to map the topic '{topic.GetUniqueKey()}'." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Perform mapping + \-------------------------------------------------------------------------------------------------------------------------*/ + return await MapAsync(topic, viewModelType, associations, cache, attributePrefix).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Perform mapping - \-----------------------------------------------------------------------------------------------------------------------*/ - return await MapAsync(topic, viewModelType, associations, cache, attributePrefix).ConfigureAwait(false); + } + /// + /// Will map a given to a given , according to the rules of the mapping + /// implementation. + /// + /// + /// + /// Because the class is using reflection to determine the target View Models, the return type is . + /// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views + /// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known + /// upfront, and it is imperative that it be strongly-typed, prefer . + /// + /// + /// Because the target object is being dynamically constructed, it must implement a default constructor. + /// + /// + /// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with + /// recursion in case is referred to multiple times (e.g., a Children collection with + /// set to include ). + /// + /// + /// The entity to derive the data from. + /// The that should be used for the View Model. + /// Determines what associations the mapping should include, if any. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + /// An instance of the dynamically determined View Model with properties appropriately mapped. + private async Task MapAsync( + Topic? topic, + Type type, + AssociationTypes associations, + MappedTopicCache cache, + string? attributePrefix = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic is null || type is null) { + return null; } - /// - /// Will map a given to a given , according to the rules of the mapping - /// implementation. - /// - /// - /// - /// Because the class is using reflection to determine the target View Models, the return type is . - /// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views - /// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known - /// upfront, and it is imperative that it be strongly-typed, prefer . - /// - /// - /// Because the target object is being dynamically constructed, it must implement a default constructor. - /// - /// - /// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with - /// recursion in case is referred to multiple times (e.g., a Children collection with - /// set to include ). - /// - /// - /// The entity to derive the data from. - /// The that should be used for the View Model. - /// Determines what associations the mapping should include, if any. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - /// An instance of the dynamically determined View Model with properties appropriately mapped. - private async Task MapAsync( - Topic? topic, - Type type, - AssociationTypes associations, - MappedTopicCache cache, - string? attributePrefix = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null || type is null) { - return null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle cached objects + \-------------------------------------------------------------------------------------------------------------------------*/ + var target = (object?)null; + + if (cache.TryGetValue(topic.Id, type, out var cacheEntry)) { + target = cacheEntry.MappedTopic; + if (cacheEntry.GetMissingAssociations(associations) == AssociationTypes.None) { + return target; } + //Call MapAsync() with target object to map missing attributes + return await MapAsync(topic, target, associations, cache, attributePrefix).ConfigureAwait(false); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle cached objects - \-----------------------------------------------------------------------------------------------------------------------*/ - var target = (object?)null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + var typeAccessor = TypeAccessorCache.GetTypeAccessor(type); + var properties = typeAccessor.GetMembers(MemberTypes.Property); + var parameters = typeAccessor.ConstructorParameters; + var arguments = new object?[parameters.Count]; + var attributeArguments = (IDictionary)new Dictionary(); + var parameterQueue = new Dictionary>(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Pre-cache entry + >------------------------------------------------------------------------------------------------------------------------- + | In property mapping, we deal with circular references by returning a cached reference. That isn't practical with + | circular references in constructor mapping. To help avoid these, we register a pre-cache entry as IsInitializing, but + | without a mapped object; the TopicMappingCache is expected to throw an exception if an attempt to map that topic to that + | type occurs again prior to the constructor mapping being completed. + \-------------------------------------------------------------------------------------------------------------------------*/ + cache.Preregister(topic.Id, type); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle AttributeDictionary constructor + >------------------------------------------------------------------------------------------------------------------------- + | A model may optionally expose a constructor with a single parameter accepting an AttributeDictionary. In this scenario, + | the TopicMappingService may optionally pass a lightweight AttributeDictionary, allowing the model's constructor to + | populate scalar values, instead of relying on reflection. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (parameters.Count is 1 && parameters[0].Type == typeof(AttributeDictionary)) { + + // This strategy is only performant if there are quite a several scalar properties and they are well-covered by the + // attributes. As a fast heuristic to evaluate this, we expect five or more attributes and three or more compatible + // properties. In practice, this should be benefitial with any more than mapped attributes, but we also expect that most + // topics will have 2-3 excluded or unmapped attributes (e.g., Title, LastModified). With models, we can be a bit more + // intelligent, by excluding any members that are likely compatible with Topic properties, thus exluding e.g., Id, Key, + // WebPath, etc. This doesn't guarantee that the attributes map to the properties, but a more accurate evaluation would + // undermine the performance benefits of this optimization. + if (topic.Attributes.Count >= 5 && properties.Count(p => !p.MaybeCompatible) >= 3) { + var attributes = topic.Attributes.AsAttributeDictionary(true); + arguments[0] = attributes; + attributeArguments = attributes; + } + else { + parameters = new(); + arguments = []; + } - if (cache.TryGetValue(topic.Id, type, out var cacheEntry)) { - target = cacheEntry.MappedTopic; - if (cacheEntry.GetMissingAssociations(associations) == AssociationTypes.None) { - return target; - } - //Call MapAsync() with target object to map missing attributes - return await MapAsync(topic, target, associations, cache, attributePrefix).ConfigureAwait(false); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle other constructors + >------------------------------------------------------------------------------------------------------------------------- + | A model may optionally expose a constructor with multiple parameters, which can be defined via reflection in the same + | way as properties would be. This is especially useful for records using the positional syntax (i.e., where properties + | are defined using the constructor). This also, optionally, provides the model with more control, where needed, over how + | it's constructed. + \-------------------------------------------------------------------------------------------------------------------------*/ + else { + + foreach (var parameter in parameters) { + parameterQueue.Add(parameter.ParameterInfo.Position, GetParameterAsync(topic, associations, parameter, cache, attributePrefix)); } - /*------------------------------------------------------------------------------------------------------------------------ - | Identify parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - var typeAccessor = TypeAccessorCache.GetTypeAccessor(type); - var properties = typeAccessor.GetMembers(MemberTypes.Property); - var parameters = typeAccessor.ConstructorParameters; - var arguments = new object?[parameters.Count]; - var attributeArguments = (IDictionary)new Dictionary(); - var parameterQueue = new Dictionary>(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Pre-cache entry - >------------------------------------------------------------------------------------------------------------------------- - | In property mapping, we deal with circular references by returning a cached reference. That isn't practical with - | circular references in constructor mapping. To help avoid these, we register a pre-cache entry as IsInitializing, but - | without a mapped object; the TopicMappingCache is expected to throw an exception if an attempt to map that topic to that - | type occurs again prior to the constructor mapping being completed. - \-----------------------------------------------------------------------------------------------------------------------*/ - cache.Preregister(topic.Id, type); - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle AttributeDictionary constructor - >------------------------------------------------------------------------------------------------------------------------- - | A model may optionally expose a constructor with a single parameter accepting an AttributeDictionary. In this scenario, - | the TopicMappingService may optionally pass a lightweight AttributeDictionary, allowing the model's constructor to - | populate scalar values, instead of relying on reflection. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (parameters.Count is 1 && parameters[0].Type == typeof(AttributeDictionary)) { - - // This strategy is only performant if there are quite a several scalar properties and they are well-covered by the - // attributes. As a fast heuristic to evaluate this, we expect five or more attributes and three or more compatible - // properties. In practice, this should be benefitial with any more than mapped attributes, but we also expect that most - // topics will have 2-3 excluded or unmapped attributes (e.g., Title, LastModified). With models, we can be a bit more - // intelligent, by excluding any members that are likely compatible with Topic properties, thus exluding e.g., Id, Key, - // WebPath, etc. This doesn't guarantee that the attributes map to the properties, but a more accurate evaluation would - // undermine the performance benefits of this optimization. - if (topic.Attributes.Count >= 5 && properties.Count(p => !p.MaybeCompatible) >= 3) { - var attributes = topic.Attributes.AsAttributeDictionary(true); - arguments[0] = attributes; - attributeArguments = attributes; - } - else { - parameters = new(); - arguments = Array.Empty(); - } + await Task.WhenAll(parameterQueue.Values).ConfigureAwait(false); + foreach (var parameter in parameterQueue) { + arguments[parameter.Key] = await parameter.Value.ConfigureAwait(false); } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle other constructors - >------------------------------------------------------------------------------------------------------------------------- - | A model may optionally expose a constructor with multiple parameters, which can be defined via reflection in the same - | way as properties would be. This is especially useful for records using the positional syntax (i.e., where properties - | are defined using the constructor). This also, optionally, provides the model with more control, where needed, over how - | it's constructed. - \-----------------------------------------------------------------------------------------------------------------------*/ - else { + } - foreach (var parameter in parameters) { - parameterQueue.Add(parameter.ParameterInfo.Position, GetParameterAsync(topic, associations, parameter, cache, attributePrefix)); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize object + \-------------------------------------------------------------------------------------------------------------------------*/ + target = Activator.CreateInstance(type, arguments); - await Task.WhenAll(parameterQueue.Values).ConfigureAwait(false); + Contract.Assume( + target, + $"The target type '{type}' could not be properly constructed, as required to map the topic '{topic.GetUniqueKey()}'." + ); - foreach (var parameter in parameterQueue) { - arguments[parameter.Key] = await parameter.Value.ConfigureAwait(false); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Cache object + \-------------------------------------------------------------------------------------------------------------------------*/ + cache.Register(topic.Id, associations, target); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Loop through properties, mapping each one + \-------------------------------------------------------------------------------------------------------------------------*/ + var propertyQueue = new List(); + var mappedParameters = parameters.Select(p => p.Name).Union(attributeArguments.Select(a => a.Key)).ToArray(); + foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { + if (!mappedParameters.Contains(property.Name, StringComparer.OrdinalIgnoreCase)) { + propertyQueue.Add(SetPropertyAsync(topic, target, associations, property, cache, attributePrefix, false)); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize object - \-----------------------------------------------------------------------------------------------------------------------*/ - target = Activator.CreateInstance(type, arguments); + await Task.WhenAll([.. propertyQueue]).ConfigureAwait(false); - Contract.Assume( - target, - $"The target type '{type}' could not be properly constructed, as required to map the topic '{topic.GetUniqueKey()}'." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Cache object - \-----------------------------------------------------------------------------------------------------------------------*/ - cache.Register(topic.Id, associations, target); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return target + \-------------------------------------------------------------------------------------------------------------------------*/ + return target; - /*------------------------------------------------------------------------------------------------------------------------ - | Loop through properties, mapping each one - \-----------------------------------------------------------------------------------------------------------------------*/ - var propertyQueue = new List(); - var mappedParameters = parameters.Select(p => p.Name).Union(attributeArguments.Select(a => a.Key)); + } - foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { - if (!mappedParameters.Contains(property.Name, StringComparer.OrdinalIgnoreCase)) { - propertyQueue.Add(SetPropertyAsync(topic, target, associations, property, cache, attributePrefix, false)); - } - } + /*============================================================================================================================ + | METHOD: MAP (T) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class { + if (typeof(Topic).IsAssignableFrom(typeof(T))) { + return topic as T; + } + return (T?)await MapAsync(topic, typeof(T), associations, new()).ConfigureAwait(false); + } - await Task.WhenAll(propertyQueue.ToArray()).ConfigureAwait(false); + /*============================================================================================================================ + | METHOD: MAP (OBJECTS) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public async Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) { + Contract.Requires(target, nameof(target)); + return await MapAsync(topic, target, associations, new()).ConfigureAwait(false); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return target - \-----------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a topic and an instance of a DTO, will populate the DTO according to the default mapping rules. + /// + /// The entity to derive the data from. + /// The target object to map the data to. + /// Determines what associations the mapping should include, if any. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + /// + /// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with + /// recursion in case is referred to multiple times (e.g., a Children collection with set to include ). + /// + /// + /// The target view model with the properties appropriately mapped. + /// + private async Task MapAsync( + Topic? topic, + object target, + AssociationTypes associations, + MappedTopicCache cache, + string? attributePrefix = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic is null) { return target; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle topics + \-------------------------------------------------------------------------------------------------------------------------*/ + if (target is Topic) { + return topic; } - /*========================================================================================================================== - | METHOD: MAP (T) + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle cached objects + >------------------------------------------------------------------------------------------------------------------------- + | If the cache contains an entry, check to make sure it includes all of the requested associations. If it does, return it. + | If it doesn't, determine the missing associations and request to have those mapped. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class { - if (typeof(Topic).IsAssignableFrom(typeof(T))) { - return topic as T; + if (cache.TryGetValue(topic.Id, target.GetType(), out var cacheEntry)) { + associations = cacheEntry.GetMissingAssociations(associations); + target = cacheEntry.MappedTopic; + if (associations is AssociationTypes.None) { + return cacheEntry.MappedTopic; } - return (T?)await MapAsync(topic, typeof(T), associations, new()).ConfigureAwait(false); + cacheEntry.AddMissingAssociations(associations); + } + else if (!topic.IsNew) { + cache.Register( + topic.Id, + associations, + target + ); } - /*========================================================================================================================== - | METHOD: MAP (OBJECTS) + /*-------------------------------------------------------------------------------------------------------------------------- + | Loop through properties, mapping each one \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public async Task MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) { - Contract.Requires(target, nameof(target)); - return await MapAsync(topic, target, associations, new()).ConfigureAwait(false); + var taskQueue = new List(); + var typeAccessor = TypeAccessorCache.GetTypeAccessor(target.GetType()); + + foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { + taskQueue.Add(SetPropertyAsync(topic, target, associations, property, cache, attributePrefix, cacheEntry is not null)); } + await Task.WhenAll([.. taskQueue]).ConfigureAwait(false); - /// - /// Given a topic and an instance of a DTO, will populate the DTO according to the default mapping rules. - /// - /// The entity to derive the data from. - /// The target object to map the data to. - /// Determines what associations the mapping should include, if any. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - /// - /// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with - /// recursion in case is referred to multiple times (e.g., a Children collection with set to include ). - /// - /// - /// The target view model with the properties appropriately mapped. - /// - private async Task MapAsync( - Topic? topic, - object target, - AssociationTypes associations, - MappedTopicCache cache, - string? attributePrefix = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic is null) { - return target; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return result + \-------------------------------------------------------------------------------------------------------------------------*/ + return target; - /*------------------------------------------------------------------------------------------------------------------------ - | Handle topics - \-----------------------------------------------------------------------------------------------------------------------*/ - if (target is Topic) { - return topic; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle cached objects - >------------------------------------------------------------------------------------------------------------------------- - | If the cache contains an entry, check to make sure it includes all of the requested associations. If it does, return it. - | If it doesn't, determine the missing associations and request to have those mapped. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (cache.TryGetValue(topic.Id, target.GetType(), out var cacheEntry)) { - associations = cacheEntry.GetMissingAssociations(associations); - target = cacheEntry.MappedTopic; - if (associations is AssociationTypes.None) { - return cacheEntry.MappedTopic; - } - cacheEntry.AddMissingAssociations(associations); - } - else if (!topic.IsNew) { - cache.Register( - topic.Id, - associations, - target - ); - } + /*============================================================================================================================ + | PRIVATE: GET PARAMETER (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , retrieves the appropriate value from the corresponding + /// topic, while honoring . + /// + /// The entity to derive the data from. + /// Determines what associations the mapping should include, if any. + /// Information related to the current parameter. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + private async Task GetParameterAsync( + Topic source, + AssociationTypes associations, + ParameterMetadata parameter, + MappedTopicCache cache, + string? attributePrefix = null + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish per-property variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = parameter.Configuration; - /*------------------------------------------------------------------------------------------------------------------------ - | Loop through properties, mapping each one - \-----------------------------------------------------------------------------------------------------------------------*/ - var taskQueue = new List(); - var typeAccessor = TypeAccessorCache.GetTypeAccessor(target.GetType()); + /*-------------------------------------------------------------------------------------------------------------------------- + | Bypass if mapping is disabled + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.DisableMapping) { + return parameter.ParameterInfo.DefaultValue; + } - foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) { - taskQueue.Add(SetPropertyAsync(topic, target, associations, property, cache, attributePrefix, cacheEntry is not null)); - } - await Task.WhenAll(taskQueue.ToArray()).ConfigureAwait(false); + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle [MapToParent] attribute + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.MapToParent) { + return await MapAsync( + source, + parameter.Type, + associations, + cache, + configuration.AttributePrefix + attributePrefix + ).ConfigureAwait(false); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return result - \-----------------------------------------------------------------------------------------------------------------------*/ - return target; + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine value + \-------------------------------------------------------------------------------------------------------------------------*/ + var value = await GetValue(source, parameter.Type, associations, parameter, cache, attributePrefix, false).ConfigureAwait(false); + if (value is null && parameter.IsList) { + return await getList(parameter.Type).ConfigureAwait(false); } - /*========================================================================================================================== - | PRIVATE: GET PARAMETER (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , retrieves the appropriate value from the corresponding - /// topic, while honoring . - /// - /// The entity to derive the data from. - /// Determines what associations the mapping should include, if any. - /// Information related to the current parameter. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - private async Task GetParameterAsync( - Topic source, - AssociationTypes associations, - ParameterMetadata parameter, - MappedTopicCache cache, - string? attributePrefix = null - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish per-property variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = parameter.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Bypass if mapping is disabled - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.DisableMapping) { - return parameter.ParameterInfo.DefaultValue; - } + return value; - /*------------------------------------------------------------------------------------------------------------------------ - | Handle [MapToParent] attribute - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.MapToParent) { - return await MapAsync( - source, - parameter.Type, - associations, - cache, - configuration.AttributePrefix + attributePrefix - ).ConfigureAwait(false); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Get List Function + \-------------------------------------------------------------------------------------------------------------------------*/ + async Task getList(Type targetType) { - /*------------------------------------------------------------------------------------------------------------------------ - | Determine value - \-----------------------------------------------------------------------------------------------------------------------*/ - var value = await GetValue(source, parameter.Type, associations, parameter, cache, attributePrefix, false).ConfigureAwait(false); + var sourceList = GetSourceCollection(source, associations, parameter, attributePrefix); + var targetList = InitializeCollection(targetType); - if (value is null && parameter.IsList) { - return await getList(parameter.Type).ConfigureAwait(false); + if (sourceList is null || targetList is null) { + return (IList?)null; } - return value; + await PopulateTargetCollectionAsync(sourceList, targetList, parameter, cache).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Get List Function - \-----------------------------------------------------------------------------------------------------------------------*/ - async Task getList(Type targetType) { + return targetList; - var sourceList = GetSourceCollection(source, associations, parameter, attributePrefix); - var targetList = InitializeCollection(targetType); + } - if (sourceList is null || targetList is null) { - return (IList?)null; - } + } - await PopulateTargetCollectionAsync(sourceList, targetList, parameter, cache).ConfigureAwait(false); + /*============================================================================================================================ + | PRIVATE: SET PROPERTY (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function that evaluates each property on the target object and attempts to retrieve a value from the source + /// based on predetermined conventions. + /// + /// The entity to derive the data from. + /// The target object to map the data to. + /// Determines what associations the mapping should include, if any. + /// Information related to the current property. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + /// Determines if properties not associated with associations should be mapped. + private async Task SetPropertyAsync( + Topic source, + object target, + AssociationTypes associations, + MemberAccessor propertyAccessor, + MappedTopicCache cache, + string? attributePrefix = null, + bool mapAssociationsOnly = false + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish per-property variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = propertyAccessor.Configuration; - return targetList; + /*-------------------------------------------------------------------------------------------------------------------------- + | Bypass if mapping is disabled + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.DisableMapping) { + return; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle [MapToParent] attribute + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.MapToParent) { + var targetProperty = propertyAccessor.GetValue(target); + if (targetProperty is not null) { + await MapAsync( + source, + targetProperty, + associations, + cache, + configuration.AttributePrefix + attributePrefix + ).ConfigureAwait(false); } - } - /*========================================================================================================================== - | PRIVATE: SET PROPERTY (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function that evaluates each property on the target object and attempts to retrieve a value from the source - /// based on predetermined conventions. - /// - /// The entity to derive the data from. - /// The target object to map the data to. - /// Determines what associations the mapping should include, if any. - /// Information related to the current property. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - /// Determines if properties not associated with associations should be mapped. - private async Task SetPropertyAsync( - Topic source, - object target, - AssociationTypes associations, - MemberAccessor propertyAccessor, - MappedTopicCache cache, - string? attributePrefix = null, - bool mapAssociationsOnly = false - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish per-property variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = propertyAccessor.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Bypass if mapping is disabled - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.DisableMapping) { - return; + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine value + \-------------------------------------------------------------------------------------------------------------------------*/ + else { + var value = await GetValue(source, propertyAccessor.Type, associations, propertyAccessor, cache, attributePrefix, mapAssociationsOnly).ConfigureAwait(false); + if (value is null && propertyAccessor.IsList) { + await SetCollectionValueAsync(source, target, associations, propertyAccessor, cache, attributePrefix).ConfigureAwait(false); } - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle [MapToParent] attribute - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.MapToParent) { - var targetProperty = propertyAccessor.GetValue(target); - if (targetProperty is not null) { - await MapAsync( - source, - targetProperty, - associations, - cache, - configuration.AttributePrefix + attributePrefix - ).ConfigureAwait(false); - } + else if (value != null && propertyAccessor.CanWrite) { + propertyAccessor.SetValue(target, value, true); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Determine value - \-----------------------------------------------------------------------------------------------------------------------*/ - else { - var value = await GetValue(source, propertyAccessor.Type, associations, propertyAccessor, cache, attributePrefix, mapAssociationsOnly).ConfigureAwait(false); - if (value is null && propertyAccessor.IsList) { - await SetCollectionValueAsync(source, target, associations, propertyAccessor, cache, attributePrefix).ConfigureAwait(false); - } - else if (value != null && propertyAccessor.CanWrite) { - propertyAccessor.SetValue(target, value, true); - } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate fields + \-------------------------------------------------------------------------------------------------------------------------*/ + propertyAccessor.Validate(target); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate fields - \-----------------------------------------------------------------------------------------------------------------------*/ - propertyAccessor.Validate(target); + } - } + /*============================================================================================================================ + | PRIVATE: GET VALUE (ASYNC) + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function that retrieves a value from the source based on predetermined conventions. + /// + /// The entity to derive the data from. + /// The of the target parameter or property. + /// Determines what associations the mapping should include, if any. + /// Information related to the current parameter or property. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + /// Determines if properties not associated with associations should be mapped. + private async Task GetValue( + Topic source, + Type targetType, + AssociationTypes associations, + ItemMetadata itemMetadata, + MappedTopicCache cache, + string? attributePrefix = "", + bool mapAssociationsOnly = false + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = itemMetadata.Configuration; - /*========================================================================================================================== - | PRIVATE: GET VALUE (ASYNC) - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function that retrieves a value from the source based on predetermined conventions. - /// - /// The entity to derive the data from. - /// The of the target parameter or property. - /// Determines what associations the mapping should include, if any. - /// Information related to the current parameter or property. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - /// Determines if properties not associated with associations should be mapped. - private async Task GetValue( - Topic source, - Type targetType, - AssociationTypes associations, - ItemMetadata itemMetadata, - MappedTopicCache cache, - string? attributePrefix = "", - bool mapAssociationsOnly = false - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = itemMetadata.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Assign default value - \-----------------------------------------------------------------------------------------------------------------------*/ - var value = (object?)null; - if (!mapAssociationsOnly && configuration.DefaultValue is not null) { - value = configuration.DefaultValue; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Assign default value + \-------------------------------------------------------------------------------------------------------------------------*/ + var value = (object?)null; + if (!mapAssociationsOnly && configuration.DefaultValue is not null) { + value = configuration.DefaultValue; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle by type, attribute - \-----------------------------------------------------------------------------------------------------------------------*/ - if (TryGetCompatibleProperty(source, targetType, itemMetadata, attributePrefix, out var compatibleValue)) { - value = compatibleValue; - } - else if (itemMetadata.IsConvertible) { - if (!mapAssociationsOnly) { - value = GetScalarValue(source, itemMetadata, attributePrefix); - } - } - else if (itemMetadata.IsList) { - return null; - } - else if (configuration.GetCompositeAttributeKey(attributePrefix) is "Parent") { - if (associations.HasFlag(AssociationTypes.Parents) && source.Parent is not null) { - value = await GetTopicReferenceAsync(source.Parent, targetType, itemMetadata, cache).ConfigureAwait(false); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle by type, attribute + \-------------------------------------------------------------------------------------------------------------------------*/ + if (TryGetCompatibleProperty(source, targetType, itemMetadata, attributePrefix, out var compatibleValue)) { + value = compatibleValue; + } + else if (itemMetadata.IsConvertible) { + if (!mapAssociationsOnly) { + value = GetScalarValue(source, itemMetadata, attributePrefix); } - else if (configuration.MapToParent) { - return null; + } + else if (itemMetadata.IsList) { + return null; + } + else if (configuration.GetCompositeAttributeKey(attributePrefix) is "Parent") { + if (associations.HasFlag(AssociationTypes.Parents) && source.Parent is not null) { + value = await GetTopicReferenceAsync(source.Parent, targetType, itemMetadata, cache).ConfigureAwait(false); } - else if (itemMetadata.Type.IsClass && associations.HasFlag(AssociationTypes.References)) { - var topicReference = getTopicReference(); - if (topicReference is not null) { - value = await GetTopicReferenceAsync(topicReference, targetType, itemMetadata, cache).ConfigureAwait(false); - } + } + else if (configuration.MapToParent) { + return null; + } + else if (itemMetadata.Type.IsClass && associations.HasFlag(AssociationTypes.References)) { + var topicReference = getTopicReference(); + if (topicReference is not null) { + value = await GetTopicReferenceAsync(topicReference, targetType, itemMetadata, cache).ConfigureAwait(false); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return value - \-----------------------------------------------------------------------------------------------------------------------*/ - return value; - - /*------------------------------------------------------------------------------------------------------------------------ - | Get Topic Reference - \-----------------------------------------------------------------------------------------------------------------------*/ - Topic? getTopicReference() { - - // Check for standard topic reference - var topicReference = source.References.GetValue(configuration.GetCompositeAttributeKey(attributePrefix)); - if (topicReference is not null) { - return topicReference; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value + \-------------------------------------------------------------------------------------------------------------------------*/ + return value; - int topicReferenceId; - if (configuration.GetCompositeAttributeKey(attributePrefix).EndsWith("Id", StringComparison.OrdinalIgnoreCase)) { - topicReferenceId = source.Attributes.GetInteger(configuration.GetCompositeAttributeKey(attributePrefix), 0); - } - else { - topicReferenceId = source.Attributes.GetInteger($"{configuration.GetCompositeAttributeKey(attributePrefix)}Id", 0); - } - if (topicReferenceId > 0) { - topicReference = _topicRepository.Load(topicReferenceId, source); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Get Topic Reference + \-------------------------------------------------------------------------------------------------------------------------*/ + Topic? getTopicReference() { + // Check for standard topic reference + var topicReference = source.References.GetValue(configuration.GetCompositeAttributeKey(attributePrefix)); + if (topicReference is not null) { return topicReference; + } + int topicReferenceId; + if (configuration.GetCompositeAttributeKey(attributePrefix).EndsWith("Id", StringComparison.OrdinalIgnoreCase)) { + topicReferenceId = source.Attributes.GetInteger(configuration.GetCompositeAttributeKey(attributePrefix), 0); } + else { + topicReferenceId = source.Attributes.GetInteger($"{configuration.GetCompositeAttributeKey(attributePrefix)}Id", 0); + } + if (topicReferenceId > 0) { + topicReference = _topicRepository.Load(topicReferenceId, source); + } + + return topicReference; } - /*========================================================================================================================== - | PRIVATE: GET SCALAR VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a scalar property from a . - /// - /// - /// The method will attempt to retrieve the value from the - /// based on, in order, the 's Get{Property}() method, - /// {Property} property, and, finally, its collection (using ). - /// - /// The source from which to pull the value. - /// The with details about the property's attributes. - /// The prefix to apply to the attributes. - /// - private static object? GetScalarValue(Topic source, ItemMetadata itemMetadata, string? attributePrefix) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = itemMetadata.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to retrieve value from topic.Get{Property}() - \-----------------------------------------------------------------------------------------------------------------------*/ - var typeAccessor = GetTopicAccessor(source.GetType()); - - var attributeValue = (string?)null; - var maybeCompatible = source.GetType() != typeof(Topic) || itemMetadata.MaybeCompatible; - - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to retrieve value from topic.{Property} - \-----------------------------------------------------------------------------------------------------------------------*/ - if (maybeCompatible) { - attributeValue = typeAccessor.GetMethodValue(source, $"Get{configuration.GetCompositeAttributeKey(attributePrefix)}")?.ToString(); - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to retrieve value from topic.{Property} - \-----------------------------------------------------------------------------------------------------------------------*/ - if (maybeCompatible && attributeValue is null) { - attributeValue = typeAccessor.GetPropertyValue(source, configuration.GetCompositeAttributeKey(attributePrefix))?.ToString(); - } + /*============================================================================================================================ + | PRIVATE: GET SCALAR VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a scalar property from a . + /// + /// + /// The method will attempt to retrieve the value from the + /// based on, in order, the 's Get{Property}() method, + /// {Property} property, and, finally, its collection (using ). + /// + /// The source from which to pull the value. + /// The with details about the property's attributes. + /// The prefix to apply to the attributes. + /// + private static string? GetScalarValue(Topic source, ItemMetadata itemMetadata, string? attributePrefix) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = itemMetadata.Configuration; - /*------------------------------------------------------------------------------------------------------------------------ - | Otherwise, attempt to retrieve value from topic.Attributes.GetValue({Property}) - \-----------------------------------------------------------------------------------------------------------------------*/ - attributeValue ??= source.Attributes.GetValue( - configuration.GetCompositeAttributeKey(attributePrefix), - configuration.DefaultValue?.ToString(), - configuration.InheritValue - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to retrieve value from topic.Get{Property}() + \-------------------------------------------------------------------------------------------------------------------------*/ + var typeAccessor = GetTopicAccessor(source.GetType()); - /*------------------------------------------------------------------------------------------------------------------------ - | Return value - \-----------------------------------------------------------------------------------------------------------------------*/ - return attributeValue; + var attributeValue = (string?)null; + var maybeCompatible = source.GetType() != typeof(Topic) || itemMetadata.MaybeCompatible; + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to retrieve value from topic.{Property} + \-------------------------------------------------------------------------------------------------------------------------*/ + if (maybeCompatible) { + attributeValue = typeAccessor.GetMethodValue(source, $"Get{configuration.GetCompositeAttributeKey(attributePrefix)}")?.ToString(); } - /*========================================================================================================================== - | PRIVATE: INITIALIZE COLLECTION + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to retrieve value from topic.{Property} \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a collection type, attempts to initialize a compatible type. - /// - /// The of collection to initialize. - private static IList? InitializeCollection(Type targetType) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to create specific type - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!targetType.IsInterface && !targetType.IsAbstract) { - return (IList?)Activator.CreateInstance(targetType); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle types that don't implement IList or IEnumerable - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!targetType.IsGenericType) { - return null; - } + if (maybeCompatible && attributeValue is null) { + attributeValue = typeAccessor.GetPropertyValue(source, configuration.GetCompositeAttributeKey(attributePrefix))?.ToString(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to create generic list - \-----------------------------------------------------------------------------------------------------------------------*/ - var parameters = targetType.GetGenericArguments(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Otherwise, attempt to retrieve value from topic.Attributes.GetValue({Property}) + \-------------------------------------------------------------------------------------------------------------------------*/ + attributeValue ??= source.Attributes.GetValue( + configuration.GetCompositeAttributeKey(attributePrefix), + configuration.DefaultValue?.ToString(), + configuration.InheritValue + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value + \-------------------------------------------------------------------------------------------------------------------------*/ + return attributeValue; - if (parameters.Length != 1) { - return null; - } + } - var genericType = typeof(List<>); - var concreteType = genericType.MakeGenericType(parameters); + /*============================================================================================================================ + | PRIVATE: INITIALIZE COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a collection type, attempts to initialize a compatible type. + /// + /// The of collection to initialize. + private static IList? InitializeCollection(Type targetType) { - return (IList?)Activator.CreateInstance(concreteType); + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to create specific type + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!targetType.IsInterface && !targetType.IsAbstract) { + return (IList?)Activator.CreateInstance(targetType); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle types that don't implement IList or IEnumerable + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!targetType.IsGenericType) { + return null; } - /*========================================================================================================================== - | PRIVATE: SET COLLECTION VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a collection property, identifies a source collection, maps the values to DTOs, and attempts to add them to the - /// target collection. - /// - /// - /// Given a collection on a DTO, attempts to identify a source - /// collection on the . Collections can be mapped to , , or to a nested topic (which will be part of - /// ). By default, will attempt to map based on the - /// property name, though this behavior can be modified using the , based on annotations - /// on the DTO. - /// - /// The source from which to pull the value. - /// The target DTO on which to set the property value. - /// Determines what associations the mapping should include, if any. - /// The with details about the property's attributes. - /// A cache to keep track of already-mapped object instances. - /// The prefix to apply to the attributes. - private async Task SetCollectionValueAsync( - Topic source, - object target, - AssociationTypes associations, - MemberAccessor memberAccessor, - MappedTopicCache cache, - string? attributePrefix - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Ensure target list is created - \-----------------------------------------------------------------------------------------------------------------------*/ - var targetList = (IList?)memberAccessor.GetValue(target); - if (targetList is null) { - targetList = InitializeCollection(memberAccessor.Type); - memberAccessor.SetValue(target, targetList); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to create generic list + \-------------------------------------------------------------------------------------------------------------------------*/ + var parameters = targetType.GetGenericArguments(); - Contract.Assume( - targetList, - $"The target list type, '{memberAccessor.Type}', could not be properly constructed, as required to " + - $"map the '{memberAccessor.Name}' property on the '{target?.GetType().Name}' object." - ); + if (parameters.Length != 1) { + return null; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish source collection to store topics to be mapped - \-----------------------------------------------------------------------------------------------------------------------*/ - var sourceList = GetSourceCollection(source, associations, memberAccessor, attributePrefix); + var genericType = typeof(List<>); + var concreteType = genericType.MakeGenericType(parameters); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate that source collection was identified - \-----------------------------------------------------------------------------------------------------------------------*/ - if (sourceList is null) return; + return (IList?)Activator.CreateInstance(concreteType); - /*------------------------------------------------------------------------------------------------------------------------ - | Map the topics from the source collection, and add them to the target collection - \-----------------------------------------------------------------------------------------------------------------------*/ - await PopulateTargetCollectionAsync(sourceList, targetList, memberAccessor, cache).ConfigureAwait(false); + } + /*============================================================================================================================ + | PRIVATE: SET COLLECTION VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a collection property, identifies a source collection, maps the values to DTOs, and attempts to add them to the + /// target collection. + /// + /// + /// Given a collection on a DTO, attempts to identify a source + /// collection on the . Collections can be mapped to , , or to a nested topic (which will be part of + /// ). By default, will attempt to map based on the + /// property name, though this behavior can be modified using the , based on annotations + /// on the DTO. + /// + /// The source from which to pull the value. + /// The target DTO on which to set the property value. + /// Determines what associations the mapping should include, if any. + /// The with details about the property's attributes. + /// A cache to keep track of already-mapped object instances. + /// The prefix to apply to the attributes. + private async Task SetCollectionValueAsync( + Topic source, + object target, + AssociationTypes associations, + MemberAccessor memberAccessor, + MappedTopicCache cache, + string? attributePrefix + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Ensure target list is created + \-------------------------------------------------------------------------------------------------------------------------*/ + var targetList = (IList?)memberAccessor.GetValue(target); + if (targetList is null) { + targetList = InitializeCollection(memberAccessor.Type); + memberAccessor.SetValue(target, targetList); } - /*========================================================================================================================== - | PRIVATE: GET SOURCE COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a source topic and a property configuration, attempts to identify a source collection that maps to the property. - /// - /// - /// Given a collection on a target DTO, attempts to identify a source collection on the - /// . Collections can be mapped to , , or to a nested topic (which will be part of - /// ). By default, will attempt to map based on the - /// property name, though this behavior can be modified using the , based on annotations - /// on the target DTO. - /// - /// The source from which to pull the value. - /// Determines what associations the mapping should include, if any. - /// The with details about the property's attributes. - /// The prefix to apply to the attributes. - private IList GetSourceCollection( - Topic source, - AssociationTypes associations, - ItemMetadata itemMetadata, - string? attributePrefix - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish source collection to store topics to be mapped - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = itemMetadata.Configuration; - var listSource = (IList)Array.Empty(); - var collectionKey = configuration.CollectionKey; - var collectionType = configuration.CollectionType; - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle children - \-----------------------------------------------------------------------------------------------------------------------*/ - listSource = getCollection( - CollectionType.Children, - s => true, - () => source.Children.ToList() - ); + Contract.Assume( + targetList, + $"The target list type, '{memberAccessor.Type}', could not be properly constructed, as required to " + + $"map the '{memberAccessor.Name}' property on the '{target?.GetType().Name}' object." + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle (outgoing) relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - listSource = getCollection( - CollectionType.Relationship, - source.Relationships.Contains, - () => source.Relationships.GetValues(collectionKey) - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish source collection to store topics to be mapped + \-------------------------------------------------------------------------------------------------------------------------*/ + var sourceList = GetSourceCollection(source, associations, memberAccessor, attributePrefix); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle nested topics, or children corresponding to the property name - \-----------------------------------------------------------------------------------------------------------------------*/ - listSource = getCollection( - CollectionType.NestedTopics, - source.Children.Contains, - () => source.Children[collectionKey].Children - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate that source collection was identified + \-------------------------------------------------------------------------------------------------------------------------*/ + if (sourceList is null) return; - /*------------------------------------------------------------------------------------------------------------------------ - | Handle (incoming) relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - listSource = getCollection( - CollectionType.IncomingRelationship, - source.IncomingRelationships.Contains, - () => source.IncomingRelationships.GetValues(collectionKey) - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Map the topics from the source collection, and add them to the target collection + \-------------------------------------------------------------------------------------------------------------------------*/ + await PopulateTargetCollectionAsync(sourceList, targetList, memberAccessor, cache).ConfigureAwait(false); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle other strongly typed source collections - \-----------------------------------------------------------------------------------------------------------------------*/ - //The following allows a target collection to be mapped to an IList source collection. This is valuable for custom, - //curated collections defined on e.g. derivatives of Topic, but which don't otherwise map to a specific collection type. - //For example, the ContentTypeDescriptor's AttributeDescriptors collection, which provides a rollup of - //AttributeDescriptors from the current ContentTypeDescriptor, as well as all of its ascendents. - if (listSource.Count == 0) { - var sourceProperty = TypeAccessorCache.GetTypeAccessor(source.GetType()).GetMember(configuration.GetCompositeAttributeKey(attributePrefix)); - if ( - sourceProperty?.GetValue(source) is IList sourcePropertyValue && - sourcePropertyValue.Count > 0 && - sourcePropertyValue[0] is Topic - ) { - listSource = getCollection( - CollectionType.MappedCollection, - s => true, - () => sourcePropertyValue.Cast().ToList() - ); - } - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Handle Metadata relationship - \-----------------------------------------------------------------------------------------------------------------------*/ - if (listSource.Count == 0 && !String.IsNullOrWhiteSpace(configuration.MetadataKey)) { - var metadataKey = $"Root:Configuration:Metadata:{configuration.MetadataKey}:LookupList"; - var metadataParent = _topicRepository.Load(metadataKey, source); - if (metadataParent is not null) { - listSource = metadataParent.Children.ToList(); - } - } + /*============================================================================================================================ + | PRIVATE: GET SOURCE COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a source topic and a property configuration, attempts to identify a source collection that maps to the property. + /// + /// + /// Given a collection on a target DTO, attempts to identify a source collection on the + /// . Collections can be mapped to , , or to a nested topic (which will be part of + /// ). By default, will attempt to map based on the + /// property name, though this behavior can be modified using the , based on annotations + /// on the target DTO. + /// + /// The source from which to pull the value. + /// Determines what associations the mapping should include, if any. + /// The with details about the property's attributes. + /// The prefix to apply to the attributes. + private IList GetSourceCollection( + Topic source, + AssociationTypes associations, + ItemMetadata itemMetadata, + string? attributePrefix + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish source collection to store topics to be mapped + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = itemMetadata.Configuration; + var listSource = (IList)[]; + var collectionKey = configuration.CollectionKey; + var collectionType = configuration.CollectionType; - /*------------------------------------------------------------------------------------------------------------------------ - | Handle flattening of children - \-----------------------------------------------------------------------------------------------------------------------*/ - if (configuration.FlattenChildren) { - var flattenedList = new List(); - listSource.ToList().ForEach(t => FlattenTopicGraph(t, flattenedList)); - listSource = flattenedList; + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle children + \-------------------------------------------------------------------------------------------------------------------------*/ + listSource = getCollection( + CollectionType.Children, + s => true, + () => [.. source.Children] + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle (outgoing) relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + listSource = getCollection( + CollectionType.Relationship, + source.Relationships.Contains, + () => source.Relationships.GetValues(collectionKey) + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle nested topics, or children corresponding to the property name + \-------------------------------------------------------------------------------------------------------------------------*/ + listSource = getCollection( + CollectionType.NestedTopics, + source.Children.Contains, + () => source.Children[collectionKey].Children + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle (incoming) relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + listSource = getCollection( + CollectionType.IncomingRelationship, + source.IncomingRelationships.Contains, + () => source.IncomingRelationships.GetValues(collectionKey) + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle other strongly typed source collections + \-------------------------------------------------------------------------------------------------------------------------*/ + //The following allows a target collection to be mapped to an IList source collection. This is valuable for custom, + //curated collections defined on e.g. derivatives of Topic, but which don't otherwise map to a specific collection type. + //For example, the ContentTypeDescriptor's AttributeDescriptors collection, which provides a rollup of + //AttributeDescriptors from the current ContentTypeDescriptor, as well as all of its ascendents. + if (listSource.Count == 0) { + var sourceProperty = TypeAccessorCache.GetTypeAccessor(source.GetType()).GetMember(configuration.GetCompositeAttributeKey(attributePrefix)); + if ( + sourceProperty?.GetValue(source) is IList sourcePropertyValue && + sourcePropertyValue.Count > 0 && + sourcePropertyValue[0] is Topic + ) { + listSource = getCollection( + CollectionType.MappedCollection, + s => true, + () => [.. sourcePropertyValue.Cast()] + ); } + } - return listSource; - - /*------------------------------------------------------------------------------------------------------------------------ - | Provide local function for evaluating current collection - \-----------------------------------------------------------------------------------------------------------------------*/ - IList getCollection(CollectionType collection, Func contains, Func> getTopics) { - var targetAssociations = AssociationMap.Mappings[collection]; - var preconditionsMet = - listSource.Count == 0 && - (collectionType is CollectionType.Any || collectionType.Equals(collection)) && - (collectionType is CollectionType.Children || collection is not CollectionType.Children) && - (targetAssociations is AssociationTypes.None || associations.HasFlag(targetAssociations)) && - contains(configuration.CollectionKey); - return preconditionsMet? getTopics() : listSource; + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle Metadata relationship + \-------------------------------------------------------------------------------------------------------------------------*/ + if (listSource.Count == 0 && !String.IsNullOrWhiteSpace(configuration.MetadataKey)) { + var metadataKey = $"Root:Configuration:Metadata:{configuration.MetadataKey}:LookupList"; + var metadataParent = _topicRepository.Load(metadataKey, source); + if (metadataParent is not null) { + listSource = [.. metadataParent.Children]; } + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle flattening of children + \-------------------------------------------------------------------------------------------------------------------------*/ + if (configuration.FlattenChildren) { + var flattenedList = new List(); + listSource.ToList().ForEach(t => FlattenTopicGraph(t, flattenedList)); + listSource = flattenedList; } - /*========================================================================================================================== - | PRIVATE: POPULATE TARGET COLLECTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a source list, will populate a target list based on the configured behavior of the target property. - /// - /// The to pull the source objects from. - /// The target to add the mapped objects to. - /// The with details about the property's attributes. - /// A cache to keep track of already-mapped object instances. - private async Task PopulateTargetCollectionAsync( - IList sourceList, - IList targetList, - ItemMetadata itemMetadata, - MappedTopicCache cache - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = itemMetadata.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Determine the type of item in the list - \-----------------------------------------------------------------------------------------------------------------------*/ - var listType = typeof(ITopicViewModel); - foreach (var type in targetList.GetType().GetInterfaces()) { - if (type.IsGenericType && typeof(IList<>) == type.GetGenericTypeDefinition()) { - //Uses last argument in case it's a KeyedCollection; in that case, we want the TItem type - listType = type.GetGenericArguments().Last(); - } - } + return listSource; - /*------------------------------------------------------------------------------------------------------------------------ - | Queue up mapping tasks - \-----------------------------------------------------------------------------------------------------------------------*/ - var taskQueue = new List>(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Provide local function for evaluating current collection + \-------------------------------------------------------------------------------------------------------------------------*/ + IList getCollection(CollectionType collection, Func contains, Func> getTopics) { + var targetAssociations = AssociationMap.Mappings[collection]; + var preconditionsMet = + listSource.Count == 0 && + (collectionType is CollectionType.Any || collectionType.Equals(collection)) && + (collectionType is CollectionType.Children || collection is not CollectionType.Children) && + (targetAssociations is AssociationTypes.None || associations.HasFlag(targetAssociations)) && + contains(configuration.CollectionKey); + return preconditionsMet? getTopics() : listSource; + } - foreach (var childTopic in sourceList) { + } - //Ensure the source topic isn't disabled; disabled topics should never be returned to the presentation layer unless - //explicitly requested by a top-level request. - if (childTopic.IsDisabled) { - continue; - } + /*============================================================================================================================ + | PRIVATE: POPULATE TARGET COLLECTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a source list, will populate a target list based on the configured behavior of the target property. + /// + /// The to pull the source objects from. + /// The target to add the mapped objects to. + /// The with details about the property's attributes. + /// A cache to keep track of already-mapped object instances. + private async Task PopulateTargetCollectionAsync( + IList sourceList, + IList targetList, + ItemMetadata itemMetadata, + MappedTopicCache cache + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = itemMetadata.Configuration; - //Skip nested topics; those should be explicitly mapped to their own collection or topic reference - if (childTopic.ContentType.Equals("List", StringComparison.OrdinalIgnoreCase)) { - continue; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine the type of item in the list + \-------------------------------------------------------------------------------------------------------------------------*/ + var listType = typeof(ITopicViewModel); + foreach (var type in targetList.GetType().GetInterfaces()) { + if (type.IsGenericType && typeof(IList<>) == type.GetGenericTypeDefinition()) { + //Uses last argument in case it's a KeyedCollection; in that case, we want the TItem type + listType = type.GetGenericArguments().Last(); + } + } - //Ensure the source topic matches any [FilterByContentType()] settings - if ( - configuration.ContentTypeFilter is not null && - !childTopic.ContentType.Equals(configuration.ContentTypeFilter, StringComparison.OrdinalIgnoreCase) - ) { - continue; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Queue up mapping tasks + \-------------------------------------------------------------------------------------------------------------------------*/ + var taskQueue = new List>(); - //Ensure the source topic matches any [FilterByAttribute()] settings - if (!configuration.SatisfiesAttributeFilters(childTopic)) { - continue; - } + foreach (var childTopic in sourceList) { - //Map child topic to target DTO - var childDto = (object)childTopic; - if (!typeof(Topic).IsAssignableFrom(listType)) { - var mappingType = GetValidatedMappingType(configuration.MapAs, listType)?? GetValidatedMappingType(childTopic, listType); - if (mappingType is not null) { - taskQueue.Add(MapAsync(childTopic, mappingType, configuration.IncludeAssociations, cache)); - } - } - else { - addToList(childDto); - } + //Ensure the source topic isn't disabled; disabled topics should never be returned to the presentation layer unless + //explicitly requested by a top-level request. + if (childTopic.IsDisabled) { + continue; + } + //Skip nested topics; those should be explicitly mapped to their own collection or topic reference + if (childTopic.ContentType.Equals("List", StringComparison.OrdinalIgnoreCase)) { + continue; } - /*------------------------------------------------------------------------------------------------------------------------ - | Process mapping tasks - \-----------------------------------------------------------------------------------------------------------------------*/ - while (taskQueue.Count > 0) { - var dtoTask = await Task.WhenAny(taskQueue).ConfigureAwait(false); - var dto = await dtoTask.ConfigureAwait(false); - taskQueue.Remove(dtoTask); - if (dto is not null) { - addToList(dto); - } + //Ensure the source topic matches any [FilterByContentType()] settings + if ( + configuration.ContentTypeFilter is not null && + !childTopic.ContentType.Equals(configuration.ContentTypeFilter, StringComparison.OrdinalIgnoreCase) + ) { + continue; } - /*------------------------------------------------------------------------------------------------------------------------ - | Function: Add to List - \-----------------------------------------------------------------------------------------------------------------------*/ - void addToList(object dto) { - try { - targetList.Add(dto); - } - catch (ArgumentException) { - //Ignore exceptions caused by duplicate keys, in case the IList represents a keyed collection - //We would defensively check for this, except IList doesn't provide a suitable method to do so + //Ensure the source topic matches any [FilterByAttribute()] settings + if (!configuration.SatisfiesAttributeFilters(childTopic)) { + continue; + } + + //Map child topic to target DTO + var childDto = (object)childTopic; + if (!typeof(Topic).IsAssignableFrom(listType)) { + var mappingType = GetValidatedMappingType(configuration.MapAs, listType)?? GetValidatedMappingType(childTopic, listType); + if (mappingType is not null) { + taskQueue.Add(MapAsync(childTopic, mappingType, configuration.IncludeAssociations, cache)); } } + else { + addToList(childDto); + } } - /*========================================================================================================================== - | PRIVATE: GET VALIDATED MODEL TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , identifies the target model type associated with it and - /// validates it against the . - /// - /// The source that the target type should be inferred from. - /// The expected that the inferred type must be compatible with. - /// The inferred target type, if valid, otherwise null. - private Type? GetValidatedMappingType(Topic sourceTopic, Type expectedType) => - GetValidatedMappingType( - _typeLookupService.Lookup($"{sourceTopic.ContentType}TopicViewModel", $"{sourceTopic.ContentType}ViewModel"), - expectedType - ); + /*-------------------------------------------------------------------------------------------------------------------------- + | Process mapping tasks + \-------------------------------------------------------------------------------------------------------------------------*/ + while (taskQueue.Count > 0) { + var dtoTask = await Task.WhenAny(taskQueue).ConfigureAwait(false); + var dto = await dtoTask.ConfigureAwait(false); + taskQueue.Remove(dtoTask); + if (dto is not null) { + addToList(dto); + } + } - /// - /// Given a , validates it against the . - /// If it is compatible, returns the . Otherwise, returns null. - /// - /// The source that should be validated. - /// - /// The expected that the must be compatible with. - /// - /// The , if valid, otherwise null. - private static Type? GetValidatedMappingType(Type? mappingType, Type expectedType) => - expectedType.IsAssignableFrom(mappingType)? mappingType : null; - - /*========================================================================================================================== - | PRIVATE: GET TOPIC REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to retrieve a topic reference form the . - /// - /// The source from which to pull the value. - /// The expected for the mapped . - /// The with details about the item's attributes. - /// A cache to keep track of already-mapped object instances. - private async Task GetTopicReferenceAsync( - Topic source, - Type targetType, - ItemMetadata itemMetadata, - MappedTopicCache cache - ) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = itemMetadata.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Bypass disabled topics - \-----------------------------------------------------------------------------------------------------------------------*/ - //Ensure the source topic isn't disabled; disabled topics should never be returned to the presentation layer unless - //explicitly requested by a top-level request. - if (source.IsDisabled) { - return null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Function: Add to List + \-------------------------------------------------------------------------------------------------------------------------*/ + void addToList(object dto) { + try { + targetList.Add(dto); } + catch (ArgumentException) { + //Ignore exceptions caused by duplicate keys, in case the IList represents a keyed collection + //We would defensively check for this, except IList doesn't provide a suitable method to do so + } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Map referenced topic - \-----------------------------------------------------------------------------------------------------------------------*/ - var topicDto = (object?)null; - var mappingType = GetValidatedMappingType(configuration.MapAs, targetType)?? GetValidatedMappingType(source, targetType); + } - if (mappingType is not null) { - topicDto = await MapAsync(source, mappingType, configuration.IncludeAssociations, cache).ConfigureAwait(false); - } + /*============================================================================================================================ + | PRIVATE: GET VALIDATED MODEL TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , identifies the target model type associated with it and + /// validates it against the . + /// + /// The source that the target type should be inferred from. + /// The expected that the inferred type must be compatible with. + /// The inferred target type, if valid, otherwise null. + private Type? GetValidatedMappingType(Topic sourceTopic, Type expectedType) => + GetValidatedMappingType( + _typeLookupService.Lookup($"{sourceTopic.ContentType}TopicViewModel", $"{sourceTopic.ContentType}ViewModel"), + expectedType + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Return type - \-----------------------------------------------------------------------------------------------------------------------*/ - return topicDto; + /// + /// Given a , validates it against the . + /// If it is compatible, returns the . Otherwise, returns null. + /// + /// The source that should be validated. + /// + /// The expected that the must be compatible with. + /// + /// The , if valid, otherwise null. + private static Type? GetValidatedMappingType(Type? mappingType, Type expectedType) => + expectedType.IsAssignableFrom(mappingType)? mappingType : null; + + /*============================================================================================================================ + | PRIVATE: GET TOPIC REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to retrieve a topic reference form the . + /// + /// The source from which to pull the value. + /// The expected for the mapped . + /// The with details about the item's attributes. + /// A cache to keep track of already-mapped object instances. + private async Task GetTopicReferenceAsync( + Topic source, + Type targetType, + ItemMetadata itemMetadata, + MappedTopicCache cache + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = itemMetadata.Configuration; + /*-------------------------------------------------------------------------------------------------------------------------- + | Bypass disabled topics + \-------------------------------------------------------------------------------------------------------------------------*/ + //Ensure the source topic isn't disabled; disabled topics should never be returned to the presentation layer unless + //explicitly requested by a top-level request. + if (source.IsDisabled) { + return null; } - /*========================================================================================================================== - | PRIVATE: FLATTEN TOPIC GRAPH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper function recursively iterates through children and adds each to a collection. - /// - /// The entity pull the data from. - /// The list of instances to add each child to. - private IList FlattenTopicGraph(Topic source, IList targetList) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate source properties - \-----------------------------------------------------------------------------------------------------------------------*/ - if (source.IsDisabled) return targetList; - if (source.ContentType is "List") return targetList; - - /*------------------------------------------------------------------------------------------------------------------------ - | Merge source list into target list - \-----------------------------------------------------------------------------------------------------------------------*/ - targetList.Add(source); - source.Children.ToList().ForEach(t => FlattenTopicGraph(t, targetList)); - return targetList; + /*-------------------------------------------------------------------------------------------------------------------------- + | Map referenced topic + \-------------------------------------------------------------------------------------------------------------------------*/ + var topicDto = (object?)null; + var mappingType = GetValidatedMappingType(configuration.MapAs, targetType)?? GetValidatedMappingType(source, targetType); + if (mappingType is not null) { + topicDto = await MapAsync(source, mappingType, configuration.IncludeAssociations, cache).ConfigureAwait(false); } - /*========================================================================================================================== - | PRIVATE: TRY GET COMPATIBLE PROPERTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a property on the that is compatible to the . - /// - /// - /// Even if the property values can't be set by the , properties should be settable assuming the - /// source and target types are compatible. In this case, needn't know anything about - /// the property type as it doesn't need to do a conversion; it can just do a one-to-one mapping. - /// - /// The source from which to pull the value. - /// The target . - /// The with details about the item's attributes. - /// The prefix to apply to the attributes. - /// The compatible property, if it is available. - private static bool TryGetCompatibleProperty(Topic source, Type targetType, ItemMetadata itemMetadata, string? attributePrefix, out object? value) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Establish configuration - \-----------------------------------------------------------------------------------------------------------------------*/ - var configuration = itemMetadata.Configuration; - - /*------------------------------------------------------------------------------------------------------------------------ - | Rely on MaybeCompatible to bypass known incompatible types - \-----------------------------------------------------------------------------------------------------------------------*/ - if (source.GetType() == typeof(Topic) && !itemMetadata.MaybeCompatible) { - value = null; - return false; - }; - - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to retrieve value from topic.{Property} - \-----------------------------------------------------------------------------------------------------------------------*/ - var sourcePropertyAccessor = GetTopicAccessor(source.GetType()).GetMember(configuration.GetCompositeAttributeKey(attributePrefix)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Escape clause if preconditions are not met - \-----------------------------------------------------------------------------------------------------------------------*/ - if (sourcePropertyAccessor is null || !targetType.IsAssignableFrom(sourcePropertyAccessor.Type)) { - value = null; - return false; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return type + \-------------------------------------------------------------------------------------------------------------------------*/ + return topicDto; + + } + + /*============================================================================================================================ + | PRIVATE: FLATTEN TOPIC GRAPH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper function recursively iterates through children and adds each to a collection. + /// + /// The entity pull the data from. + /// The list of instances to add each child to. + private static IList FlattenTopicGraph(Topic source, IList targetList) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate source properties + \-------------------------------------------------------------------------------------------------------------------------*/ + if (source.IsDisabled) return targetList; + if (source.ContentType is "List") return targetList; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Merge source list into target list + \-------------------------------------------------------------------------------------------------------------------------*/ + targetList.Add(source); + source.Children.ToList().ForEach(t => FlattenTopicGraph(t, targetList)); + return targetList; + + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return value - \-----------------------------------------------------------------------------------------------------------------------*/ - value = sourcePropertyAccessor.GetValue(source); + /*============================================================================================================================ + | PRIVATE: TRY GET COMPATIBLE PROPERTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a property on the that is compatible to the . + /// + /// + /// Even if the property values can't be set by the , properties should be settable assuming the + /// source and target types are compatible. In this case, needn't know anything about + /// the property type as it doesn't need to do a conversion; it can just do a one-to-one mapping. + /// + /// The source from which to pull the value. + /// The target . + /// The with details about the item's attributes. + /// The prefix to apply to the attributes. + /// The compatible property, if it is available. + private static bool TryGetCompatibleProperty(Topic source, Type targetType, ItemMetadata itemMetadata, string? attributePrefix, out object? value) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish configuration + \-------------------------------------------------------------------------------------------------------------------------*/ + var configuration = itemMetadata.Configuration; + + /*-------------------------------------------------------------------------------------------------------------------------- + | Rely on MaybeCompatible to bypass known incompatible types + \-------------------------------------------------------------------------------------------------------------------------*/ + if (source.GetType() == typeof(Topic) && !itemMetadata.MaybeCompatible) { + value = null; + return false; + }; - return true; + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to retrieve value from topic.{Property} + \-------------------------------------------------------------------------------------------------------------------------*/ + var sourcePropertyAccessor = GetTopicAccessor(source.GetType()).GetMember(configuration.GetCompositeAttributeKey(attributePrefix)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Escape clause if preconditions are not met + \-------------------------------------------------------------------------------------------------------------------------*/ + if (sourcePropertyAccessor is null || !targetType.IsAssignableFrom(sourcePropertyAccessor.Type)) { + value = null; + return false; } - /*========================================================================================================================== - | PRIVATE: GET TOPIC ACCESSOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a specific for a , returns the appropriate from - /// the . - /// - /// The of the source . - private static TypeAccessor GetTopicAccessor(Type topicType) => - topicType == typeof(Topic) ? _topicTypeAccessor : TypeAccessorCache.GetTypeAccessor(topicType); + value = sourcePropertyAccessor.GetValue(source); + + return true; + + } + + /*============================================================================================================================ + | PRIVATE: GET TOPIC ACCESSOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a specific for a , returns the appropriate from + /// the . + /// + /// The of the source . + private static TypeAccessor GetTopicAccessor(Type topicType) => + topicType == typeof(Topic) ? _topicTypeAccessor : TypeAccessorCache.GetTypeAccessor(topicType); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/_exceptions/InvalidTypeException.cs b/OnTopic/Mapping/_exceptions/InvalidTypeException.cs index 650abc76..3bfaf613 100644 --- a/OnTopic/Mapping/_exceptions/InvalidTypeException.cs +++ b/OnTopic/Mapping/_exceptions/InvalidTypeException.cs @@ -3,57 +3,44 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ -using System.Runtime.Serialization; using OnTopic.Lookup; -namespace OnTopic.Mapping { +namespace OnTopic.Mapping; + +/*============================================================================================================================== +| CLASS: INVALID TYPE EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The is thrown when an implementation requests a +/// target type that cannot be located using the supplied . +/// +/// +/// Having one (base) class used for all expected exceptions from the and other mapping +/// service interfaces allows implementors to capture all exceptions—while, potentially, catching more specific exceptions +/// based on derived classes, if we discover the need for more specific exceptions. +/// +[ExcludeFromCodeCoverage] +public class InvalidTypeException: TopicMappingException { /*============================================================================================================================ - | CLASS: INVALID TYPE EXCEPTION + | CONSTRUCTOR: INVALID TYPE EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The is thrown when an implementation requests a - /// target type that cannot be located using the supplied . + /// Initializes a new instance. /// - /// - /// Having one (base) class used for all expected exceptions from the and other mapping - /// service interfaces allows implementors to capture all exceptions—while, potentially, catching more specific exceptions - /// based on derived classes, if we discover the need for more specific exceptions. - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class InvalidTypeException: TopicMappingException { - - /*========================================================================================================================== - | CONSTRUCTOR: INVALID TYPE EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance. - /// - public InvalidTypeException() : base() { } + public InvalidTypeException() : base() { } - /// - /// Initializes a new instance with a specific error message. - /// - /// The message to display for this exception. - public InvalidTypeException(string message) : base(message) { } - - /// - /// Initializes a new instance with a specific error message and nested exception. - /// - /// The message to display for this exception. - /// The reference to the original, underlying exception. - public InvalidTypeException(string message, Exception innerException) : base(message, innerException) { } + /// + /// Initializes a new instance with a specific error message. + /// + /// The message to display for this exception. + public InvalidTypeException(string message) : base(message) { } - /// - /// Instantiates a new instance for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected InvalidTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Initializes a new instance with a specific error message and nested exception. + /// + /// The message to display for this exception. + /// The reference to the original, underlying exception. + public InvalidTypeException(string message, Exception innerException) : base(message, innerException) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/_exceptions/MappingModelValidationException.cs b/OnTopic/Mapping/_exceptions/MappingModelValidationException.cs index 09abd0fe..aff6c2ce 100644 --- a/OnTopic/Mapping/_exceptions/MappingModelValidationException.cs +++ b/OnTopic/Mapping/_exceptions/MappingModelValidationException.cs @@ -3,61 +3,48 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ -using System.Runtime.Serialization; using OnTopic.Mapping.Reverse; using OnTopic.Metadata; -namespace OnTopic.Mapping { +namespace OnTopic.Mapping; + +/*============================================================================================================================== +| CLASS: MAPPING MODEL VALIDATION EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The is thrown when an +/// implementation is provided a model that cannot be reliably mapped back to the target , thus +/// introducing potential data integrity issues. +/// +/// +/// The read-only mapping services, such as , are generally designed to be forgiving of +/// mismatches. By contrast, because the is intended to update the persistence +/// store, it is generally designed to fail if there are any discrepancies between the source model and the target . Given this, the is expected to be thrown for +/// validation errors caused by e.g. the . +/// +[ExcludeFromCodeCoverage] +public class MappingModelValidationException: TopicMappingException { /*============================================================================================================================ - | CLASS: MAPPING MODEL VALIDATION EXCEPTION + | CONSTRUCTOR: MAPPING MODEL VALIDATION EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The is thrown when an - /// implementation is provided a model that cannot be reliably mapped back to the target , thus - /// introducing potential data integrity issues. + /// Initializes a new instance. /// - /// - /// The read-only mapping services, such as , are generally designed to be forgiving of - /// mismatches. By contrast, because the is intended to update the persistence - /// store, it is generally designed to fail if there are any discrepancies between the source model and the target . Given this, the is expected to be thrown for - /// validation errors caused by e.g. the . - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class MappingModelValidationException: TopicMappingException { - - /*========================================================================================================================== - | CONSTRUCTOR: MAPPING MODEL VALIDATION EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance. - /// - public MappingModelValidationException() : base() { } + public MappingModelValidationException() : base() { } - /// - /// Initializes a new instance with a specific error message. - /// - /// The message to display for this exception. - public MappingModelValidationException(string message) : base(message) { } - - /// - /// Initializes a new instance with a specific error message and nested exception. - /// - /// The message to display for this exception. - /// The reference to the original, underlying exception. - public MappingModelValidationException(string message, Exception innerException) : base(message, innerException) { } + /// + /// Initializes a new instance with a specific error message. + /// + /// The message to display for this exception. + public MappingModelValidationException(string message) : base(message) { } - /// - /// Instantiates a new instance for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected MappingModelValidationException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Initializes a new instance with a specific error message and nested exception. + /// + /// The message to display for this exception. + /// The reference to the original, underlying exception. + public MappingModelValidationException(string message, Exception innerException) : base(message, innerException) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Mapping/_exceptions/TopicMappingException.cs b/OnTopic/Mapping/_exceptions/TopicMappingException.cs index 9e872bac..450d16fd 100644 --- a/OnTopic/Mapping/_exceptions/TopicMappingException.cs +++ b/OnTopic/Mapping/_exceptions/TopicMappingException.cs @@ -3,56 +3,42 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ -using System.Runtime.Serialization; +namespace OnTopic.Mapping; -namespace OnTopic.Mapping { +/*============================================================================================================================== +| CLASS: TOPIC MAPPING EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The provides a general exception that can be thrown for any errors that arise from +/// concrete implementations of as well as other mapping service interfaces. +/// +/// +/// Having one (base) class used for all expected exceptions from the and other mapping +/// service interfaces allows implementors to capture all exceptions—while, potentially, catching more specific exceptions +/// based on derived classes, if we discover the need for more specific exceptions. +/// +[ExcludeFromCodeCoverage] +public class TopicMappingException : Exception { /*============================================================================================================================ - | CLASS: TOPIC MAPPING EXCEPTION + | CONSTRUCTOR: TOPIC MAPPING EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The provides a general exception that can be thrown for any errors that arise from - /// concrete implementations of as well as other mapping service interfaces. + /// Initializes a new instance. /// - /// - /// Having one (base) class used for all expected exceptions from the and other mapping - /// service interfaces allows implementors to capture all exceptions—while, potentially, catching more specific exceptions - /// based on derived classes, if we discover the need for more specific exceptions. - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class TopicMappingException : Exception { + public TopicMappingException() : base() { } - /*========================================================================================================================== - | CONSTRUCTOR: TOPIC MAPPING EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance. - /// - public TopicMappingException() : base() { } - - /// - /// Initializes a new instance with a specific error message. - /// - /// The message to display for this exception. - public TopicMappingException(string message) : base(message) { } - - /// - /// Initializes a new instance with a specific error message and nested exception. - /// - /// The message to display for this exception. - /// The reference to the original, underlying exception. - public TopicMappingException(string message, Exception innerException) : base(message, innerException) { } + /// + /// Initializes a new instance with a specific error message. + /// + /// The message to display for this exception. + public TopicMappingException(string message) : base(message) { } - /// - /// Instantiates a new instance for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected TopicMappingException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Initializes a new instance with a specific error message and nested exception. + /// + /// The message to display for this exception. + /// The reference to the original, underlying exception. + public TopicMappingException(string message, Exception innerException) : base(message, innerException) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Metadata/AttributeDescriptor.cs b/OnTopic/Metadata/AttributeDescriptor.cs index 2d099174..f9a71b5e 100644 --- a/OnTopic/Metadata/AttributeDescriptor.cs +++ b/OnTopic/Metadata/AttributeDescriptor.cs @@ -5,198 +5,197 @@ \=============================================================================================================================*/ using OnTopic.Collections.Specialized; -namespace OnTopic.Metadata { +namespace OnTopic.Metadata; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE DESCRIPTOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents metadata for describing an attribute, including information on how it will be presented and validated in the +/// editor. +/// +/// +/// +/// Every in the Topic Library is associated with a , which +/// determines the expected schema of the topic. That schema is described through the +/// collection, which provides a list of +/// s associated with that content type. For instance, the commonly-configured "Page" +/// Content Type has attributes such as "Keywords", "Body", etc. Each of those are individually represented by instances +/// of the class. +/// +/// +/// The purpose of the class is only to describe the schema of an attribute. For each +/// individual , the actual values of attributes are stored in objects via +/// the property. By contrast to , the +/// class is focused exclusively on representing the attribute's value; it is not aware of +/// whether that attribute is required, what data type it represents, or how it should be displayed in the editor. +/// +/// +/// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of +/// the CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. +/// +/// +public class AttributeDescriptor : Topic { /*============================================================================================================================ - | CLASS: ATTRIBUTE DESCRIPTOR + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents metadata for describing an attribute, including information on how it will be presented and validated in the - /// editor. + /// Initializes a new instance of a class with a , , and, optionally, , . /// /// - /// - /// Every in the Topic Library is associated with a , which - /// determines the expected schema of the topic. That schema is described through the - /// collection, which provides a list of - /// s associated with that content type. For instance, the commonly-configured "Page" - /// Content Type has attributes such as "Keywords", "Body", etc. Each of those are individually represented by instances - /// of the class. - /// - /// - /// The purpose of the class is only to describe the schema of an attribute. For each - /// individual , the actual values of attributes are stored in objects via - /// the property. By contrast to , the - /// class is focused exclusively on representing the attribute's value; it is not aware of - /// whether that attribute is required, what data type it represents, or how it should be displayed in the editor. - /// - /// - /// This class is primarily used by the Topic Editor interface to determine how attributes are displayed as part of - /// the CMS; except in very specific scenarios, it is not typically used elsewhere in the Topic Library itself. - /// + /// By default, when creating new attributes, the s for both and will be set to , which is required in order to + /// correctly save new topics to the database. When the parameter is set, however, the property is set to false on as well as on , since it is assumed these are being set to the same values currently used in the + /// persistence store. /// - public class AttributeDescriptor : Topic { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a class with a , , and, optionally, , . - /// - /// - /// By default, when creating new attributes, the s for both and will be set to , which is required in order to - /// correctly save new topics to the database. When the parameter is set, however, the property is set to false on as well as on , since it is assumed these are being set to the same values currently used in the - /// persistence store. - /// - /// A string representing the key for the new topic instance. - /// A string representing the key of the target content type. - /// Optional topic to set as the new topic's parent. - /// The unique identifier assigned by the data store for an existing topic. - /// - /// Thrown when the class representing the content type is found, but doesn't derive from . - /// - /// A strongly-typed instance of the class based on the target content type. - public AttributeDescriptor( - string key, - string contentType, - Topic? parent = null, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { + /// A string representing the key for the new topic instance. + /// A string representing the key of the target content type. + /// Optional topic to set as the new topic's parent. + /// The unique identifier assigned by the data store for an existing topic. + /// + /// Thrown when the class representing the content type is found, but doesn't derive from . + /// + /// A strongly-typed instance of the class based on the target content type. + public AttributeDescriptor( + string key, + string contentType, + Topic? parent = null, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { - } + } - /*========================================================================================================================== - | PROPERTY: MODEL TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets an value suggesting how this attribute is modeled in the object graph. - /// - /// - /// Often, there are several editor controls (represented by ) which correspond to a single model - /// structure in the Topic Library. For instance, both Relationships and TokenizedTopicList are ways of - /// exposing the same underlying relationship to the editor in different forms. The property - /// reduces these down into a single type based on how they're exposed in the Topic Library, not based on how they're - /// exposed in the editor. - /// - [ExcludeFromCodeCoverage] - public virtual ModelType ModelType { get; protected init; } = ModelType.ScalarValue; + /*============================================================================================================================ + | PROPERTY: MODEL TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets an value suggesting how this attribute is modeled in the object graph. + /// + /// + /// Often, there are several editor controls (represented by ) which correspond to a single model + /// structure in the Topic Library. For instance, both Relationships and TokenizedTopicList are ways of + /// exposing the same underlying relationship to the editor in different forms. The property + /// reduces these down into a single type based on how they're exposed in the Topic Library, not based on how they're + /// exposed in the editor. + /// + [ExcludeFromCodeCoverage] + public virtual ModelType ModelType { get; protected init; } = ModelType.ScalarValue; - /*========================================================================================================================== - | PROPERTY: EDITOR TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the filename reference to the Attribute Type control associate with the Topic object. - /// - /// - /// The type attribute maps to the name of a control or view component in the editor representing the specific type of - /// attribute. For instance, a value of "Boolean" might map to a BooleanViewComponent which displays an attribute's - /// value as a standard HTML checkbox. There is no validation of the type at the library level; it is up to the editor to - /// provide a match and, if not found, display an error. - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") && !value.Contains("/") - /// - [ExcludeFromCodeCoverage] - public string EditorType => GetType().Name.Replace("AttributeDescriptor", "", StringComparison.OrdinalIgnoreCase); + /*============================================================================================================================ + | PROPERTY: EDITOR TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the filename reference to the Attribute Type control associate with the Topic object. + /// + /// + /// The type attribute maps to the name of a control or view component in the editor representing the specific type of + /// attribute. For instance, a value of "Boolean" might map to a BooleanViewComponent which displays an attribute's + /// value as a standard HTML checkbox. There is no validation of the type at the library level; it is up to the editor to + /// provide a match and, if not found, display an error. + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") && !value.Contains("/") + /// + [ExcludeFromCodeCoverage] + public string EditorType => GetType().Name.Replace("AttributeDescriptor", "", StringComparison.OrdinalIgnoreCase); - /*========================================================================================================================== - | PROPERTY: DISPLAY GROUP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the tab in the editor within which the Attribute should be displayed. - /// - /// - /// When attributes are displayed in the editor, they are grouped by tabs. The tabs are not predetermined, but rather set - /// by individual attributes. If five attributes, for instance, have a display group of "Settings", then a tab will be - /// rendered called "Settings" and will list those five attributes (assuming none are set to ). - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - [ExcludeFromCodeCoverage] - public string? DisplayGroup { - get => Attributes.GetValue("DisplayGroup", ""); - set { - Contract.Requires(!String.IsNullOrWhiteSpace(value), nameof(value)); - SetAttributeValue("DisplayGroup", value); - } + /*============================================================================================================================ + | PROPERTY: DISPLAY GROUP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the tab in the editor within which the Attribute should be displayed. + /// + /// + /// When attributes are displayed in the editor, they are grouped by tabs. The tabs are not predetermined, but rather set + /// by individual attributes. If five attributes, for instance, have a display group of "Settings", then a tab will be + /// rendered called "Settings" and will list those five attributes (assuming none are set to ). + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + [ExcludeFromCodeCoverage] + public string? DisplayGroup { + get => Attributes.GetValue("DisplayGroup", ""); + set { + Contract.Requires(!String.IsNullOrWhiteSpace(value), nameof(value)); + SetAttributeValue("DisplayGroup", value); } + } - /*========================================================================================================================== - | PROPERTY: IS REQUIRED? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether or not the attribute is required. - /// - /// - /// This is used to establish a required field validator in the editor interface. This should be used by the form - /// validation in the editor to ensure the field contains a value. - /// - [ExcludeFromCodeCoverage] - public bool IsRequired { - get => Attributes.GetBoolean("IsRequired"); - set => SetAttributeValue("IsRequired", value ? "1" : "0"); - } + /*============================================================================================================================ + | PROPERTY: IS REQUIRED? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether or not the attribute is required. + /// + /// + /// This is used to establish a required field validator in the editor interface. This should be used by the form + /// validation in the editor to ensure the field contains a value. + /// + [ExcludeFromCodeCoverage] + public bool IsRequired { + get => Attributes.GetBoolean("IsRequired"); + set => SetAttributeValue("IsRequired", value ? "1" : "0"); + } - /*========================================================================================================================== - | PROPERTY: DEFAULT VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the default value that should be used if an explicit value is not defined. - /// - /// - /// The default value is only used if the value is not otherwise defined. Once a topic has been saved in the editor, this - /// value (if not overwritten) is committed to the database and, thus, that version is used in the future. As such, the - /// default value only affects the topic when it is first being created via the editor. - /// - [ExcludeFromCodeCoverage] - public string? DefaultValue { - get => Attributes.GetValue("DefaultValue", null); - set => SetAttributeValue("DefaultValue", value); - } + /*============================================================================================================================ + | PROPERTY: DEFAULT VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the default value that should be used if an explicit value is not defined. + /// + /// + /// The default value is only used if the value is not otherwise defined. Once a topic has been saved in the editor, this + /// value (if not overwritten) is committed to the database and, thus, that version is used in the future. As such, the + /// default value only affects the topic when it is first being created via the editor. + /// + [ExcludeFromCodeCoverage] + public string? DefaultValue { + get => Attributes.GetValue("DefaultValue", null); + set => SetAttributeValue("DefaultValue", value); + } - /*========================================================================================================================== - | PROPERTY: IS EXTENDED ATTRIBUTE? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether or not the attribute is stored as part of the attributes XML. - /// - /// - /// - /// Optionally, attributes may be stored as extended attributes, which means they may not be loaded initially, and not - /// initially accessible to in-memory queries. On the backend, these may be stored independently, such as in an XML, - /// which may be more efficient to store. This is required for larger values, as indexed attributes are limited to 255 - /// characters. - /// - /// - /// Attributes that are needed to provide indexes, sitemaps, navigation, etc. should be indexed so that they're always - /// available in memory without requiring an additional database query. These increase the memory requirements of the - /// application, but reduce the number of database round-trips required for topics that are accessed outside of a single - /// page. For instance, the title and description of a topic may be cross-referenced on other pages or as part of the - /// navigation, and should thus be indexed. Indexed attributes are those not stored as extended attributes. - /// - /// - /// This property and its corresponding attribute was named StoreInBlob in versions of OnTopic prior to 4.0. - /// - /// - [ExcludeFromCodeCoverage] - public bool IsExtendedAttribute { - get => Attributes.GetBoolean("IsExtendedAttribute", Attributes.GetBoolean("StoreInBlob")); - set => SetAttributeValue("IsExtendedAttribute", value ? "1" : "0"); - } + /*============================================================================================================================ + | PROPERTY: IS EXTENDED ATTRIBUTE? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether or not the attribute is stored as part of the attributes XML. + /// + /// + /// + /// Optionally, attributes may be stored as extended attributes, which means they may not be loaded initially, and not + /// initially accessible to in-memory queries. On the backend, these may be stored independently, such as in an XML, + /// which may be more efficient to store. This is required for larger values, as indexed attributes are limited to 255 + /// characters. + /// + /// + /// Attributes that are needed to provide indexes, sitemaps, navigation, etc. should be indexed so that they're always + /// available in memory without requiring an additional database query. These increase the memory requirements of the + /// application, but reduce the number of database round-trips required for topics that are accessed outside of a single + /// page. For instance, the title and description of a topic may be cross-referenced on other pages or as part of the + /// navigation, and should thus be indexed. Indexed attributes are those not stored as extended attributes. + /// + /// + /// This property and its corresponding attribute was named StoreInBlob in versions of OnTopic prior to 4.0. + /// + /// + [ExcludeFromCodeCoverage] + public bool IsExtendedAttribute { + get => Attributes.GetBoolean("IsExtendedAttribute", Attributes.GetBoolean("StoreInBlob")); + set => SetAttributeValue("IsExtendedAttribute", value ? "1" : "0"); + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Metadata/AttributeDescriptorCollection.cs b/OnTopic/Metadata/AttributeDescriptorCollection.cs index d213cb23..a9f2726b 100644 --- a/OnTopic/Metadata/AttributeDescriptorCollection.cs +++ b/OnTopic/Metadata/AttributeDescriptorCollection.cs @@ -5,24 +5,23 @@ \=============================================================================================================================*/ using OnTopic.Collections; -namespace OnTopic.Metadata { +namespace OnTopic.Metadata; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE DESCRIPTOR COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +public class AttributeDescriptorCollection : KeyedTopicCollection { /*============================================================================================================================ - | CLASS: ATTRIBUTE DESCRIPTOR COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Initializes a new instance of the class. /// - public class AttributeDescriptorCollection : KeyedTopicCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - public AttributeDescriptorCollection() : base(null) { - } + public AttributeDescriptorCollection() : base(null) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Metadata/ContentTypeDescriptor.cs b/OnTopic/Metadata/ContentTypeDescriptor.cs index ba46c575..96ee4b1e 100644 --- a/OnTopic/Metadata/ContentTypeDescriptor.cs +++ b/OnTopic/Metadata/ContentTypeDescriptor.cs @@ -7,275 +7,274 @@ using OnTopic.Collections.Specialized; using OnTopic.Associations; -namespace OnTopic.Metadata { +namespace OnTopic.Metadata; + +/*============================================================================================================================== +| CLASS: CONTENT TYPE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Content types provide schema information for each topic, including which attributes that topic is expected to include. +/// +/// +/// +/// Each topic is associated with a content type. The content type determines which attributes are displayed in the Topics +/// Editor (via the property). +/// +/// +/// Each content type associated with a is itself a with a Content Type of +/// "Content Type". The attributes of the "Content Type" Content Type represent the metadata associated with every content +/// type. For example, the "Content Type" Content Type has attributes such as which +/// represents which attributes should be associated with each instance of a . To +/// represent this, the class provides a strongly-typed derivation of the class, with properties mapping to attributes specific to the "Content Type" Content Type. +/// +/// +// ### TODO JJC082515: Should add a Get() to simply checks against the collection (e.g., via Contains() then indexer[]). +public class ContentTypeDescriptor : Topic { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private AttributeDescriptorCollection? _attributeDescriptors; + private ReadOnlyKeyedTopicCollection? _permittedContentTypes; + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of a class with a , , and, optionally, , . + /// + /// + /// By default, when creating new attributes, the s for both and will be set to , which is required in order to + /// correctly save new topics to the database. When the parameter is set, however, the property is set to false on as well as on , since it is assumed these are being set to the same values currently used in the + /// persistence store. + /// + /// A string representing the key for the new topic instance. + /// A string representing the key of the target content type. + /// The unique identifier assigned by the data store for an existing topic. + /// Optional topic to set as the new topic's parent. + /// + /// Thrown when the class representing the content type is found, but doesn't derive from . + /// + /// A strongly-typed instance of the class based on the target content type. + public ContentTypeDescriptor( + string key, + string contentType, + Topic? parent = null, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { + } /*============================================================================================================================ - | CLASS: CONTENT TYPE + | PROPERTY: DISABLE CHILD TOPICS \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Content types provide schema information for each topic, including which attributes that topic is expected to include. + /// Determines whether instances of this are permitted to contain child topics. /// /// /// - /// Each topic is associated with a content type. The content type determines which attributes are displayed in the Topics - /// Editor (via the property). + /// By default, topics are hierarchical: any topic can contain any number of child topics. While this flexibility makes + /// sense for both the library and the underlying data stores, however, it doesn't always make sense for individual + /// topics. For example, while it may make sense for a "Page" topic to have child "Page" topics, it likely won't make + /// sense for an "Article" topic to. This property allows this functionality to be disabled. /// /// - /// Each content type associated with a is itself a with a Content Type of - /// "Content Type". The attributes of the "Content Type" Content Type represent the metadata associated with every content - /// type. For example, the "Content Type" Content Type has attributes such as which - /// represents which attributes should be associated with each instance of a . To - /// represent this, the class provides a strongly-typed derivation of the class, with properties mapping to attributes specific to the "Content Type" Content Type. + /// It is important to note that this functionality only affects the Topic Editor interface, by disabling the option to + /// add a child topic. This functionality is not enforced by the library itself. As such, developers may + /// programmatically add child topics to a topic regardless of whether it's associated is set to . /// /// - // ### TODO JJC082515: Should add a Get() to simply checks against the collection (e.g., via Contains() then indexer[]). - public class ContentTypeDescriptor : Topic { + [ExcludeFromCodeCoverage] + public bool DisableChildTopics { + get => Attributes.GetBoolean("DisableChildTopics"); + set => SetAttributeValue("DisableChildTopics", value ? "1" : "0"); + } - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private AttributeDescriptorCollection? _attributeDescriptors; - private ReadOnlyKeyedTopicCollection? _permittedContentTypes; + /*============================================================================================================================ + | PROPERTY: PERMITTED CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a read-only collection of what types of content types are permitted to be created as children of instances of + /// this content type. + /// + /// + /// + /// By default, topics are hierarchical: any topic can contain any number of child topics. While this flexibility makes + /// sense for both the library and the underlying data stores, however, it doesn't always make sense for individual + /// topics. For example, while it may make sense for a "Page" topic to have child "Comment" topics, it wouldn't make + /// sense for "Comment" topics to have child "Page" topics. This property allows the topics library to configure which + /// types of topics can be created under instances of the current content type. + /// + /// + /// It is important to note that this functionality only affects the Topic Editor interface by restricting the content + /// type of topics created under instances of this content type. This functionality is not enforced by the library + /// itself. As such, developers may programmatically add child topics to a topic regardless of whether it's associated + /// permits topics of that Content Type to be created. + /// + /// + /// To add content types to the collection, use . + /// + /// + public ReadOnlyKeyedTopicCollection PermittedContentTypes { + get { - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a class with a , , and, optionally, , . - /// - /// - /// By default, when creating new attributes, the s for both and will be set to , which is required in order to - /// correctly save new topics to the database. When the parameter is set, however, the property is set to false on as well as on , since it is assumed these are being set to the same values currently used in the - /// persistence store. - /// - /// A string representing the key for the new topic instance. - /// A string representing the key of the target content type. - /// The unique identifier assigned by the data store for an existing topic. - /// Optional topic to set as the new topic's parent. - /// - /// Thrown when the class representing the content type is found, but doesn't derive from . - /// - /// A strongly-typed instance of the class based on the target content type. - public ContentTypeDescriptor( - string key, - string contentType, - Topic? parent = null, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - } + /*------------------------------------------------------------------------------------------------------------------------ + | Populate values from relationships + \-----------------------------------------------------------------------------------------------------------------------*/ + if (_permittedContentTypes is null) { + var permittedContentTypes = new KeyedTopicCollection(); + var contentTypes = Relationships.GetValues("ContentTypes"); + foreach (var contentType in contentTypes.Cast()) { + permittedContentTypes.Add(contentType); + } + _permittedContentTypes = new(permittedContentTypes); + } + + /*------------------------------------------------------------------------------------------------------------------------ + | Return values + \-----------------------------------------------------------------------------------------------------------------------*/ + return _permittedContentTypes; - /*========================================================================================================================== - | PROPERTY: DISABLE CHILD TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether instances of this are permitted to contain child topics. - /// - /// - /// - /// By default, topics are hierarchical: any topic can contain any number of child topics. While this flexibility makes - /// sense for both the library and the underlying data stores, however, it doesn't always make sense for individual - /// topics. For example, while it may make sense for a "Page" topic to have child "Page" topics, it likely won't make - /// sense for an "Article" topic to. This property allows this functionality to be disabled. - /// - /// - /// It is important to note that this functionality only affects the Topic Editor interface, by disabling the option to - /// add a child topic. This functionality is not enforced by the library itself. As such, developers may - /// programmatically add child topics to a topic regardless of whether it's associated is set to . - /// - /// - [ExcludeFromCodeCoverage] - public bool DisableChildTopics { - get => Attributes.GetBoolean("DisableChildTopics"); - set => SetAttributeValue("DisableChildTopics", value ? "1" : "0"); } + } - /*========================================================================================================================== - | PROPERTY: PERMITTED CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a read-only collection of what types of content types are permitted to be created as children of instances of - /// this content type. - /// - /// - /// - /// By default, topics are hierarchical: any topic can contain any number of child topics. While this flexibility makes - /// sense for both the library and the underlying data stores, however, it doesn't always make sense for individual - /// topics. For example, while it may make sense for a "Page" topic to have child "Comment" topics, it wouldn't make - /// sense for "Comment" topics to have child "Page" topics. This property allows the topics library to configure which - /// types of topics can be created under instances of the current content type. - /// - /// - /// It is important to note that this functionality only affects the Topic Editor interface by restricting the content - /// type of topics created under instances of this content type. This functionality is not enforced by the library - /// itself. As such, developers may programmatically add child topics to a topic regardless of whether it's associated - /// permits topics of that Content Type to be created. - /// - /// - /// To add content types to the collection, use . - /// - /// - public ReadOnlyKeyedTopicCollection PermittedContentTypes { - get { + /*============================================================================================================================ + | PROPERTY: ATTRIBUTE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a list of objects that are supported for objects implementing this + /// ContentType. + /// + /// + /// Attributes are not just derived from the specific Content Type topic in the database. They are also inherited from + /// any parent content types. For instance, if a Content Type "Page" has an attribute "Body", then all Content Types + /// created underneath "Page" will also have an attribute "Body". As such, the property + /// must crawl through each parent Content Type to collate the list of supported attributes. + /// + public AttributeDescriptorCollection AttributeDescriptors { + get { + + if (_attributeDescriptors is null) { /*---------------------------------------------------------------------------------------------------------------------- - | Populate values from relationships + | Create new instance \---------------------------------------------------------------------------------------------------------------------*/ - if (_permittedContentTypes is null) { - var permittedContentTypes = new KeyedTopicCollection(); - var contentTypes = Relationships.GetValues("ContentTypes"); - foreach (var contentType in contentTypes.Cast()) { - permittedContentTypes.Add(contentType); + _attributeDescriptors = new(); + + /*---------------------------------------------------------------------------------------------------------------------- + | Get values from nested topics + \---------------------------------------------------------------------------------------------------------------------*/ + if (Children.Contains("Attributes")) { + foreach (var attribute in Children["Attributes"].Children.Cast()) { + _attributeDescriptors.Add(attribute); } - _permittedContentTypes = new(permittedContentTypes); } /*---------------------------------------------------------------------------------------------------------------------- - | Return values + | Get values from parent \---------------------------------------------------------------------------------------------------------------------*/ - return _permittedContentTypes; - - } - } - - /*========================================================================================================================== - | PROPERTY: ATTRIBUTE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a list of objects that are supported for objects implementing this - /// ContentType. - /// - /// - /// Attributes are not just derived from the specific Content Type topic in the database. They are also inherited from - /// any parent content types. For instance, if a Content Type "Page" has an attribute "Body", then all Content Types - /// created underneath "Page" will also have an attribute "Body". As such, the property - /// must crawl through each parent Content Type to collate the list of supported attributes. - /// - public AttributeDescriptorCollection AttributeDescriptors { - get { - - if (_attributeDescriptors is null) { - - /*-------------------------------------------------------------------------------------------------------------------- - | Create new instance - \-------------------------------------------------------------------------------------------------------------------*/ - _attributeDescriptors = new(); - - /*-------------------------------------------------------------------------------------------------------------------- - | Get values from nested topics - \-------------------------------------------------------------------------------------------------------------------*/ - if (Children.Contains("Attributes")) { - foreach (var attribute in Children["Attributes"].Children.Cast()) { + var parent = Parent as ContentTypeDescriptor; + if (parent?.AttributeDescriptors is not null) { + foreach (var attribute in parent.AttributeDescriptors) { + if (!_attributeDescriptors.Contains(attribute.Key)) { _attributeDescriptors.Add(attribute); } } - - /*-------------------------------------------------------------------------------------------------------------------- - | Get values from parent - \-------------------------------------------------------------------------------------------------------------------*/ - var parent = Parent as ContentTypeDescriptor; - if (parent?.AttributeDescriptors is not null) { - foreach (var attribute in parent.AttributeDescriptors) { - if (!_attributeDescriptors.Contains(attribute.Key)) { - _attributeDescriptors.Add(attribute); - } - } - } - } - /*---------------------------------------------------------------------------------------------------------------------- - | Return the dictionary object - \---------------------------------------------------------------------------------------------------------------------*/ - return _attributeDescriptors; - } + /*------------------------------------------------------------------------------------------------------------------------ + | Return the dictionary object + \-----------------------------------------------------------------------------------------------------------------------*/ + return _attributeDescriptors; + } - /*========================================================================================================================== - | METHOD: RESET ATTRIBUTE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Resets the list of s stored in the collection on - /// not only this , but also any descendent s. - /// - /// - /// Each has an collection which includes not only - /// the s associated with that , but also any - /// s from any parent s in the topic graph. This - /// reflects the fact that attributes are inherited from parent content types. As a result, however, when an is added or removed, or a is moved to a new parent, - /// this cache should be reset on the associated and all descendent s to ensure the change is reflected. - /// - internal void ResetAttributeDescriptors() { - _attributeDescriptors = null!; - foreach (var topic in Children.Where(t => t is ContentTypeDescriptor).Cast()) { - topic.ResetAttributeDescriptors(); - } + } + + /*============================================================================================================================ + | METHOD: RESET ATTRIBUTE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Resets the list of s stored in the collection on + /// not only this , but also any descendent s. + /// + /// + /// Each has an collection which includes not only + /// the s associated with that , but also any + /// s from any parent s in the topic graph. This + /// reflects the fact that attributes are inherited from parent content types. As a result, however, when an is added or removed, or a is moved to a new parent, + /// this cache should be reset on the associated and all descendent s to ensure the change is reflected. + /// + internal void ResetAttributeDescriptors() { + _attributeDescriptors = null!; + foreach (var topic in Children.Where(t => t is ContentTypeDescriptor).Cast()) { + topic.ResetAttributeDescriptors(); } + } - /*========================================================================================================================== - | METHOD: RESET PERMITTED CONTENT TYPES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Resets the list of s stored in the collection - /// on this . - /// - /// - /// Each has a collection which includes the s associated with that . As this is cached, however, - /// the value should be reset whenever a has been modified, in case those values have - /// changed. - /// - internal void ResetPermittedContentTypes() => _permittedContentTypes = null; + /*============================================================================================================================ + | METHOD: RESET PERMITTED CONTENT TYPES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Resets the list of s stored in the collection + /// on this . + /// + /// + /// Each has a collection which includes the s associated with that . As this is cached, however, + /// the value should be reset whenever a has been modified, in case those values have + /// changed. + /// + internal void ResetPermittedContentTypes() => _permittedContentTypes = null; - /*========================================================================================================================== - | METHOD: IS TYPE OF? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether the Content Type that the current topic implements is, or derives from, a particular Content Type. - /// - /// The string identifier for the Content Type to compare to. - /// A Boolean value stating whether the current topic implements a particular Content Type. - /// - /// !String.IsNullOrWhiteSpace(contentTypeName) - /// - public bool IsTypeOf(string contentTypeName) { + /*============================================================================================================================ + | METHOD: IS TYPE OF? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether the Content Type that the current topic implements is, or derives from, a particular Content Type. + /// + /// The string identifier for the Content Type to compare to. + /// A Boolean value stating whether the current topic implements a particular Content Type. + /// + /// !String.IsNullOrWhiteSpace(contentTypeName) + /// + public bool IsTypeOf(string contentTypeName) { - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(!String.IsNullOrWhiteSpace(contentTypeName), "The attribute contentTypeName must be specified."); - TopicFactory.ValidateKey(contentTypeName); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(!String.IsNullOrWhiteSpace(contentTypeName), "The attribute contentTypeName must be specified."); + TopicFactory.ValidateKey(contentTypeName); - /*------------------------------------------------------------------------------------------------------------------------ - | Determine match - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentType = (ContentTypeDescriptor?)this; + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine match + \-------------------------------------------------------------------------------------------------------------------------*/ + var contentType = (ContentTypeDescriptor?)this; - while (contentType is not null) { - if (contentType.Key.Equals(contentTypeName, StringComparison.OrdinalIgnoreCase)) { - return true; - } - contentType = contentType.Parent as ContentTypeDescriptor; + while (contentType is not null) { + if (contentType.Key.Equals(contentTypeName, StringComparison.OrdinalIgnoreCase)) { + return true; } + contentType = contentType.Parent as ContentTypeDescriptor; + } - return false; + return false; - } + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Metadata/ContentTypeDescriptorCollection.cs b/OnTopic/Metadata/ContentTypeDescriptorCollection.cs index 2fad7be9..4682898e 100644 --- a/OnTopic/Metadata/ContentTypeDescriptorCollection.cs +++ b/OnTopic/Metadata/ContentTypeDescriptorCollection.cs @@ -7,82 +7,81 @@ using OnTopic.Querying; using OnTopic.Repositories; -namespace OnTopic.Metadata { +namespace OnTopic.Metadata; + +/*============================================================================================================================== +| CLASS: CONTENT TYPE DESCRIPTOR COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +/// +/// While the can be used to store any collection of objects, it has additional tooling in the form of the as well as the +/// constructor for handling a flattened list of s used for the method. +/// +public class ContentTypeDescriptorCollection : KeyedTopicCollection { /*============================================================================================================================ - | CLASS: CONTENT TYPE DESCRIPTOR COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Initializes a new instance of the class. /// - /// - /// While the can be used to store any collection of objects, it has additional tooling in the form of the as well as the - /// constructor for handling a flattened list of s used for the method. - /// - public class ContentTypeDescriptorCollection : KeyedTopicCollection { + public ContentTypeDescriptorCollection() : base(null) { + } - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - public ContentTypeDescriptorCollection() : base(null) { - } + /// + /// Initializes a new instance of the class based on a root . + /// + /// The from which to initialize the collection. + public ContentTypeDescriptorCollection(ContentTypeDescriptor? rootContentType) : base(null) { + Refresh(rootContentType); + } - /// - /// Initializes a new instance of the class based on a root . - /// - /// The from which to initialize the collection. - public ContentTypeDescriptorCollection(ContentTypeDescriptor? rootContentType) : base(null) { - Refresh(rootContentType); - } + /*============================================================================================================================ + | REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Updates the current instance of the based on a new root . + /// + /// The from which to initialize the collection. + public void Refresh(ContentTypeDescriptor? rootContentType) { - /*========================================================================================================================== - | REFRESH + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Updates the current instance of the based on a new root . - /// - /// The from which to initialize the collection. - public void Refresh(ContentTypeDescriptor? rootContentType) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - #pragma warning disable IDE0078 // Use pattern matching - if (rootContentType is null || rootContentType is { Children.Count: 0 }) { - return; - } - #pragma warning restore IDE0078 // Use pattern matching - - Contract.Requires( - rootContentType.Key.Equals("ContentTypes", StringComparison.OrdinalIgnoreCase), - $"The {nameof(rootContentType)} is expected to represent the root of the content type topic graph, with a " + - $"key of 'ContentTypes'. Instead, the supplied ContentTypeDescriptor has a key of '{rootContentType.Key}'." - ); + #pragma warning disable IDE0078 // Use pattern matching + if (rootContentType is null || rootContentType is { Children.Count: 0 }) { + return; + } + #pragma warning restore IDE0078 // Use pattern matching - /*------------------------------------------------------------------------------------------------------------------------ - | Clear any existing values - \-----------------------------------------------------------------------------------------------------------------------*/ - Clear(); + Contract.Requires( + rootContentType.Key.Equals("ContentTypes", StringComparison.OrdinalIgnoreCase), + $"The {nameof(rootContentType)} is expected to represent the root of the content type topic graph, with a " + + $"key of 'ContentTypes'. Instead, the supplied ContentTypeDescriptor has a key of '{rootContentType.Key}'." + ); - /*------------------------------------------------------------------------------------------------------------------------ - | Add all ContentTypeDescriptors to collection - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentTypeDescriptors = rootContentType - .FindAll(t => t is ContentTypeDescriptor) - .Cast(); - foreach (var contentType in contentTypeDescriptors) { - Add((ContentTypeDescriptor)contentType); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Clear any existing values + \-------------------------------------------------------------------------------------------------------------------------*/ + Clear(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Add all ContentTypeDescriptors to collection + \-------------------------------------------------------------------------------------------------------------------------*/ + var contentTypeDescriptors = rootContentType + .FindAll(t => t is ContentTypeDescriptor) + .Cast(); + foreach (var contentType in contentTypeDescriptors) { + Add((ContentTypeDescriptor)contentType); } - } //Class -} //Namespace \ No newline at end of file + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Metadata/ModelType.cs b/OnTopic/Metadata/ModelType.cs index 80e5c75d..c71cce0b 100644 --- a/OnTopic/Metadata/ModelType.cs +++ b/OnTopic/Metadata/ModelType.cs @@ -4,72 +4,71 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Metadata { +namespace OnTopic.Metadata; - /*============================================================================================================================ - | ENUM: MODEL TYPE +/*============================================================================================================================== +| ENUM: MODEL TYPE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides options describing how a specific attribute is exposed in terms of the Topic Library's object model. +/// +public enum ModelType { + + /*---------------------------------------------------------------------------------------------------------------------------- + | NONE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides options describing how a specific attribute is exposed in terms of the Topic Library's object model. + /// No value is configured. /// - public enum ModelType { - - /*-------------------------------------------------------------------------------------------------------------------------- - | NONE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// No value is configured. - /// - None = 0, + None = 0, - /*-------------------------------------------------------------------------------------------------------------------------- - | SCALAR VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A standard attribute value, exposed primarily through the collection, or a - /// corresponding property. - /// - ScalarValue = 1, + /*---------------------------------------------------------------------------------------------------------------------------- + | SCALAR VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A standard attribute value, exposed primarily through the collection, or a + /// corresponding property. + /// + ScalarValue = 1, - /*-------------------------------------------------------------------------------------------------------------------------- - | RELATIONSHIP - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A relationship to a collection of separate s. Relationships are exposed as strongly-typed - /// collections through the property. - /// - Relationship = 2, + /*---------------------------------------------------------------------------------------------------------------------------- + | RELATIONSHIP + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A relationship to a collection of separate s. Relationships are exposed as strongly-typed + /// collections through the property. + /// + Relationship = 2, - /*-------------------------------------------------------------------------------------------------------------------------- - | TOPIC REFERENCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A reference to a separate . References are ideally exposed and populated as strongly-typed - /// properties on —or a derived class—as done with e.g. . - /// - Reference = 3, + /*---------------------------------------------------------------------------------------------------------------------------- + | TOPIC REFERENCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A reference to a separate . References are ideally exposed and populated as strongly-typed + /// properties on —or a derived class—as done with e.g. . + /// + Reference = 3, - /*-------------------------------------------------------------------------------------------------------------------------- - | NESTED TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A set of child s packaged as part of the current . - /// - NestedTopic = 4, + /*---------------------------------------------------------------------------------------------------------------------------- + | NESTED TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A set of child s packaged as part of the current . + /// + NestedTopic = 4, - /*-------------------------------------------------------------------------------------------------------------------------- - | REFLEXIVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A special value for s placed on s, which specifies - /// that the should be inherited from the . - /// - /// - /// This is useful for implementing an which reflects the it is placed on. For example, the attribute should store the value - /// in the same location as the for which it's setting. - /// - Reflexive = 5 + /*---------------------------------------------------------------------------------------------------------------------------- + | REFLEXIVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A special value for s placed on s, which specifies + /// that the should be inherited from the . + /// + /// + /// This is useful for implementing an which reflects the it is placed on. For example, the attribute should store the value + /// in the same location as the for which it's setting. + /// + Reflexive = 5 - } //Enum -} //Namespace \ No newline at end of file +} //Enum \ No newline at end of file diff --git a/OnTopic/Models/IAssociatedTopicBindingModel.cs b/OnTopic/Models/IAssociatedTopicBindingModel.cs index e0df1ba7..4e2a89a2 100644 --- a/OnTopic/Models/IAssociatedTopicBindingModel.cs +++ b/OnTopic/Models/IAssociatedTopicBindingModel.cs @@ -6,32 +6,31 @@ using System.ComponentModel.DataAnnotations; using OnTopic.Mapping.Reverse; -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: ASSOCIATED TOPIC BINDING MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a generic data transfer topic for binding an association of a binding model to an existing . +/// +/// +/// It is strictly required that any binding models used as associations implement the interface for the default to correctly identify +/// and map an association back to a . +/// +public interface IAssociatedTopicBindingModel { /*============================================================================================================================ - | INTERFACE: ASSOCIATED TOPIC BINDING MODEL + | PROPERTY: UNIQUE KEY \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a generic data transfer topic for binding an association of a binding model to an existing . + /// Gets or sets the topic's attribute, the unique text identifier for the topic. /// - /// - /// It is strictly required that any binding models used as associations implement the interface for the default to correctly identify - /// and map an association back to a . - /// - public interface IAssociatedTopicBindingModel { - - /*========================================================================================================================== - | PROPERTY: UNIQUE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's attribute, the unique text identifier for the topic. - /// - /// - /// value is not null - /// - [Required, NotNull, DisallowNull] - string? UniqueKey { get; init; } + /// + /// value is not null + /// + [Required, NotNull, DisallowNull] + string? UniqueKey { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/ICoreTopicViewModel.cs b/OnTopic/Models/ICoreTopicViewModel.cs index 5096d783..28d1e0fe 100644 --- a/OnTopic/Models/ICoreTopicViewModel.cs +++ b/OnTopic/Models/ICoreTopicViewModel.cs @@ -8,52 +8,51 @@ using OnTopic.Mapping; using OnTopic.Metadata; -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: CORE TOPIC VIEW MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Ensures that a model maintains, at minimum, a and property, which are +/// expected of all s. +/// +/// +/// +/// This is necessary to support e.g. a , while also allowing it to filter by +/// —a common requirement for topic (view model) collections. +/// +/// +/// It is not required that topic view models implement the interface for the to correctly identify and map s to topic view models. That said, the +/// interface does ensure that those view models can be keyed, which is useful for, especially, child collections. +/// +/// +public interface ICoreTopicViewModel { + + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the topic's attribute, the primary text identifier for the . + /// + /// + /// value is not null + /// + [Required, NotNull, DisallowNull] + string? Key { get; init; } /*============================================================================================================================ - | INTERFACE: CORE TOPIC VIEW MODEL + | PROPERTY: CONTENT TYPE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Ensures that a model maintains, at minimum, a and property, which are - /// expected of all s. + /// Gets the key name of the content type that the current topic represents. /// /// - /// - /// This is necessary to support e.g. a , while also allowing it to filter by - /// —a common requirement for topic (view model) collections. - /// - /// - /// It is not required that topic view models implement the interface for the to correctly identify and map s to topic view models. That said, the - /// interface does ensure that those view models can be keyed, which is useful for, especially, child collections. - /// + /// Each topic is associated with a content type. The content type determines which attributes are displayed in the Topics + /// Editor (via the property). /// - public interface ICoreTopicViewModel { - - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the topic's attribute, the primary text identifier for the . - /// - /// - /// value is not null - /// - [Required, NotNull, DisallowNull] - string? Key { get; init; } - - /*========================================================================================================================== - | PROPERTY: CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the key name of the content type that the current topic represents. - /// - /// - /// Each topic is associated with a content type. The content type determines which attributes are displayed in the Topics - /// Editor (via the property). - /// - [Required, NotNull, DisallowNull] - string? ContentType { get; init; } + [Required, NotNull, DisallowNull] + string? ContentType { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/IHierarchicalTopicViewModel{T}.cs b/OnTopic/Models/IHierarchicalTopicViewModel{T}.cs index ee2869b1..1f171676 100644 --- a/OnTopic/Models/IHierarchicalTopicViewModel{T}.cs +++ b/OnTopic/Models/IHierarchicalTopicViewModel{T}.cs @@ -6,28 +6,27 @@ using System.Collections.ObjectModel; using OnTopic.Mapping.Hierarchical; -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: HIERARCHICAL VIEW MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides an interface for a view model that is hierarchical—i.e., supports populating child objects. +/// +/// +/// Using the interface allows the to remain view model agnostic, thus working with lightly-decorated POCOs. +/// It makes no other assumptions about the interface outside of those absolutely necessary to support a hierarchy. +/// +public interface IHierarchicalTopicViewModel where T : IHierarchicalTopicViewModel { /*============================================================================================================================ - | INTERFACE: HIERARCHICAL VIEW MODEL + | PROPERTY: CHILDREN \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides an interface for a view model that is hierarchical—i.e., supports populating child objects. + /// Represents a collection of child instances. /// - /// - /// Using the interface allows the to remain view model agnostic, thus working with lightly-decorated POCOs. - /// It makes no other assumptions about the interface outside of those absolutely necessary to support a hierarchy. - /// - public interface IHierarchicalTopicViewModel where T : IHierarchicalTopicViewModel { - - /*========================================================================================================================== - | PROPERTY: CHILDREN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Represents a collection of child instances. - /// - Collection Children { get; } + Collection Children { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/INavigableTopicViewModel.cs b/OnTopic/Models/INavigableTopicViewModel.cs index df13b929..e5667aaa 100644 --- a/OnTopic/Models/INavigableTopicViewModel.cs +++ b/OnTopic/Models/INavigableTopicViewModel.cs @@ -5,42 +5,41 @@ \=============================================================================================================================*/ using System.ComponentModel.DataAnnotations; -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: NAVIGABLE TOPIC VIEW MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Ensures basic properties needed to treat a view model as a navigable entry. +/// +/// +/// No topics are expected to have a Navigable content type. Instead, implementers of this view model are expected +/// to manually construct instances. +/// +public interface INavigableTopicViewModel { + + /*============================================================================================================================ + | PROPERTY: TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required, NotNull, DisallowNull] + string? Title { get; init; } /*============================================================================================================================ - | INTERFACE: NAVIGABLE TOPIC VIEW MODEL + | PROPERTY: SHORT TITLE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Ensures basic properties needed to treat a view model as a navigable entry. + /// In addition to the Title, a site may opt to define a Short Title used exclusively in the navigation. If present, this + /// value should be used instead of Title. /// - /// - /// No topics are expected to have a Navigable content type. Instead, implementers of this view model are expected - /// to manually construct instances. - /// - public interface INavigableTopicViewModel { + string? ShortTitle { get; init; } - /*========================================================================================================================== - | PROPERTY: TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required, NotNull, DisallowNull] - string? Title { get; init; } - - /*========================================================================================================================== - | PROPERTY: SHORT TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// In addition to the Title, a site may opt to define a Short Title used exclusively in the navigation. If present, this - /// value should be used instead of Title. - /// - string? ShortTitle { get; init; } - - /*========================================================================================================================== - | PROPERTY: WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - [Required, NotNull, DisallowNull] - string? WebPath { get; init; } + /*============================================================================================================================ + | PROPERTY: WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + [Required, NotNull, DisallowNull] + string? WebPath { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/INavigationTopicViewModel{T}.cs b/OnTopic/Models/INavigationTopicViewModel{T}.cs index 5028f471..2d5b1870 100644 --- a/OnTopic/Models/INavigationTopicViewModel{T}.cs +++ b/OnTopic/Models/INavigationTopicViewModel{T}.cs @@ -4,33 +4,32 @@ | Project Website \=============================================================================================================================*/ -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: NAVIGATION TOPIC VIEW MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a generic model for feeding views information about a navigation entry. +/// +/// +/// No topics are expected to have a Navigation content type. Instead, implementers of this view model are expected +/// to manually construct instances. +/// +public interface INavigationTopicViewModel : + INavigableTopicViewModel, + IHierarchicalTopicViewModel where T: INavigationTopicViewModel +{ /*============================================================================================================================ - | INTERFACE: NAVIGATION TOPIC VIEW MODEL + | METHOD: IS SELECTED? \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a generic model for feeding views information about a navigation entry. + /// Determines if the current item is selected based on the provided . /// - /// - /// No topics are expected to have a Navigation content type. Instead, implementers of this view model are expected - /// to manually construct instances. - /// - public interface INavigationTopicViewModel : - INavigableTopicViewModel, - IHierarchicalTopicViewModel where T: INavigationTopicViewModel - { - - /*========================================================================================================================== - | METHOD: IS SELECTED? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if the current item is selected based on the provided . - /// - /// - /// The path to compare against the current - /// - bool IsSelected(string webPath); + /// + /// The path to compare against the current + /// + bool IsSelected(string webPath); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/IPageTopicViewModel.cs b/OnTopic/Models/IPageTopicViewModel.cs index f6f6974a..b73ee970 100644 --- a/OnTopic/Models/IPageTopicViewModel.cs +++ b/OnTopic/Models/IPageTopicViewModel.cs @@ -5,42 +5,41 @@ \=============================================================================================================================*/ using OnTopic.Mapping; -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: PAGE TOPIC VIEW MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a generic data transfer topic for feeding views based on the page content type. +/// +/// +/// +/// It is not strictly required that topic view models implement the interface for the +/// default to correctly identify and map s to topic view models. +/// That said, the interface does define properties that presentation infrastructure may expect. As a result, if it isn't +/// provided via the public interface then it will instead need to be defined in some other way. +/// +/// +[Obsolete($"The {nameof(IPageTopicViewModel)} is no longer utilized.", true)] +public interface IPageTopicViewModel : ITopicViewModel, INavigableTopicViewModel { /*============================================================================================================================ - | INTERFACE: PAGE TOPIC VIEW MODEL + | PROPERTY: META KEYWORDS \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a generic data transfer topic for feeding views based on the page content type. + /// Gets or sets the Meta Keywords attribute, which represents the HTML metadata that will be presented alongside the + /// page. /// - /// - /// - /// It is not strictly required that topic view models implement the interface for the - /// default to correctly identify and map s to topic view models. - /// That said, the interface does define properties that presentation infrastructure may expect. As a result, if it isn't - /// provided via the public interface then it will instead need to be defined in some other way. - /// - /// - [Obsolete($"The {nameof(IPageTopicViewModel)} is no longer utilized.", true)] - public interface IPageTopicViewModel : ITopicViewModel, INavigableTopicViewModel { - - /*========================================================================================================================== - | PROPERTY: META KEYWORDS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Meta Keywords attribute, which represents the HTML metadata that will be presented alongside the - /// page. - /// - string? MetaKeywords { get; init; } + string? MetaKeywords { get; init; } - /*========================================================================================================================== - | PROPERTY: META DESCRIPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Meta Description attribute, which represents the HTML metadata that will be presented alongside the - /// page. - /// - string? MetaDescription { get; init; } + /*============================================================================================================================ + | PROPERTY: META DESCRIPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the Meta Description attribute, which represents the HTML metadata that will be presented alongside the + /// page. + /// + string? MetaDescription { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/IRelatedTopicBindingModel.cs b/OnTopic/Models/IRelatedTopicBindingModel.cs index 4d960171..9efcfc8e 100644 --- a/OnTopic/Models/IRelatedTopicBindingModel.cs +++ b/OnTopic/Models/IRelatedTopicBindingModel.cs @@ -5,24 +5,23 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Reverse; -namespace OnTopic.Models { +namespace OnTopic.Models; - /*============================================================================================================================ - | INTERFACE: RELATED TOPIC BINDING MODEL - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a generic data transfer topic for binding an association of a binding model to an existing . - /// - /// - /// It is strictly required that any binding models used as associations implement the interface for the default to correctly identify and map an association back - /// to a . - /// - [Obsolete( - "The IRelatedTopicBindingModel has been replaced by the IAssociatedTopicBindingModel. Please update references.", - true - )] - public interface IRelatedTopicBindingModel: IAssociatedTopicBindingModel { +/*============================================================================================================================== +| INTERFACE: RELATED TOPIC BINDING MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a generic data transfer topic for binding an association of a binding model to an existing . +/// +/// +/// It is strictly required that any binding models used as associations implement the interface for the default to correctly identify and map an association back +/// to a . +/// +[Obsolete( + "The IRelatedTopicBindingModel has been replaced by the IAssociatedTopicBindingModel. Please update references.", + true +)] +public interface IRelatedTopicBindingModel: IAssociatedTopicBindingModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/ITopicBindingModel.cs b/OnTopic/Models/ITopicBindingModel.cs index fe24aa13..3acd39ee 100644 --- a/OnTopic/Models/ITopicBindingModel.cs +++ b/OnTopic/Models/ITopicBindingModel.cs @@ -5,20 +5,19 @@ \=============================================================================================================================*/ using OnTopic.Mapping.Reverse; -namespace OnTopic.Models { +namespace OnTopic.Models; - /*============================================================================================================================ - | INTERFACE: TOPIC BINDING MODEL - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a generic data transfer topic for binding form values to controller actions. - /// - /// - /// It is strictly required that topic binding models implement the interface for the - /// default to correctly identify and map a binding model to a . - /// - public interface ITopicBindingModel: ICoreTopicViewModel { +/*============================================================================================================================== +| INTERFACE: TOPIC BINDING MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a generic data transfer topic for binding form values to controller actions. +/// +/// +/// It is strictly required that topic binding models implement the interface for the +/// default to correctly identify and map a binding model to a . +/// +public interface ITopicBindingModel: ICoreTopicViewModel { - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Models/ITopicViewModel.cs b/OnTopic/Models/ITopicViewModel.cs index 91e61860..2c77ec7d 100644 --- a/OnTopic/Models/ITopicViewModel.cs +++ b/OnTopic/Models/ITopicViewModel.cs @@ -6,86 +6,85 @@ using System.ComponentModel.DataAnnotations; using OnTopic.Mapping; -namespace OnTopic.Models { +namespace OnTopic.Models; + +/*============================================================================================================================== +| INTERFACE: TOPIC VIEW MODEL +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a generic data transfer topic for feeding views. +/// +/// +/// +/// It is not strictly required that topic view models implement the interface for the +/// default to correctly identify and map s to topic view models. +/// That said, the interface does define properties that presentation infrastructure may expect. As a result, if it isn't +/// provided via the public interface then it will instead need to be defined in some other way. +/// +/// +/// For instance, in the default MVC library, the TopicViewResult class requires that the and be supplied separately if they're not provided as part of a . The exact details of this will obviously vary based on the implementation of the presentation +/// layer and any supporting libraries. +/// +/// +public interface ITopicViewModel: ICoreTopicViewModel, IAssociatedTopicBindingModel, ITopicBindingModel { /*============================================================================================================================ - | INTERFACE: TOPIC VIEW MODEL + | PROPERTY: ID \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a generic data transfer topic for feeding views. + /// Gets or sets the topic's ID attribute, the primary unique identifier for the topic. /// - /// - /// - /// It is not strictly required that topic view models implement the interface for the - /// default to correctly identify and map s to topic view models. - /// That said, the interface does define properties that presentation infrastructure may expect. As a result, if it isn't - /// provided via the public interface then it will instead need to be defined in some other way. - /// - /// - /// For instance, in the default MVC library, the TopicViewResult class requires that the and be supplied separately if they're not provided as part of a . The exact details of this will obviously vary based on the implementation of the presentation - /// layer and any supporting libraries. - /// - /// - public interface ITopicViewModel: ICoreTopicViewModel, IAssociatedTopicBindingModel, ITopicBindingModel { + int Id { get; init; } - /*========================================================================================================================== - | PROPERTY: ID - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's ID attribute, the primary unique identifier for the topic. - /// - int Id { get; init; } - - /*========================================================================================================================== - | PROPERTY: WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's attribute, which represents the in its URL format. - /// - [Required, NotNull, DisallowNull] - string? WebPath { get; init; } + /*============================================================================================================================ + | PROPERTY: WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the topic's attribute, which represents the in its URL format. + /// + [Required, NotNull, DisallowNull] + string? WebPath { get; init; } - /*========================================================================================================================== - | PROPERTY: VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the View attribute, representing the default view to be used for the topic. - /// - /// - /// This value can be set via the query string (via the TopicViewResultExecutor class), via the Accepts header - /// (also via the TopicViewResultExecutor class), on the topic itself (via this property), or via the . By default, it will be set to the name of the ; e.g., if the Content Type is Page, then the view will be Page. This will cause the - /// TopicViewResultExecutor to look for a view at, for instance, /Views/Page/Page.cshtml. - /// - string? View { get; init; } + /*============================================================================================================================ + | PROPERTY: VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the View attribute, representing the default view to be used for the topic. + /// + /// + /// This value can be set via the query string (via the TopicViewResultExecutor class), via the Accepts header + /// (also via the TopicViewResultExecutor class), on the topic itself (via this property), or via the . By default, it will be set to the name of the ; e.g., if the Content Type is Page, then the view will be Page. This will cause the + /// TopicViewResultExecutor to look for a view at, for instance, /Views/Page/Page.cshtml. + /// + string? View { get; init; } - /*========================================================================================================================== - | PROPERTY: IS HIDDEN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether the current topic is hidden. - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The IsHidden property is no longer supported by {nameof(ITopicViewModel)}.", true)] - bool IsHidden { get; init; } + /*============================================================================================================================ + | PROPERTY: IS HIDDEN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether the current topic is hidden. + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The IsHidden property is no longer supported by {nameof(ITopicViewModel)}.", true)] + bool IsHidden { get; init; } - /*========================================================================================================================== - | PROPERTY: TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Title attribute, which represents the friendly name of the topic. - /// - /// - /// While the may not contain, for instance, spaces or symbols, there are no - /// restrictions on what characters can be used in the title. For this reason, it provides the default public value for - /// referencing topics. - /// - [Required, NotNull, DisallowNull] - string? Title { get; init; } + /*============================================================================================================================ + | PROPERTY: TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the Title attribute, which represents the friendly name of the topic. + /// + /// + /// While the may not contain, for instance, spaces or symbols, there are no + /// restrictions on what characters can be used in the title. For this reason, it provides the default public value for + /// referencing topics. + /// + [Required, NotNull, DisallowNull] + string? Title { get; init; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Attributes/AttributeValue.cs b/OnTopic/Obsolete/Attributes/AttributeValue.cs index e7cd82a4..7cbe16fb 100644 --- a/OnTopic/Obsolete/Attributes/AttributeValue.cs +++ b/OnTopic/Obsolete/Attributes/AttributeValue.cs @@ -9,213 +9,212 @@ #pragma warning disable IDE0060 // Remove unused parameter -namespace OnTopic.Attributes { +namespace OnTopic.Attributes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE VALUE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents the immutable value of a particular attribute on a . +/// +/// +/// +/// Provides values and metadata specific to individual attribute values, such as state (e.g., the +/// property signifies whether the attribute value has changed) and its date. +/// +/// +/// Typically, the will be exposed as part of a via +/// the collection. +/// +/// +/// Be aware that while represents the value of a specific attribute, the metadata for +/// describing the purpose, constraints, and usage of that particular attribute is described by the class. +/// +/// +/// This class is immutable: once it is constructed, the values cannot be changed. To change a value, callers must either +/// create a new instance of the class or, preferably, call the +/// 's +/// method. +/// +/// +[ExcludeFromCodeCoverage] +[Obsolete($"The {nameof(AttributeValue)} type has been renamed to {nameof(AttributeRecord)}.", true)] +public class AttributeValue { + + /*============================================================================================================================ + | CONSTRUCTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Initializes a new instance of the class, using the specified key/value pair. + /// + /// + /// The string identifier for the collection item key/value pair. + /// + /// + /// The string value text for the collection item key/value pair. + /// + /// + /// An optional boolean indicator noting whether the collection item is a new value, and + /// should thus be saved to the database when is next called. + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + public AttributeValue(string key, string? value, bool isDirty = true) { + throw new NotImplementedException(); + } + + /// + /// Initializes a new instance of the class, using the specified key/value pair. + /// + /// + /// The string identifier for the collection item key/value pair. + /// + /// + /// The string value text for the collection item key/value pair. + /// + /// + /// An optional boolean indicator noting whether the collection item is a new value, and + /// should thus be saved to the database when is next called. + /// + /// + /// If disabled, will not call local properties on that + /// correspond to the as a means of enforcing the business logic. + /// + /// + /// The value that the attribute was last modified. This is intended exclusively for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// Determines if the attribute originated from an extended attributes data store. + /// + /// !String.IsNullOrWhiteSpace(key) + /// + internal AttributeValue( + string key, + string? value, + bool isDirty, + bool enforceBusinessLogic, + DateTime? lastModified = null, + bool? isExtendedAttribute = null + ) : this( + key, + value, + isDirty + ) { + throw new NotImplementedException(); + } + + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the key of the attribute. + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public string Key { get; } + + /*============================================================================================================================ + | PROPERTY: VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the current value of the attribute. + /// + public string? Value { get; } /*============================================================================================================================ - | CLASS: ATTRIBUTE VALUE + | PROPERTY: IS DIRTY \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents the immutable value of a particular attribute on a . + /// Boolean setting which is set automatically when an attribute's is set to a new value. + /// + /// + /// The IsDirty property is used by the to determine whether or not + /// the value has been persisted to the database. If it is set to true, the attribute's value is sent to the database + /// when is called. Otherwise, it is + /// ignored, thus preventing the need to update attributes (or create new versions of attributes) whose values haven't + /// changed. + /// + public bool IsDirty { get; set; } + + /*============================================================================================================================ + | PROPERTY: ENFORCE BUSINESS LOGIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether business logic should be enforced when adding an to an + /// . + /// + /// + /// By default, when a user attempts to update an attribute's value by calling , or when an is added to the , the will automatically attempt to call any corresponding setters on + /// (or a derived instance) to ensure that the business logic is enforced. To avoid an infinite loop, however, this is + /// disabled when properties on call . + /// When that happens, the value is set to false to communicate to the that it should not call the local property. This value is only intended for internal + /// use. + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + internal bool EnforceBusinessLogic { get; set; } + + /*============================================================================================================================ + | PROPERTY: LAST MODIFIED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Read-only reference to the last DateTime the instance was updated. + /// + public DateTime LastModified { get; internal set; } = DateTime.Now; + + /*============================================================================================================================ + | PROPERTY: IS EXTENDED ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if this attribute originated from a data store as an extended attribute. /// /// /// - /// Provides values and metadata specific to individual attribute values, such as state (e.g., the - /// property signifies whether the attribute value has changed) and its date. - /// - /// - /// Typically, the will be exposed as part of a via - /// the collection. + /// How an attribute is stored in the underlying repository doesn't impact how the attribute is treated as part of the + /// object model. By tracking this, however, OnTopic is able to evaluate configuration mismatches during . This allows the to effective handle + /// scenarios where the configuration for an has changed prior to the last time a was saved, and thus change the location where it is stored. /// /// - /// Be aware that while represents the value of a specific attribute, the metadata for - /// describing the purpose, constraints, and usage of that particular attribute is described by the class. + /// This is important because, otherwise, implementations rely primarily on to determine if a value should be saved. If an attribute's value hasn't changed, but the location + /// it should be stored has, that could potentially result in the attribute being deleted, as the attribute won't show + /// up for when is called with isDirty set to true and + /// isExtendedAttribute is set to either true or false. By introducing , the is able to detect conflicts between the configuration and + /// the underlying data store, and ensure data is stored appropriately. /// /// - /// This class is immutable: once it is constructed, the values cannot be changed. To change a value, callers must either - /// create a new instance of the class or, preferably, call the - /// 's - /// method. + /// The property maps to the + /// property. The former describes where the data was actually stored, whereas the latter describes where the + /// data should be stored. /// /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(AttributeValue)} type has been renamed to {nameof(AttributeRecord)}.", true)] - public class AttributeValue { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class, using the specified key/value pair. - /// - /// - /// The string identifier for the collection item key/value pair. - /// - /// - /// The string value text for the collection item key/value pair. - /// - /// - /// An optional boolean indicator noting whether the collection item is a new value, and - /// should thus be saved to the database when is next called. - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - public AttributeValue(string key, string? value, bool isDirty = true) { - throw new NotImplementedException(); - } - - /// - /// Initializes a new instance of the class, using the specified key/value pair. - /// - /// - /// The string identifier for the collection item key/value pair. - /// - /// - /// The string value text for the collection item key/value pair. - /// - /// - /// An optional boolean indicator noting whether the collection item is a new value, and - /// should thus be saved to the database when is next called. - /// - /// - /// If disabled, will not call local properties on that - /// correspond to the as a means of enforcing the business logic. - /// - /// - /// The value that the attribute was last modified. This is intended exclusively for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// Determines if the attribute originated from an extended attributes data store. - /// - /// !String.IsNullOrWhiteSpace(key) - /// - internal AttributeValue( - string key, - string? value, - bool isDirty, - bool enforceBusinessLogic, - DateTime? lastModified = null, - bool? isExtendedAttribute = null - ) : this( - key, - value, - isDirty - ) { - throw new NotImplementedException(); - } - - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the key of the attribute. - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public string Key { get; } - - /*========================================================================================================================== - | PROPERTY: VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the current value of the attribute. - /// - public string? Value { get; } - - /*========================================================================================================================== - | PROPERTY: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Boolean setting which is set automatically when an attribute's is set to a new value. - /// - /// - /// The IsDirty property is used by the to determine whether or not - /// the value has been persisted to the database. If it is set to true, the attribute's value is sent to the database - /// when is called. Otherwise, it is - /// ignored, thus preventing the need to update attributes (or create new versions of attributes) whose values haven't - /// changed. - /// - public bool IsDirty { get; set; } - - /*========================================================================================================================== - | PROPERTY: ENFORCE BUSINESS LOGIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether business logic should be enforced when adding an to an - /// . - /// - /// - /// By default, when a user attempts to update an attribute's value by calling , or when an is added to the , the will automatically attempt to call any corresponding setters on - /// (or a derived instance) to ensure that the business logic is enforced. To avoid an infinite loop, however, this is - /// disabled when properties on call . - /// When that happens, the value is set to false to communicate to the that it should not call the local property. This value is only intended for internal - /// use. - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - internal bool EnforceBusinessLogic { get; set; } - - /*========================================================================================================================== - | PROPERTY: LAST MODIFIED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Read-only reference to the last DateTime the instance was updated. - /// - public DateTime LastModified { get; internal set; } = DateTime.Now; - - /*========================================================================================================================== - | PROPERTY: IS EXTENDED ATTRIBUTE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if this attribute originated from a data store as an extended attribute. - /// - /// - /// - /// How an attribute is stored in the underlying repository doesn't impact how the attribute is treated as part of the - /// object model. By tracking this, however, OnTopic is able to evaluate configuration mismatches during . This allows the to effective handle - /// scenarios where the configuration for an has changed prior to the last time a was saved, and thus change the location where it is stored. - /// - /// - /// This is important because, otherwise, implementations rely primarily on to determine if a value should be saved. If an attribute's value hasn't changed, but the location - /// it should be stored has, that could potentially result in the attribute being deleted, as the attribute won't show - /// up for when is called with isDirty set to true and - /// isExtendedAttribute is set to either true or false. By introducing , the is able to detect conflicts between the configuration and - /// the underlying data store, and ensure data is stored appropriately. - /// - /// - /// The property maps to the - /// property. The former describes where the data was actually stored, whereas the latter describes where the - /// data should be stored. - /// - /// - public bool? IsExtendedAttribute { get; internal set; } + public bool? IsExtendedAttribute { get; internal set; } - } //Class -} //Namespace +} //Class #pragma warning restore IDE0060 // Remove unused parameter \ No newline at end of file diff --git a/OnTopic/Obsolete/Collections/AttributeValueCollection.cs b/OnTopic/Obsolete/Collections/AttributeValueCollection.cs index e45431cb..a30ee5a4 100644 --- a/OnTopic/Obsolete/Collections/AttributeValueCollection.cs +++ b/OnTopic/Obsolete/Collections/AttributeValueCollection.cs @@ -8,341 +8,340 @@ #pragma warning disable IDE0060 // Remove unused parameter -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE VALUE COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Represents a collection of objects. +/// +/// +/// objects represent individual instances of attributes associated with particular topics. +/// The class tracks these through its property, which is an instance of +/// the class. +/// +[ExcludeFromCodeCoverage] +[Obsolete($"The {nameof(AttributeValueCollection)} class has been renamed to {nameof(AttributeCollection)}.", true)] +public class AttributeValueCollection : KeyedCollection { /*============================================================================================================================ - | CLASS: ATTRIBUTE VALUE COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Represents a collection of objects. + /// Initializes a new instance of the class. /// /// - /// objects represent individual instances of attributes associated with particular topics. - /// The class tracks these through its property, which is an instance of - /// the class. + /// The is intended exclusively for providing access to attributes via the + /// property. For this reason, the constructor is marked as internal. /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(AttributeValueCollection)} class has been renamed to {nameof(AttributeCollection)}.", true)] - public class AttributeValueCollection : KeyedCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// - /// The is intended exclusively for providing access to attributes via the - /// property. For this reason, the constructor is marked as internal. - /// - /// A reference to the topic that the current attribute collection is bound to. - internal AttributeValueCollection(Topic parentTopic) : base(StringComparer.InvariantCultureIgnoreCase) { - throw new NotImplementedException(); - } + /// A reference to the topic that the current attribute collection is bound to. + internal AttributeValueCollection(Topic parentTopic) : base(StringComparer.InvariantCultureIgnoreCase) { + throw new NotImplementedException(); + } - /*========================================================================================================================== - | METHOD: IS DIRTY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determine if any attributes in the are dirty. - /// - /// - /// This method is intended primarily for data storage providers, such as , which may need - /// to determine if any attributes are dirty prior to saving them to the data storage medium. Be aware that this does - /// not track whether any have been modified; as such, it may still be necessary - /// to persist changes to the storage medium. - /// - /// - /// Optionally excludes s whose keys start with LastModified. This is useful for - /// excluding the byline (LastModifiedBy) and dateline (LastModified) since these values are automatically - /// generated by e.g. the OnTopic Editor and, thus, may be irrelevant updates if no other attribute values have changed. - /// - /// True if the attribute value is marked as dirty; otherwise false. - public bool IsDirty(bool excludeLastModified = false) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: IS DIRTY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determine if any attributes in the are dirty. + /// + /// + /// This method is intended primarily for data storage providers, such as , which may need + /// to determine if any attributes are dirty prior to saving them to the data storage medium. Be aware that this does + /// not track whether any have been modified; as such, it may still be necessary + /// to persist changes to the storage medium. + /// + /// + /// Optionally excludes s whose keys start with LastModified. This is useful for + /// excluding the byline (LastModifiedBy) and dateline (LastModified) since these values are automatically + /// generated by e.g. the OnTopic Editor and, thus, may be irrelevant updates if no other attribute values have changed. + /// + /// True if the attribute value is marked as dirty; otherwise false. + public bool IsDirty(bool excludeLastModified = false) => throw new NotImplementedException(); - /// - /// Determine if a given attribute is marked as dirty. Will return false if the attribute key cannot be found. - /// - /// - /// This method is intended primarily for data storage providers, such as , which may need - /// to determine if a specific attribute key is dirty prior to saving it to the data storage medium. Because IsDirty - /// is a state of the current , it does not support inheritFromParent or - /// inheritFromDerived (which otherwise default to true). - /// - /// The string identifier for the . - /// True if the attribute value is marked as dirty; otherwise false. - public bool IsDirty(string name) => throw new NotImplementedException(); + /// + /// Determine if a given attribute is marked as dirty. Will return false if the attribute key cannot be found. + /// + /// + /// This method is intended primarily for data storage providers, such as , which may need + /// to determine if a specific attribute key is dirty prior to saving it to the data storage medium. Because IsDirty + /// is a state of the current , it does not support inheritFromParent or + /// inheritFromDerived (which otherwise default to true). + /// + /// The string identifier for the . + /// True if the attribute value is marked as dirty; otherwise false. + public bool IsDirty(string name) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Marks the collection—including all items—as clean, meaning they have been persisted to - /// the underlying . - /// - /// - /// This method is intended primarily for data storage providers, such as , so that they can - /// mark the collection, and all items it contains, as clean. After this, will return false until any items are modified or removed. - /// - /// - /// The value that the attributes were last saved. This corresponds to the . - /// - public void MarkClean(DateTime? version = null) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Marks the collection—including all items—as clean, meaning they have been persisted to + /// the underlying . + /// + /// + /// This method is intended primarily for data storage providers, such as , so that they can + /// mark the collection, and all items it contains, as clean. After this, will return false until any items are modified or removed. + /// + /// + /// The value that the attributes were last saved. This corresponds to the . + /// + public void MarkClean(DateTime? version = null) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Marks an individual as clean. - /// - /// - /// This method is intended primarily for data storage providers, such as , so that they can - /// mark an as clean. After this, will return false for - /// that item until it is modified. - /// - /// The string identifier for the . - /// - /// The value that the attribute was last modified. This denotes the associated with the specific attribute. - /// - public void MarkClean(string name, DateTime? version = null) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Marks an individual as clean. + /// + /// + /// This method is intended primarily for data storage providers, such as , so that they can + /// mark an as clean. After this, will return false for + /// that item until it is modified. + /// + /// The string identifier for the . + /// + /// The value that the attribute was last modified. This denotes the associated with the specific attribute. + /// + public void MarkClean(string name, DateTime? version = null) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: GET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets a named attribute from the Attributes dictionary. - /// - /// The string identifier for the . - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// The string value for the Attribute. - [return: NotNull] - public string GetValue(string name, bool inheritFromParent = false) => GetValue(name, "", inheritFromParent); + /*============================================================================================================================ + | METHOD: GET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets a named attribute from the Attributes dictionary. + /// + /// The string identifier for the . + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// The string value for the Attribute. + [return: NotNull] + public string GetValue(string name, bool inheritFromParent = false) => GetValue(name, "", inheritFromParent); - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling - /// of inheritance, and an optional setting for searching through derived topics for values. - /// - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// - /// Boolean indicator nothing whether to search through any of the topic's topics in - /// order to get the value. - /// - /// The string value for the Attribute. - [return: NotNullIfNotNull(nameof(defaultValue))] - public string? GetValue(string name, string? defaultValue, bool inheritFromParent = false, bool inheritFromDerived = true) - => throw new NotImplementedException(); + /// + /// Gets a named attribute from the Attributes dictionary with a specified default value, an optional setting for enabling + /// of inheritance, and an optional setting for searching through derived topics for values. + /// + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// + /// Boolean indicator nothing whether to search through any of the topic's topics in + /// order to get the value. + /// + /// The string value for the Attribute. + [return: NotNullIfNotNull(nameof(defaultValue))] + public string? GetValue(string name, string? defaultValue, bool inheritFromParent = false, bool inheritFromDerived = true) + => throw new NotImplementedException(); - /// - /// Gets a named attribute from the Attributes dictionary with a specified default value and an optional number of - /// s through whom to crawl to retrieve an inherited value. - /// - /// The string identifier for the . - /// A string value to which to fall back in the case the value is not found. - /// - /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. - /// - /// The number of recursions to perform when attempting to get the value. - /// The string value for the Attribute. - /// - /// !String.IsNullOrWhiteSpace(name) - /// - /// - /// !name.Contains(" ") - /// - /// - /// maxHops >= 0 - /// - /// - /// maxHops <= 100 - /// - [return: NotNullIfNotNull(nameof(defaultValue))] - internal string? GetValue(string name, string? defaultValue, bool inheritFromParent, int maxHops) - => throw new NotImplementedException(); + /// + /// Gets a named attribute from the Attributes dictionary with a specified default value and an optional number of + /// s through whom to crawl to retrieve an inherited value. + /// + /// The string identifier for the . + /// A string value to which to fall back in the case the value is not found. + /// + /// Boolean indicator nothing whether to search through the topic's parents in order to get the value. + /// + /// The number of recursions to perform when attempting to get the value. + /// The string value for the Attribute. + /// + /// !String.IsNullOrWhiteSpace(name) + /// + /// + /// !name.Contains(" ") + /// + /// + /// maxHops >= 0 + /// + /// + /// maxHops <= 100 + /// + [return: NotNullIfNotNull(nameof(defaultValue))] + internal string? GetValue(string name, string? defaultValue, bool inheritFromParent, int maxHops) + => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: SET VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Helper method that either adds a new object or updates the value of an existing one, - /// depending on whether that value already exists. - /// - /// - /// Minimizes the need for defensive conditions throughout the library. - /// - /// The string identifier for the AttributeValue. - /// The text value for the AttributeValue. - /// - /// Specified whether the value should be marked as . By default, it will be marked as - /// dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// The value that the attribute was last modified. This is intended exclusively for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// Determines if the attribute originated from an extended attributes data store. - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - public void SetValue( - string key, - string? value, - bool? isDirty = null, - DateTime? version = null, - bool? isExtendedAttribute = null - ) - => SetValue(key, value, isDirty, true, version, isExtendedAttribute); + /*============================================================================================================================ + | METHOD: SET VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Helper method that either adds a new object or updates the value of an existing one, + /// depending on whether that value already exists. + /// + /// + /// Minimizes the need for defensive conditions throughout the library. + /// + /// The string identifier for the AttributeValue. + /// The text value for the AttributeValue. + /// + /// Specified whether the value should be marked as . By default, it will be marked as + /// dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// The value that the attribute was last modified. This is intended exclusively for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// Determines if the attribute originated from an extended attributes data store. + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + public void SetValue( + string key, + string? value, + bool? isDirty = null, + DateTime? version = null, + bool? isExtendedAttribute = null + ) + => SetValue(key, value, isDirty, true, version, isExtendedAttribute); - /// - /// Protected helper method that either adds a new object or updates the value of an existing - /// one, depending on whether that value already exists. - /// - /// - /// When this overload is called, no attempt will be made to route the call through corresponding properties, if - /// available. As such, this is intended specifically to be called by internal properties as a means of avoiding a - /// feedback loop. - /// - /// The string identifier for the AttributeValue. - /// The text value for the AttributeValue. - /// - /// Specified whether the value should be marked as . By default, it will be marked as - /// dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// Instructs the underlying code to call corresponding properties, if available, to ensure business logic is enforced. - /// This should be set to false if setting attributes from internal properties in order to avoid an infinite loop. - /// - /// - /// The value that the attribute was last modified. This is intended exclusively for use when - /// populating the topic graph from a persistent data store as a means of indicating the current version for each - /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. - /// - /// Determines if the attribute originated from an extended attributes data store. - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - internal void SetValue( - string key, - string? value, - bool? isDirty, - bool enforceBusinessLogic, - DateTime? version = null, - bool? isExtendedAttribute = null - ) => throw new NotImplementedException(); + /// + /// Protected helper method that either adds a new object or updates the value of an existing + /// one, depending on whether that value already exists. + /// + /// + /// When this overload is called, no attempt will be made to route the call through corresponding properties, if + /// available. As such, this is intended specifically to be called by internal properties as a means of avoiding a + /// feedback loop. + /// + /// The string identifier for the AttributeValue. + /// The text value for the AttributeValue. + /// + /// Specified whether the value should be marked as . By default, it will be marked as + /// dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// Instructs the underlying code to call corresponding properties, if available, to ensure business logic is enforced. + /// This should be set to false if setting attributes from internal properties in order to avoid an infinite loop. + /// + /// + /// The value that the attribute was last modified. This is intended exclusively for use when + /// populating the topic graph from a persistent data store as a means of indicating the current version for each + /// attribute. This is used when e.g. importing values to determine if the existing value is newer than the source value. + /// + /// Determines if the attribute originated from an extended attributes data store. + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + internal void SetValue( + string key, + string? value, + bool? isDirty, + bool enforceBusinessLogic, + DateTime? version = null, + bool? isExtendedAttribute = null + ) => throw new NotImplementedException(); - /*========================================================================================================================== - | OVERRIDE: INSERT ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to insert a new into the collection, to ensure that local - /// business logic is enforced. - /// - /// - /// - /// If a settable property is available corresponding to the , the call should be routed - /// through that to ensure local business logic is enforced. This is determined by looking for the "__" prefix, which is - /// set by the 's - /// enforceBusinessLogic parameter. To avoid an infinite loop, internal setters must call this overload. - /// - /// - /// Compared to the base implementation, will throw a specific error if a duplicate key - /// is inserted. This conveniently provides the name of the so it's clear what key is - /// being duplicated. - /// - /// - /// The location that the should be set. - /// The object which is being inserted. - /// - /// An AttributeValue with the Key '{item.Key}' already exists. The Value of the existing item is "{this[item.Key].Value}; - /// the new item's Value is '{item.Value}'. These AttributeValues are associated with the Topic '{GetUniqueKey()}'." - /// - protected override void InsertItem(int index, AttributeValue item) => throw new NotImplementedException(); + /*============================================================================================================================ + | OVERRIDE: INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to insert a new into the collection, to ensure that local + /// business logic is enforced. + /// + /// + /// + /// If a settable property is available corresponding to the , the call should be routed + /// through that to ensure local business logic is enforced. This is determined by looking for the "__" prefix, which is + /// set by the 's + /// enforceBusinessLogic parameter. To avoid an infinite loop, internal setters must call this overload. + /// + /// + /// Compared to the base implementation, will throw a specific error if a duplicate key + /// is inserted. This conveniently provides the name of the so it's clear what key is + /// being duplicated. + /// + /// + /// The location that the should be set. + /// The object which is being inserted. + /// + /// An AttributeValue with the Key '{item.Key}' already exists. The Value of the existing item is "{this[item.Key].Value}; + /// the new item's Value is '{item.Value}'. These AttributeValues are associated with the Topic '{GetUniqueKey()}'." + /// + protected override void InsertItem(int index, AttributeValue item) => throw new NotImplementedException(); - /*========================================================================================================================== - | OVERRIDE: SET ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to update an in the collection, to ensure that local business - /// logic is enforced. - /// - /// - /// If a settable property is available corresponding to the , the call should be routed - /// through that to ensure local business logic is enforced. This is determined by looking for the "__" prefix, which is - /// set by the 's - /// enforceBusinessLogic parameter. To avoid an infinite loop, internal setters must call this overload. - /// - /// The location that the should be set. - /// The object which is being inserted. - protected override void SetItem(int index, AttributeValue item) => throw new NotImplementedException(); + /*============================================================================================================================ + | OVERRIDE: SET ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to update an in the collection, to ensure that local business + /// logic is enforced. + /// + /// + /// If a settable property is available corresponding to the , the call should be routed + /// through that to ensure local business logic is enforced. This is determined by looking for the "__" prefix, which is + /// set by the 's + /// enforceBusinessLogic parameter. To avoid an infinite loop, internal setters must call this overload. + /// + /// The location that the should be set. + /// The object which is being inserted. + protected override void SetItem(int index, AttributeValue item) => throw new NotImplementedException(); - /*========================================================================================================================== - | OVERRIDE: REMOVE ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Intercepts all attempts to remove an from the collection, to ensure that it is - /// appropriately marked as . - /// - /// - /// When an is removed, will return true—even if no remaining - /// s are marked as . - /// - protected override void RemoveItem(int index) => throw new NotImplementedException(); + /*============================================================================================================================ + | OVERRIDE: REMOVE ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Intercepts all attempts to remove an from the collection, to ensure that it is + /// appropriately marked as . + /// + /// + /// When an is removed, will return true—even if no remaining + /// s are marked as . + /// + protected override void RemoveItem(int index) => throw new NotImplementedException(); - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Method must be overridden for the EntityCollection to extract the keys from the items. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - protected override string GetKeyForItem(AttributeValue item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Key; - } + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Method must be overridden for the EntityCollection to extract the keys from the items. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + protected override string GetKeyForItem(AttributeValue item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Key; + } - } //Class -} //Namespace +} //Class #pragma warning restore IDE0060 // Remove unused parameter \ No newline at end of file diff --git a/OnTopic/Obsolete/Collections/NamedTopicCollection.cs b/OnTopic/Obsolete/Collections/NamedTopicCollection.cs index faa93624..62ff941c 100644 --- a/OnTopic/Obsolete/Collections/NamedTopicCollection.cs +++ b/OnTopic/Obsolete/Collections/NamedTopicCollection.cs @@ -7,91 +7,90 @@ using OnTopic.Associations; using OnTopic.Collections.Specialized; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: NAMED TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a named version of the , suitable for use in +/// , or other derivatives of . +/// +[ExcludeFromCodeCoverage] +[Obsolete( + $"Migrated to {nameof(KeyValuesPair>)} as part of new {nameof(TopicRelationshipMultiMap)} type.", + true +)] +public class NamedTopicCollection: KeyedTopicCollection { /*============================================================================================================================ - | CLASS: NAMED TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a named version of the , suitable for use in - /// , or other derivatives of . + /// Initializes a new instance of the class. /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"Migrated to {nameof(KeyValuesPair>)} as part of new {nameof(TopicRelationshipMultiMap)} type.", - true - )] - public class NamedTopicCollection: KeyedTopicCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// Provides a name for the collection, used to identify different collections. - /// Optionally seeds the collection with an optional list of topic references. - public NamedTopicCollection(string name = "", IEnumerable? topics = null) : base() { - Name = name; - if (topics is not null) { - CopyTo(topics.ToArray(), 0); - } + /// Provides a name for the collection, used to identify different collections. + /// Optionally seeds the collection with an optional list of topic references. + public NamedTopicCollection(string name = "", IEnumerable? topics = null) : base() { + Name = name; + if (topics is not null) { + CopyTo([.. topics], 0); } + } - /*========================================================================================================================== - | IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines if the collection has been modified. This value is set to true any time a new item is inserted or - /// removed from the collection. - /// - public bool IsDirty { get; set; } + /*============================================================================================================================ + | IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines if the collection has been modified. This value is set to true any time a new item is inserted or + /// removed from the collection. + /// + public bool IsDirty { get; set; } - /*========================================================================================================================== - | INSERT ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// When inserting an item, determine if it will change the collection; if it will, mark the collection as . - /// - protected new void InsertItem(int index, Topic topic) => throw new NotImplementedException(); + /*============================================================================================================================ + | INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// When inserting an item, determine if it will change the collection; if it will, mark the collection as . + /// + protected new void InsertItem(int index, Topic topic) => throw new NotImplementedException(); - /*========================================================================================================================== - | SET ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// When updating an existing item, determine if it will change the collection; if it will, mark the collection as . - /// - protected new void SetItem(int index, Topic topic) => throw new NotImplementedException(); + /*============================================================================================================================ + | SET ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// When updating an existing item, determine if it will change the collection; if it will, mark the collection as . + /// + protected new void SetItem(int index, Topic topic) => throw new NotImplementedException(); - /*========================================================================================================================== - | REMOVE ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// When removing an item from the collection, mark the collection as . - /// - protected override void RemoveItem(int index) => throw new NotImplementedException(); + /*============================================================================================================================ + | REMOVE ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// When removing an item from the collection, mark the collection as . + /// + protected override void RemoveItem(int index) => throw new NotImplementedException(); - /*========================================================================================================================== - | CLEAR ITEMS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// When clearing the collection, mark the collection as if it had items in it. - /// - protected override void ClearItems() => throw new NotImplementedException(); + /*============================================================================================================================ + | CLEAR ITEMS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// When clearing the collection, mark the collection as if it had items in it. + /// + protected override void ClearItems() => throw new NotImplementedException(); - /*========================================================================================================================== - | PROPERTY: NAME - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides an optional name for the collection. - /// - /// - /// The Name property is optional, and primary intended to differentiate multiple - /// instances being referenced in a single collection, such as the . - /// - public string Name { get; } + /*============================================================================================================================ + | PROPERTY: NAME + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides an optional name for the collection. + /// + /// + /// The Name property is optional, and primary intended to differentiate multiple + /// instances being referenced in a single collection, such as the . + /// + public string Name { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Collections/ReadOnlyTopicCollection{T}.cs b/OnTopic/Obsolete/Collections/ReadOnlyTopicCollection{T}.cs index 3bda09d1..b089ed15 100644 --- a/OnTopic/Obsolete/Collections/ReadOnlyTopicCollection{T}.cs +++ b/OnTopic/Obsolete/Collections/ReadOnlyTopicCollection{T}.cs @@ -5,61 +5,60 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: READ ONLY TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a read-only collection of topics. +/// +[ExcludeFromCodeCoverage] +[Obsolete( + $"The {nameof(ReadOnlyTopicCollection )} has been renamed to {nameof(ReadOnlyKeyedTopicCollection)}", + true +)] +public class ReadOnlyTopicCollection : ReadOnlyCollection where T : Topic { /*============================================================================================================================ - | CLASS: READ ONLY TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a read-only collection of topics. + /// Establishes a new based on an existing . /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The {nameof(ReadOnlyTopicCollection )} has been renamed to {nameof(ReadOnlyKeyedTopicCollection)}", - true - )] - public class ReadOnlyTopicCollection : ReadOnlyCollection where T : Topic { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// The underlying . - public ReadOnlyTopicCollection(IList innerCollection) : base(innerCollection) { - throw new NotImplementedException(); - } + /// The underlying . + public ReadOnlyTopicCollection(IList innerCollection) : base(innerCollection) { + throw new NotImplementedException(); + } - /*========================================================================================================================== - | METHOD: GET TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a by key. - /// - public T? GetTopic(string key) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: GET TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a by key. + /// + public T? GetTopic(string key) => throw new NotImplementedException(); - /*========================================================================================================================== - | FACTORY METHOD: FROM LIST - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes a new based on an existing . - /// - /// - /// The will be converted to a . - /// - /// The underlying . - [Obsolete("This is effectively satisfied by the related overload, and will be removed in OnTopic 5.0.0.", false)] - public ReadOnlyTopicCollection FromList(IList innerCollection) => throw new NotImplementedException(); + /*============================================================================================================================ + | FACTORY METHOD: FROM LIST + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes a new based on an existing . + /// + /// + /// The will be converted to a . + /// + /// The underlying . + [Obsolete("This is effectively satisfied by the related overload, and will be removed in OnTopic 5.0.0.", false)] + public ReadOnlyTopicCollection FromList(IList innerCollection) => throw new NotImplementedException(); - /*========================================================================================================================== - | INDEXER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves an by key. - /// - /// The topic key. - public Topic? this[string key] => null; + /*============================================================================================================================ + | INDEXER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves an by key. + /// + /// The topic key. + public Topic? this[string key] => null; - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Collections/RelatedTopicCollection.cs b/OnTopic/Obsolete/Collections/RelatedTopicCollection.cs index daf3a591..1567878d 100644 --- a/OnTopic/Obsolete/Collections/RelatedTopicCollection.cs +++ b/OnTopic/Obsolete/Collections/RelatedTopicCollection.cs @@ -8,191 +8,190 @@ #pragma warning disable IDE0060 // Remove unused parameter -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: RELATED TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a simple interface for accessing collections of topic collections. +/// +[ExcludeFromCodeCoverage] +[Obsolete($"{nameof(RelatedTopicCollection)} has been migrated to the new {nameof(TopicRelationshipMultiMap)}", true)] +public class RelatedTopicCollection : KeyedCollection { /*============================================================================================================================ - | CLASS: RELATED TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a simple interface for accessing collections of topic collections. + /// Initializes a new instance of the . /// - [ExcludeFromCodeCoverage] - [Obsolete($"{nameof(RelatedTopicCollection)} has been migrated to the new {nameof(TopicRelationshipMultiMap)}", true)] - public class RelatedTopicCollection : KeyedCollection { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the . - /// - /// - /// The constructor requires a reference to a instance, which the related topics are to be associated - /// with. This will be used when setting incoming relationships. In addition, a may - /// be set as if it is specifically intended to track incoming relationships; if this is not - /// set, then it will not allow incoming relationships to be set via the internal - /// overload. - /// - public RelatedTopicCollection(Topic parent, bool isIncoming = false) : base(StringComparer.OrdinalIgnoreCase) { - } - - /*========================================================================================================================== - | PROPERTY: KEYS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of relationship key available. - /// - /// - /// Returns an enumerable list of relationship keys. - /// - public ReadOnlyCollection Keys => new(Items.Select(t => t.Name).ToList()); - - /*========================================================================================================================== - | METHOD: GET ALL TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of all related objects, independent of relationship key. - /// - /// - /// Returns an enumerable list of objects. - /// - public ReadOnlyTopicCollection GetAllTopics() => throw new NotImplementedException(); - - /// - /// Retrieves a list of all related objects, independent of relationship key, filtered by content - /// type. - /// - /// - /// Returns an enumerable list of objects. - /// - public ReadOnlyTopicCollection GetAllTopics(string contentType) => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: GET TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a list of objects grouped by a specific relationship key. - /// - /// - /// Returns a reference to the underlying ; modifications to this collection will modify - /// the 's . As such, this should be used with care. - /// - /// The key of the relationship to be returned. - public NamedTopicCollection GetTopics(string relationshipKey) => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: CLEAR TOPICS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes all objects grouped by a specific relationship key. - /// - /// The key of the relationship to be cleared. - public void ClearTopics(string relationshipKey) => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: REMOVE TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Removes a specific object associated with a specific relationship key. - /// - /// The key of the relationship. - /// The key of the topic to be removed. - /// - /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. - /// - /// - /// Returns true if the is removed; returns false if either the relationship key or the - /// cannot be found. - /// - public bool RemoveTopic(string relationshipKey, string topicKey, bool isIncoming = false) => - throw new NotImplementedException(); - - /// - /// Removes a specific object associated with a specific relationship key. - /// - /// The key of the relationship. - /// The topic to be removed. - /// - /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. - /// - /// - /// Returns true if the is removed; returns false if either the relationship key or the - /// cannot be found. - /// - public bool RemoveTopic(string relationshipKey, Topic topic, bool isIncoming = false) => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: SET TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Ensures that a is associated with the specified relationship key. - /// - /// - /// If a relationship by a given key is not currently established, it will automatically be created. - /// - /// The key of the relationship. - /// The topic to be added, if it doesn't already exist. - public void SetTopic(string relationshipKey, Topic topic) => SetTopic(relationshipKey, topic, false); - - /// - /// Ensures that an incoming is associated with the specified relationship key. - /// - /// - /// If a relationship by a given key is not currently established, it will automatically be c. - /// - /// The key of the relationship. - /// The topic to be added, if it doesn't already exist. - /// - /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. - /// - /// - /// Optionally forces the collection to a state, assuming the topic was set. - /// - public void SetTopic(string relationshipKey, Topic topic, bool isIncoming, bool? isDirty = null) => - throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Evaluates each of the child s to determine if any of them are set to . If they are, returns true. - /// - public bool IsDirty() => Items.Any(r => r.IsDirty); - - /*========================================================================================================================== - | OVERRIDE: INSERT ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// Fires any time a is added to the collection. - /// - /// Compared to the base implementation, will throw a specific error if a duplicate key is - /// inserted. This conveniently provides the name of the , so it's clear what key is - /// being duplicated. - /// - /// The zero-based index at which should be inserted. - /// The instance to insert. - /// - /// A NamedTopicCollection with the Name '{item.Name}' already exists in this RelatedTopicCollection. The existing key is - /// {this[item.Name].Name}'; the new item's is '{item.Name}'. This collection is associated with the '{GetUniqueKey()}' - /// Topic. - /// - protected override void InsertItem(int index, NamedTopicCollection item) => throw new NotImplementedException(); - - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a method for the to retrieve the key from the underlying - /// collection of objects, in this case s. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - protected override string GetKeyForItem(NamedTopicCollection item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Name; - } - - } //Class -} //Namespace + /// + /// The constructor requires a reference to a instance, which the related topics are to be associated + /// with. This will be used when setting incoming relationships. In addition, a may + /// be set as if it is specifically intended to track incoming relationships; if this is not + /// set, then it will not allow incoming relationships to be set via the internal + /// overload. + /// + public RelatedTopicCollection(Topic parent, bool isIncoming = false) : base(StringComparer.OrdinalIgnoreCase) { + } + + /*============================================================================================================================ + | PROPERTY: KEYS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of relationship key available. + /// + /// + /// Returns an enumerable list of relationship keys. + /// + public ReadOnlyCollection Keys => new([.. Items.Select(t => t.Name)]); + + /*============================================================================================================================ + | METHOD: GET ALL TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of all related objects, independent of relationship key. + /// + /// + /// Returns an enumerable list of objects. + /// + public ReadOnlyTopicCollection GetAllTopics() => throw new NotImplementedException(); + + /// + /// Retrieves a list of all related objects, independent of relationship key, filtered by content + /// type. + /// + /// + /// Returns an enumerable list of objects. + /// + public ReadOnlyTopicCollection GetAllTopics(string contentType) => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: GET TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a list of objects grouped by a specific relationship key. + /// + /// + /// Returns a reference to the underlying ; modifications to this collection will modify + /// the 's . As such, this should be used with care. + /// + /// The key of the relationship to be returned. + public NamedTopicCollection GetTopics(string relationshipKey) => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: CLEAR TOPICS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes all objects grouped by a specific relationship key. + /// + /// The key of the relationship to be cleared. + public void ClearTopics(string relationshipKey) => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: REMOVE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Removes a specific object associated with a specific relationship key. + /// + /// The key of the relationship. + /// The key of the topic to be removed. + /// + /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. + /// + /// + /// Returns true if the is removed; returns false if either the relationship key or the + /// cannot be found. + /// + public bool RemoveTopic(string relationshipKey, string topicKey, bool isIncoming = false) => + throw new NotImplementedException(); + + /// + /// Removes a specific object associated with a specific relationship key. + /// + /// The key of the relationship. + /// The topic to be removed. + /// + /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. + /// + /// + /// Returns true if the is removed; returns false if either the relationship key or the + /// cannot be found. + /// + public bool RemoveTopic(string relationshipKey, Topic topic, bool isIncoming = false) => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: SET TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Ensures that a is associated with the specified relationship key. + /// + /// + /// If a relationship by a given key is not currently established, it will automatically be created. + /// + /// The key of the relationship. + /// The topic to be added, if it doesn't already exist. + public void SetTopic(string relationshipKey, Topic topic) => SetTopic(relationshipKey, topic, false); + + /// + /// Ensures that an incoming is associated with the specified relationship key. + /// + /// + /// If a relationship by a given key is not currently established, it will automatically be c. + /// + /// The key of the relationship. + /// The topic to be added, if it doesn't already exist. + /// + /// Notes that this is setting an internal relationship, and thus shouldn't set the reciprocal relationship. + /// + /// + /// Optionally forces the collection to a state, assuming the topic was set. + /// + public void SetTopic(string relationshipKey, Topic topic, bool isIncoming, bool? isDirty = null) => + throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Evaluates each of the child s to determine if any of them are set to . If they are, returns true. + /// + public bool IsDirty() => Items.Any(r => r.IsDirty); + + /*============================================================================================================================ + | OVERRIDE: INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// Fires any time a is added to the collection. + /// + /// Compared to the base implementation, will throw a specific error if a duplicate key is + /// inserted. This conveniently provides the name of the , so it's clear what key is + /// being duplicated. + /// + /// The zero-based index at which should be inserted. + /// The instance to insert. + /// + /// A NamedTopicCollection with the Name '{item.Name}' already exists in this RelatedTopicCollection. The existing key is + /// {this[item.Name].Name}'; the new item's is '{item.Name}'. This collection is associated with the '{GetUniqueKey()}' + /// Topic. + /// + protected override void InsertItem(int index, NamedTopicCollection item) => throw new NotImplementedException(); + + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a method for the to retrieve the key from the underlying + /// collection of objects, in this case s. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + protected override string GetKeyForItem(NamedTopicCollection item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Name; + } + +} //Class #pragma warning restore IDE0060 // Remove unused parameter \ No newline at end of file diff --git a/OnTopic/Obsolete/Collections/TopicCollection{T}.cs b/OnTopic/Obsolete/Collections/TopicCollection{T}.cs index b097cb01..1fb4bb93 100644 --- a/OnTopic/Obsolete/Collections/TopicCollection{T}.cs +++ b/OnTopic/Obsolete/Collections/TopicCollection{T}.cs @@ -5,93 +5,92 @@ \=============================================================================================================================*/ using System.Collections.ObjectModel; -namespace OnTopic.Collections { +namespace OnTopic.Collections; + +/*============================================================================================================================== +| CLASS: TOPIC COLLECTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a strongly-typed collection of instances, or a derived type. +/// +[ExcludeFromCodeCoverage] +[Obsolete($"The {nameof(TopicCollection)} class has been renamed to {nameof(KeyedTopicCollection)}.", true)] +public class TopicCollection: KeyedCollection, IEnumerable where T : Topic { /*============================================================================================================================ - | CLASS: TOPIC COLLECTION + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides a strongly-typed collection of instances, or a derived type. + /// Initializes a new instance of the class. /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(TopicCollection)} class has been renamed to {nameof(KeyedTopicCollection)}.", true)] - public class TopicCollection: KeyedCollection, IEnumerable where T : Topic { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// Seeds the collection with an optional list of topic references. - public TopicCollection(IEnumerable? topics = null) : base(StringComparer.OrdinalIgnoreCase) { - if (topics is not null) { - foreach (var topic in topics) { - Add(topic); - } + /// Seeds the collection with an optional list of topic references. + public TopicCollection(IEnumerable? topics = null) : base(StringComparer.OrdinalIgnoreCase) { + if (topics is not null) { + foreach (var topic in topics) { + Add(topic); } } + } - /*========================================================================================================================== - | METHOD: GET TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a by key. - /// - public T? GetTopic(string key) => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: GET TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a by key. + /// + public T? GetTopic(string key) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: AS READ ONLY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a read-only version of this . - /// - public ReadOnlyTopicCollection AsReadOnly() => throw new NotImplementedException(); + /*============================================================================================================================ + | METHOD: AS READ ONLY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a read-only version of this . + /// + public ReadOnlyTopicCollection AsReadOnly() => throw new NotImplementedException(); - /*========================================================================================================================== - | OVERRIDE: INSERT ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// Fires any time a is added to the collection. - /// - /// Compared to the base implementation, will throw a specific error if a duplicate key is - /// inserted. This conveniently provides the name of the 's , so - /// it's clear what key is being duplicated. - /// - /// The zero-based index at which should be inserted. - /// The instance to insert. - /// - /// A {typeof(T).Name} with the Key '{item.Key}' already exists. The UniqueKey of the existing {typeof(T).Name} is - /// '{GetUniqueKey()}'; the new item's is '{item.GetUniqueKey()}'. - /// - protected override void InsertItem(int index, T item) => throw new NotImplementedException(); + /*============================================================================================================================ + | OVERRIDE: INSERT ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// Fires any time a is added to the collection. + /// + /// Compared to the base implementation, will throw a specific error if a duplicate key is + /// inserted. This conveniently provides the name of the 's , so + /// it's clear what key is being duplicated. + /// + /// The zero-based index at which should be inserted. + /// The instance to insert. + /// + /// A {typeof(T).Name} with the Key '{item.Key}' already exists. The UniqueKey of the existing {typeof(T).Name} is + /// '{GetUniqueKey()}'; the new item's is '{item.GetUniqueKey()}'. + /// + protected override void InsertItem(int index, T item) => throw new NotImplementedException(); - /*========================================================================================================================== - | METHOD: CHANGE KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Changes the key associated with a topic to maintain referential integrity. - /// - /// - /// By default, doesn't permit mutable keys; this mitigates that issue by - /// allowing the collection's lookup dictionary to be updated whenever the key is updated in the corresponding topic - /// object. - /// - /// The topic object for which the should be changed. - /// The string value for the new key. - internal void ChangeKey(T topic, string newKey) => base.ChangeItemKey(topic, newKey); + /*============================================================================================================================ + | METHOD: CHANGE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Changes the key associated with a topic to maintain referential integrity. + /// + /// + /// By default, doesn't permit mutable keys; this mitigates that issue by + /// allowing the collection's lookup dictionary to be updated whenever the key is updated in the corresponding topic + /// object. + /// + /// The topic object for which the should be changed. + /// The string value for the new key. + internal void ChangeKey(T topic, string newKey) => base.ChangeItemKey(topic, newKey); - /*========================================================================================================================== - | OVERRIDE: GET KEY FOR ITEM - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Method must be overridden for the EntityCollection to extract the keys from the items. - /// - /// The object from which to extract the key. - /// The key for the specified collection item. - protected override string GetKeyForItem(T item) { - Contract.Requires(item, "The item must be available in order to derive its key."); - return item.Key; - } + /*============================================================================================================================ + | OVERRIDE: GET KEY FOR ITEM + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Method must be overridden for the EntityCollection to extract the keys from the items. + /// + /// The object from which to extract the key. + /// The key for the specified collection item. + protected override string GetKeyForItem(T item) { + Contract.Requires(item, "The item must be available in order to derive its key."); + return item.Key; + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Mapping/Annotations/FollowAttribute.cs b/OnTopic/Obsolete/Mapping/Annotations/FollowAttribute.cs index fc1229e4..ab991129 100644 --- a/OnTopic/Obsolete/Mapping/Annotations/FollowAttribute.cs +++ b/OnTopic/Obsolete/Mapping/Annotations/FollowAttribute.cs @@ -4,35 +4,34 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: FOLLOW +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +[ExcludeFromCodeCoverage] +[AttributeUsage(AttributeTargets.Property)] +[Obsolete($"The {nameof(FollowAttribute)} has been renamed to {nameof(IncludeAttribute)}.", true)] +public sealed class FollowAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: FOLLOW + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [AttributeUsage(AttributeTargets.Property)] - [Obsolete($"The {nameof(FollowAttribute)} has been renamed to {nameof(IncludeAttribute)}.", true)] - public sealed class FollowAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the by providing an . - /// - /// The specific relationships that should be crawled. - public FollowAttribute(Relationships relationships) { - Relationships = relationships; - } + /// + /// Annotates a property with the by providing an . + /// + /// The specific relationships that should be crawled. + public FollowAttribute(Relationships relationships) { + Relationships = relationships; + } - /*========================================================================================================================== - | PROPERTY: RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the type(s) of relationships that should be recursed over. - /// - public Relationships Relationships { get; } + /*============================================================================================================================ + | PROPERTY: RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the type(s) of relationships that should be recursed over. + /// + public Relationships Relationships { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Mapping/Annotations/RelationshipAttribute.cs b/OnTopic/Obsolete/Mapping/Annotations/RelationshipAttribute.cs index d64839c3..869a470b 100644 --- a/OnTopic/Obsolete/Mapping/Annotations/RelationshipAttribute.cs +++ b/OnTopic/Obsolete/Mapping/Annotations/RelationshipAttribute.cs @@ -4,52 +4,52 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ATTRIBUTE: RELATIONSHIP +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +[ExcludeFromCodeCoverage] +[AttributeUsage(AttributeTargets.Property)] +[Obsolete($"The {nameof(RelationshipAttribute)} has been renamed to {nameof(CollectionAttribute)}.", true)] +public sealed class RelationshipAttribute : Attribute { /*============================================================================================================================ - | ATTRIBUTE: RELATIONSHIP + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - [ExcludeFromCodeCoverage] - [AttributeUsage(AttributeTargets.Property)] - [Obsolete($"The {nameof(RelationshipAttribute)} has been renamed to {nameof(CollectionAttribute)}.", true)] - public sealed class RelationshipAttribute : Attribute { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Annotates a property with the by providing an . - /// - /// The key value of the collection associated with the current property. - public RelationshipAttribute(string key) { - TopicFactory.ValidateKey(key, false); - Key = key; - } + /// + /// Annotates a property with the by providing an . + /// + /// The key value of the collection associated with the current property. + public RelationshipAttribute(string key) { + TopicFactory.ValidateKey(key, false); + Key = key; + } - /// - /// Annotates a property with the by providing the . - /// - /// Optional. The type of collection the collection is associated with. - public RelationshipAttribute(RelationshipType type = RelationshipType.Any) { - Type = type; - } + /// + /// Annotates a property with the by providing the . + /// + /// Optional. The type of collection the collection is associated with. + public RelationshipAttribute(RelationshipType type = RelationshipType.Any) { + Type = type; + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the collection key. - /// - public string? Key { get; } + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the collection key. + /// + public string? Key { get; } - /*========================================================================================================================== - | PROPERTY: TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the value of the . - /// - public RelationshipType Type { get; set; } + /*============================================================================================================================ + | PROPERTY: TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the value of the . + /// + [SuppressMessage("Design", "CA1019:Define accessors for attribute arguments", Justification = "Retained for symmetry with CollectionAttribute; this class is marked [Obsolete(error: true)] and cannot be used in compiled code.")] + public RelationshipType Type { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Mapping/Annotations/RelationshipType.cs b/OnTopic/Obsolete/Mapping/Annotations/RelationshipType.cs index b3bd88cd..84be74a9 100644 --- a/OnTopic/Obsolete/Mapping/Annotations/RelationshipType.cs +++ b/OnTopic/Obsolete/Mapping/Annotations/RelationshipType.cs @@ -4,25 +4,24 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; - /*============================================================================================================================ - | ENUM: RELATIONSHIP TYPE - \---------------------------------------------------------------------------------------------------------------------------*/ - /// - [Obsolete($"{nameof(RelationshipType)} has been renamed to {nameof(CollectionType)}", true)] - public enum RelationshipType { +/*============================================================================================================================== +| ENUM: RELATIONSHIP TYPE +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +[Obsolete($"{nameof(RelationshipType)} has been renamed to {nameof(CollectionType)}", true)] +public enum RelationshipType { - #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - Any = 0, - Children = 1, - Relationship = 2, - IncomingRelationship = 3, - NestedTopics = 4, - MappedCollection = 5 + Any = 0, + Children = 1, + Relationship = 2, + IncomingRelationship = 3, + NestedTopics = 4, + MappedCollection = 5 - #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member - } //Enum -} //Namespace \ No newline at end of file +} //Enum \ No newline at end of file diff --git a/OnTopic/Obsolete/Mapping/Annotations/Relationships.cs b/OnTopic/Obsolete/Mapping/Annotations/Relationships.cs index 464ca53b..e90f49d5 100644 --- a/OnTopic/Obsolete/Mapping/Annotations/Relationships.cs +++ b/OnTopic/Obsolete/Mapping/Annotations/Relationships.cs @@ -4,23 +4,22 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Mapping.Annotations { +namespace OnTopic.Mapping.Annotations; + +/*============================================================================================================================== +| ENUM: RELATIONSHIPS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +[Flags] +[Obsolete($"The {nameof(Relationships)} enum has been renamed to {nameof(AssociationTypes)}.", true)] +public enum Relationships { /*============================================================================================================================ - | ENUM: RELATIONSHIPS + | NONE \---------------------------------------------------------------------------------------------------------------------------*/ - /// - [Flags] - [Obsolete($"The {nameof(Relationships)} enum has been renamed to {nameof(AssociationTypes)}.", true)] - public enum Relationships { - - /*========================================================================================================================== - | NONE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Do not follow any associations. - /// - None = 0 + /// + /// Do not follow any associations. + /// + None = 0 - } //Enum -} //Namespace \ No newline at end of file +} //Enum \ No newline at end of file diff --git a/OnTopic/Obsolete/Metadata/Attributes/AttributeTypeDescriptor.cs b/OnTopic/Obsolete/Metadata/Attributes/AttributeTypeDescriptor.cs index 8ee9e98d..bcb4a810 100644 --- a/OnTopic/Obsolete/Metadata/Attributes/AttributeTypeDescriptor.cs +++ b/OnTopic/Obsolete/Metadata/Attributes/AttributeTypeDescriptor.cs @@ -4,43 +4,42 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Metadata.AttributeTypes { +namespace OnTopic.Metadata.AttributeTypes; + +/*============================================================================================================================== +| CLASS: ATTRIBUTE TYPE (DESCRIPTOR) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a base class for attribute type classes. +/// +/// +/// In the OnTopic Editor, every attribute is assigned a type, which represents how the data should be presented in the +/// editor, what constraints those data have, and how those data should be stored in the data source. In Version 4.0.0 and +/// above, these attribute types are described by their own s, which offer a strongly +/// typed representation of those properties. This class provides a base for those representations. +/// +[ExcludeFromCodeCoverage] +[Obsolete( + $"The {nameof(AttributeTypeDescriptor)} class is obsolete. Derive from {nameof(AttributeDescriptor)} instead.", + true +)] +public abstract class AttributeTypeDescriptor : AttributeDescriptor { /*============================================================================================================================ - | CLASS: ATTRIBUTE TYPE (DESCRIPTOR) + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a base class for attribute type classes. - /// - /// - /// In the OnTopic Editor, every attribute is assigned a type, which represents how the data should be presented in the - /// editor, what constraints those data have, and how those data should be stored in the data source. In Version 4.0.0 and - /// above, these attribute types are described by their own s, which offer a strongly - /// typed representation of those properties. This class provides a base for those representations. - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The {nameof(AttributeTypeDescriptor)} class is obsolete. Derive from {nameof(AttributeDescriptor)} instead.", - true - )] - public abstract class AttributeTypeDescriptor : AttributeDescriptor { - - /*========================================================================================================================== - | CONSTRUCTOR - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - protected AttributeTypeDescriptor( - string key, - string contentType, - Topic parent, - int id = -1 - ) : base( - key, - contentType, - parent, - id - ) { - } + /// + protected AttributeTypeDescriptor( + string key, + string contentType, + Topic parent, + int id = -1 + ) : base( + key, + contentType, + parent, + id + ) { + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Repositories/DeleteEventArgs.cs b/OnTopic/Obsolete/Repositories/DeleteEventArgs.cs index 87d64a8e..6ad527b8 100644 --- a/OnTopic/Obsolete/Repositories/DeleteEventArgs.cs +++ b/OnTopic/Obsolete/Repositories/DeleteEventArgs.cs @@ -4,36 +4,35 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: DELETE EVENT ARGS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The DeleteEventArgs class defines an event argument type specific to deletion events +/// +[ExcludeFromCodeCoverage] +[Obsolete($"The {nameof(DeleteEventArgs)} has been renamed to {nameof(TopicEventArgs)}", true)] +public class DeleteEventArgs : EventArgs { /*============================================================================================================================ - | CLASS: DELETE EVENT ARGS + | CONSTRUCTOR: TAXONOMY DELETE EVENT ARGS \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The DeleteEventArgs class defines an event argument type specific to deletion events + /// Initializes a new instance of the class. /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(DeleteEventArgs)} has been renamed to {nameof(TopicEventArgs)}", true)] - public class DeleteEventArgs : EventArgs { - - /*========================================================================================================================== - | CONSTRUCTOR: TAXONOMY DELETE EVENT ARGS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// The topic. - public DeleteEventArgs(Topic topic) : base() { - Topic = topic; - } + /// The topic. + public DeleteEventArgs(Topic topic) : base() { + Topic = topic; + } - /*========================================================================================================================== - | PROPERTY: TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Getter that returns the Topic object associated with the event - /// - public Topic Topic { get; set; } + /*============================================================================================================================ + | PROPERTY: TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Getter that returns the Topic object associated with the event + /// + public Topic Topic { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Repositories/MoveEventArgs.cs b/OnTopic/Obsolete/Repositories/MoveEventArgs.cs index c4665f40..a5262b3a 100644 --- a/OnTopic/Obsolete/Repositories/MoveEventArgs.cs +++ b/OnTopic/Obsolete/Repositories/MoveEventArgs.cs @@ -4,64 +4,63 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: MOVE EVENT ARGS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The MoveEventArgs object defines an event argument type specific to move events. +/// +/// +/// Allows tracking of the source and destination topics. +/// +[ExcludeFromCodeCoverage] +[Obsolete($"The {nameof(MoveEventArgs)} have been renamed to {nameof(TopicMoveEventArgs)}.", true)] +public class MoveEventArgs : EventArgs { /*============================================================================================================================ - | CLASS: MOVE EVENT ARGS + | CONSTRUCTOR: MOVE EVENT ARGS \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The MoveEventArgs object defines an event argument type specific to move events. + /// Initializes a new instance of the class and sets the and + /// properties based on the specified objects. /// - /// - /// Allows tracking of the source and destination topics. - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(MoveEventArgs)} have been renamed to {nameof(TopicMoveEventArgs)}.", true)] - public class MoveEventArgs : EventArgs { - - /*========================================================================================================================== - | CONSTRUCTOR: MOVE EVENT ARGS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class and sets the and - /// properties based on the specified objects. - /// - /// The topic object associated with the move event. - /// The parent topic object targeted by the move event. - /// - /// topic is not null - /// - /// - /// target is not null - /// - /// - /// topic != target - /// - public MoveEventArgs(Topic topic, Topic target) { - Contract.Requires(topic, "topic"); - Contract.Requires(target, "target"); - Contract.Requires(topic != target, "The topic cannot be its own parent."); - Topic = topic; - Target = target; - } + /// The topic object associated with the move event. + /// The parent topic object targeted by the move event. + /// + /// topic is not null + /// + /// + /// target is not null + /// + /// + /// topic != target + /// + public MoveEventArgs(Topic topic, Topic target) { + Contract.Requires(topic, "topic"); + Contract.Requires(target, "target"); + Contract.Requires(topic != target, "The topic cannot be its own parent."); + Topic = topic; + Target = target; + } - /*========================================================================================================================== - | PROPERTY: EVENT TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Topic object associated with the event. - /// - public Topic Topic { get; set; } + /*============================================================================================================================ + | PROPERTY: EVENT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the Topic object associated with the event. + /// + public Topic Topic { get; set; } - /*========================================================================================================================== - | PROPERTY: TARGET - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the new parent that the topic will be moved to. - /// - public Topic Target { get; set; } + /*============================================================================================================================ + | PROPERTY: TARGET + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the new parent that the topic will be moved to. + /// + public Topic Target { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Obsolete/Repositories/RenameEventArgs.cs b/OnTopic/Obsolete/Repositories/RenameEventArgs.cs index 50e54213..c309efd8 100644 --- a/OnTopic/Obsolete/Repositories/RenameEventArgs.cs +++ b/OnTopic/Obsolete/Repositories/RenameEventArgs.cs @@ -4,40 +4,39 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: RENAME EVENT ARGS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The RenameEventArgs object defines an event argument type specific to rename events. +/// +[ExcludeFromCodeCoverage] +[Obsolete($"The {nameof(RenameEventArgs)} have been renamed to {nameof(TopicEventArgs)}.", true)] +public class RenameEventArgs : EventArgs { /*============================================================================================================================ - | CLASS: RENAME EVENT ARGS + | CONSTRUCTOR: TAXONOMY RENAME EVENT ARGS \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The RenameEventArgs object defines an event argument type specific to rename events. + /// Initializes a new instance of the class and sets the property based + /// on the specified object. /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(RenameEventArgs)} have been renamed to {nameof(TopicEventArgs)}.", true)] - public class RenameEventArgs : EventArgs { - - /*========================================================================================================================== - | CONSTRUCTOR: TAXONOMY RENAME EVENT ARGS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class and sets the property based - /// on the specified object. - /// - /// The topic object associated with the rename event. - public RenameEventArgs(Topic topic) { - Topic = topic; - } + /// The topic object associated with the rename event. + public RenameEventArgs(Topic topic) { + Topic = topic; + } - /*========================================================================================================================== - | PROPERTY: TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Topic object associated with the event. - /// - /// - /// The topic. - /// - public Topic Topic { get; } + /*============================================================================================================================ + | PROPERTY: TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the Topic object associated with the event. + /// + /// + /// The topic. + /// + public Topic Topic { get; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Querying/TopicCollectionExtensions.cs b/OnTopic/Querying/TopicCollectionExtensions.cs index d2d924b6..b930c608 100644 --- a/OnTopic/Querying/TopicCollectionExtensions.cs +++ b/OnTopic/Querying/TopicCollectionExtensions.cs @@ -5,43 +5,42 @@ \=============================================================================================================================*/ using OnTopic.Collections; -namespace OnTopic.Querying { +namespace OnTopic.Querying; + +/*============================================================================================================================== +| CLASS: TOPIC COLLECTION (EXTENSIONS) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides extensions for querying , , and related +/// collections via the generic interface. +/// +public static class TopicCollectionExtensions { /*============================================================================================================================ - | CLASS: TOPIC COLLECTION (EXTENSIONS) + | METHOD: ANY DIRTY? \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides extensions for querying , , and related - /// collections via the generic interface. + /// Determines whether any of the instances in the collection are marked as . /// - public static class TopicCollectionExtensions { - - /*========================================================================================================================== - | METHOD: ANY DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether any of the instances in the collection are marked as . - /// - /// - /// This does not determine if the collection itself is dirty—it only determines if any instances in - /// the collection are . This distinction is important. For example, if a clean is added to the collection, then the collection will be dirty—but - /// will be false. - /// - /// The collection of instances to operate against. - /// Returns true if any of the instances are . - public static bool AnyDirty(this IEnumerable topics) => topics.Any(t => t.IsDirty(true)); + /// + /// This does not determine if the collection itself is dirty—it only determines if any instances in + /// the collection are . This distinction is important. For example, if a clean is added to the collection, then the collection will be dirty—but + /// will be false. + /// + /// The collection of instances to operate against. + /// Returns true if any of the instances are . + public static bool AnyDirty(this IEnumerable topics) => topics.Any(t => t.IsDirty(true)); - /*========================================================================================================================== - | METHOD: ANY NEW? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether any of the instances in the collection are marked as . - /// - /// The collection of instances to operate against. - /// Returns true if any of the instances are . - public static bool AnyNew(this IEnumerable topics) => topics.Any(t => t.IsNew); + /*============================================================================================================================ + | METHOD: ANY NEW? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether any of the instances in the collection are marked as . + /// + /// The collection of instances to operate against. + /// Returns true if any of the instances are . + public static bool AnyNew(this IEnumerable topics) => topics.Any(t => t.IsNew); - } } diff --git a/OnTopic/Querying/TopicExtensions.cs b/OnTopic/Querying/TopicExtensions.cs index 6764ca59..9acece90 100644 --- a/OnTopic/Querying/TopicExtensions.cs +++ b/OnTopic/Querying/TopicExtensions.cs @@ -7,293 +7,292 @@ using OnTopic.Collections.Specialized; using OnTopic.Metadata; -namespace OnTopic.Querying { +namespace OnTopic.Querying; + +/*============================================================================================================================== +| CLASS: TOPIC (EXTENSIONS) +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides extensions for querying . +/// +public static class TopicExtensions { /*============================================================================================================================ - | CLASS: TOPIC (EXTENSIONS) + | METHOD: FIND FIRST \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides extensions for querying . + /// Finds the first instance of a in the topic tree that satisfies the delegate. /// - public static class TopicExtensions { + /// The instance of the to operate against; populated automatically by .NET. + /// The function to validate whether a should be included in the output. + /// The first instance of the topic to be satisfied. + public static Topic? FindFirst(this Topic topic, Func predicate) { - /*========================================================================================================================== - | METHOD: FIND FIRST + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Finds the first instance of a in the topic tree that satisfies the delegate. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The function to validate whether a should be included in the output. - /// The first instance of the topic to be satisfied. - public static Topic? FindFirst(this Topic topic, Func predicate) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires(predicate, nameof(predicate)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Search attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - if (predicate(topic)) { - return topic; - } + Contract.Requires(topic, nameof(topic)); + Contract.Requires(predicate, nameof(predicate)); - /*------------------------------------------------------------------------------------------------------------------------ - | Recurse over children - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var child in topic.Children) { - var nestedResult = child.FindFirst(predicate); - if (nestedResult is not null) { - return nestedResult; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Search attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + if (predicate(topic)) { + return topic; + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Recurse over children + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var child in topic.Children) { + var nestedResult = child.FindFirst(predicate); + if (nestedResult is not null) { + return nestedResult; } + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Indicate no results found + \-------------------------------------------------------------------------------------------------------------------------*/ + return null; + + } - /*------------------------------------------------------------------------------------------------------------------------ - | Indicate no results found - \-----------------------------------------------------------------------------------------------------------------------*/ - return null; + /*============================================================================================================================ + | METHOD: FIND FIRST PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Finds the first instance of among the parents that satisfies the delegate. + /// + /// The instance of the to operate against; populated automatically by .NET. + /// The function to validate whether a should be included in the output. + /// The first instance of a parent topic to be satisfied. + public static Topic? FindFirstParent(this Topic topic, Func predicate) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); + Contract.Requires(predicate, nameof(predicate)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Search attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + if (predicate(topic)) { + return topic; } - /*========================================================================================================================== - | METHOD: FIND FIRST PARENT + /*-------------------------------------------------------------------------------------------------------------------------- + | Find lowest common root \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Finds the first instance of among the parents that satisfies the delegate. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The function to validate whether a should be included in the output. - /// The first instance of a parent topic to be satisfied. - public static Topic? FindFirstParent(this Topic topic, Func predicate) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires(predicate, nameof(predicate)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Search attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - if (predicate(topic)) { - return topic; + while (topic.Parent is not null) { + if (predicate(topic.Parent)) { + return topic.Parent; } + topic = topic.Parent; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Find lowest common root - \-----------------------------------------------------------------------------------------------------------------------*/ - while (topic.Parent is not null) { - if (predicate(topic.Parent)) { - return topic.Parent; - } - topic = topic.Parent; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Indicate no results found + \-------------------------------------------------------------------------------------------------------------------------*/ + return null; - /*------------------------------------------------------------------------------------------------------------------------ - | Indicate no results found - \-----------------------------------------------------------------------------------------------------------------------*/ - return null; + } - } + /*============================================================================================================================ + | METHOD: FIND ALL + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a collection of all topics descending from—and including—the current topic. + /// + /// The instance of the to operate against; populated automatically by .NET. + /// A collection of topics descending from the current topic. + public static ReadOnlyTopicCollection FindAll(this Topic topic) => topic.FindAll(t => true); - /*========================================================================================================================== - | METHOD: FIND ALL + /// + /// Retrieves a collection of topics based on a supplied function. + /// + /// The instance of the to operate against; populated automatically by .NET. + /// The function to validate whether a should be included in the output. + /// A collection of topics matching the input parameters. + public static ReadOnlyTopicCollection FindAll(this Topic topic, Func predicate) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a collection of all topics descending from—and including—the current topic. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// A collection of topics descending from the current topic. - public static ReadOnlyTopicCollection FindAll(this Topic topic) => topic.FindAll(t => true); - - /// - /// Retrieves a collection of topics based on a supplied function. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The function to validate whether a should be included in the output. - /// A collection of topics matching the input parameters. - public static ReadOnlyTopicCollection FindAll(this Topic topic, Func predicate) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires(predicate, nameof(predicate)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Search attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var results = new TopicCollection(); - - if (predicate(topic)) { - results.Add(topic); - } + Contract.Requires(topic, nameof(topic)); + Contract.Requires(predicate, nameof(predicate)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Search attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var results = new TopicCollection(); - /*------------------------------------------------------------------------------------------------------------------------ - | Recurse over children - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var child in topic.Children) { - var nestedResults = child.FindAll(predicate); - foreach (var matchedTopic in nestedResults) { - if (!results.Contains(matchedTopic)) { - results.Add(matchedTopic); - } + if (predicate(topic)) { + results.Add(topic); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Recurse over children + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var child in topic.Children) { + var nestedResults = child.FindAll(predicate); + foreach (var matchedTopic in nestedResults) { + if (!results.Contains(matchedTopic)) { + results.Add(matchedTopic); } } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Return results - \-----------------------------------------------------------------------------------------------------------------------*/ - return new(results); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return results + \-------------------------------------------------------------------------------------------------------------------------*/ + return new(results); - } + } - /*========================================================================================================================== - | METHOD: FIND ALL BY ATTRIBUTE + /*============================================================================================================================ + | METHOD: FIND ALL BY ATTRIBUTE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a collection of topics based on an attribute name and value. + /// + /// The instance of the to operate against; populated automatically by .NET. + /// The string identifier for the against which to be searched. + /// The text value for the against which to be searched. + /// A collection of topics matching the input parameters. + /// + /// !String.IsNullOrWhiteSpace(name) + /// + /// + /// !name.Contains(" ") + /// + public static ReadOnlyTopicCollection FindAllByAttribute(this Topic topic, string attributeKey, string attributeValue) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a collection of topics based on an attribute name and value. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The string identifier for the against which to be searched. - /// The text value for the against which to be searched. - /// A collection of topics matching the input parameters. - /// - /// !String.IsNullOrWhiteSpace(name) - /// - /// - /// !name.Contains(" ") - /// - public static ReadOnlyTopicCollection FindAllByAttribute(this Topic topic, string attributeKey, string attributeValue) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires(!String.IsNullOrWhiteSpace(attributeKey), nameof(attributeKey)); - Contract.Requires(!String.IsNullOrWhiteSpace(attributeValue), nameof(attributeValue)); - TopicFactory.ValidateKey(attributeKey); - - /*------------------------------------------------------------------------------------------------------------------------ - | Return results - \-----------------------------------------------------------------------------------------------------------------------*/ - return topic.FindAll(t => - !String.IsNullOrEmpty(t.Attributes.GetValue(attributeKey)) && - t.Attributes.GetValue(attributeKey, "").Contains(attributeValue, StringComparison.OrdinalIgnoreCase) - ); + Contract.Requires(topic, nameof(topic)); + Contract.Requires(!String.IsNullOrWhiteSpace(attributeKey), nameof(attributeKey)); + Contract.Requires(!String.IsNullOrWhiteSpace(attributeValue), nameof(attributeValue)); + TopicFactory.ValidateKey(attributeKey); + /*-------------------------------------------------------------------------------------------------------------------------- + | Return results + \-------------------------------------------------------------------------------------------------------------------------*/ + return topic.FindAll(t => + !String.IsNullOrEmpty(t.Attributes.GetValue(attributeKey)) && + t.Attributes.GetValue(attributeKey, "").Contains(attributeValue, StringComparison.OrdinalIgnoreCase) + ); + + } + + /*============================================================================================================================ + | METHOD: GET TOPIC INDEX + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves all topics from the topic cache, and places them in an dictionary indexed by . + /// + /// The instance of the to operate against; populated automatically by .NET. + /// A dictionary of topics indexed by . + public static TopicIndex GetTopicIndex(this Topic topic) => new(topic.FindAll()); + + /*============================================================================================================================ + | METHOD: GET ROOT TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves the root in the current topic graph. + /// + /// The instance of the to operate against; populated automatically by .NET. + /// The at the root o the current topic graph. + public static Topic GetRootTopic(this Topic topic) => topic.FindFirstParent(t => t.Parent is null)!; + + /*============================================================================================================================ + | METHOD: GET BY UNIQUE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a with the specified , if available. + /// + /// The instance of the to operate against; populated automatically by .NET. + /// The of the to return. + /// A with the specified , if found. + public static Topic? GetByUniqueKey(this Topic topic, string uniqueKey) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, "The topic parameter must be specified."); + Contract.Requires(!String.IsNullOrWhiteSpace(uniqueKey), nameof(uniqueKey)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Find lowest common root + \-------------------------------------------------------------------------------------------------------------------------*/ + var currentTopic = topic.GetRootTopic(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle request for root + \-------------------------------------------------------------------------------------------------------------------------*/ + if (currentTopic.Key.Equals(uniqueKey, StringComparison.OrdinalIgnoreCase)) { + return currentTopic; } - /*========================================================================================================================== - | METHOD: GET TOPIC INDEX + /*-------------------------------------------------------------------------------------------------------------------------- + | Process keys \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves all topics from the topic cache, and places them in an dictionary indexed by . - /// - /// The instance of the to operate against; populated automatically by .NET. - /// A dictionary of topics indexed by . - public static TopicIndex GetTopicIndex(this Topic topic) => new(topic.FindAll()); - - /*========================================================================================================================== - | METHOD: GET ROOT TOPIC + if (uniqueKey.StartsWith(currentTopic.Key + ":", StringComparison.OrdinalIgnoreCase)) { + uniqueKey = uniqueKey[(currentTopic.Key.Length + 1)..]; + } + var keys = uniqueKey.Split(':', StringSplitOptions.RemoveEmptyEntries); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Navigate to the specific path \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the root in the current topic graph. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The at the root o the current topic graph. - public static Topic GetRootTopic(this Topic topic) => topic.FindFirstParent(t => t.Parent is null)!; - - /*========================================================================================================================== - | METHOD: GET BY UNIQUE KEY + foreach (var key in keys) { + currentTopic = currentTopic?.Children.GetValue(key); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Return topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a with the specified , if available. - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The of the to return. - /// A with the specified , if found. - public static Topic? GetByUniqueKey(this Topic topic, string uniqueKey) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, "The topic parameter must be specified."); - Contract.Requires(!String.IsNullOrWhiteSpace(uniqueKey), nameof(uniqueKey)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Find lowest common root - \-----------------------------------------------------------------------------------------------------------------------*/ - var currentTopic = topic.GetRootTopic(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Handle request for root - \-----------------------------------------------------------------------------------------------------------------------*/ - if (currentTopic.Key.Equals(uniqueKey, StringComparison.OrdinalIgnoreCase)) { - return currentTopic; - } + return currentTopic; - /*------------------------------------------------------------------------------------------------------------------------ - | Process keys - \-----------------------------------------------------------------------------------------------------------------------*/ - if (uniqueKey.StartsWith(currentTopic.Key + ":", StringComparison.OrdinalIgnoreCase)) { - uniqueKey = uniqueKey[(currentTopic.Key.Length + 1)..]; - } - var keys = uniqueKey.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Navigate to the specific path - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var key in keys) { - currentTopic = currentTopic?.Children.GetValue(key); - } + /*============================================================================================================================ + | METHOD: GET CONTENT TYPE DESCRIPTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves the for the current . + /// + /// The instance of the to operate against; populated automatically by .NET. + /// The associated with the . + public static ContentTypeDescriptor? GetContentTypeDescriptor(this Topic topic) { - /*------------------------------------------------------------------------------------------------------------------------ - | Return topic - \-----------------------------------------------------------------------------------------------------------------------*/ - return currentTopic; + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate contracts + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, "The topic parameter must be specified."); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Find the root + \-------------------------------------------------------------------------------------------------------------------------*/ + var rootContentType = topic.GetByUniqueKey("Root:Configuration:ContentTypes"); - /*========================================================================================================================== - | METHOD: GET CONTENT TYPE DESCRIPTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Find content type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves the for the current . - /// - /// The instance of the to operate against; populated automatically by .NET. - /// The associated with the . - public static ContentTypeDescriptor? GetContentTypeDescriptor(this Topic topic) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate contracts - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, "The topic parameter must be specified."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Find the root - \-----------------------------------------------------------------------------------------------------------------------*/ - var rootContentType = topic.GetByUniqueKey("Root:Configuration:ContentTypes"); - - /*------------------------------------------------------------------------------------------------------------------------ - | Find content type - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentTypeDescriptor = rootContentType?.FindFirst(t => - t.Key.Equals(topic.ContentType, StringComparison.OrdinalIgnoreCase) && - t is ContentTypeDescriptor - ) as ContentTypeDescriptor; - - /*------------------------------------------------------------------------------------------------------------------------ - | Return content type - \-----------------------------------------------------------------------------------------------------------------------*/ - return contentTypeDescriptor; + var contentTypeDescriptor = rootContentType?.FindFirst(t => + t.Key.Equals(topic.ContentType, StringComparison.OrdinalIgnoreCase) && + t is ContentTypeDescriptor + ) as ContentTypeDescriptor; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Return content type + \-------------------------------------------------------------------------------------------------------------------------*/ + return contentTypeDescriptor; + + } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/ITopicRepository.cs b/OnTopic/Repositories/ITopicRepository.cs index 3729c3da..bb00114b 100644 --- a/OnTopic/Repositories/ITopicRepository.cs +++ b/OnTopic/Repositories/ITopicRepository.cs @@ -5,232 +5,231 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| INTERFACE: TOPIC REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines the interface for reading and writing topics from a data storage repository. +/// +public interface ITopicRepository { + + /*============================================================================================================================ + | EVENT HANDLERS + \---------------------------------------------------------------------------------------------------------------------------*/ + + /// + /// Raised after a is loaded from the as part of a operation, or one of its overloads. + /// + /// + /// The event should only be raised when a new is loaded from the underlying + /// persistence store. It should not be loaded, for example, if a value is loaded from the cache, or a topicId is + /// queried from the database. Given this, this event will need to be raised in actual implementations, since it is + /// specific to the business logic of each . + /// + event EventHandler TopicLoaded; + + /// + /// Raised after a is saved in the as part of a operation. + /// + event EventHandler TopicSaved; + + /// + /// Raised after a is deleted from the as part of a operation. + /// + event EventHandler TopicDeleted; + + /// + /// Raised after a is moved within the as part of a operation. + /// + event EventHandler TopicMoved; + + /// + /// Raised after a is renamed as ppart of a + /// operation. + /// + event EventHandler TopicRenamed; + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(DeleteEvent)} has been renamed to {nameof(TopicDeleted)}")] + event EventHandler DeleteEvent; + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(MoveEvent)} has been renamed to {nameof(TopicMoved)}")] + event EventHandler MoveEvent; + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(RenameEvent)} has been renamed to {nameof(TopicRenamed)}")] + event EventHandler RenameEvent; + + /*============================================================================================================================ + | GET CONTENT TYPE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Retrieves a collection of Content Type Descriptor objects from the configuration section of the data provider. + /// + ContentTypeDescriptorCollection GetContentTypeDescriptors(); + + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + + /// + /// Loads the entire root topic graph, including all descendants. + /// + /// A topic object. + public Topic? Load() => Load(-1); + + /// + /// Loads a (and, optionally, all of its descendants) based on the specified . + /// + /// The topic identifier. + /// + /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic + /// associations—such as references, relationships, and —are integrated with existing entities. + /// + /// Determines whether or not to recurse through and load a topic's children. + /// A topic object. + Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true); + + /// + /// Loads a (and, optionally, all of its descendants) based on the specified . + /// + /// The fully-qualified unique topic key. + /// + /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic + /// associations—such as references, relationships, and —are integrated with existing entities. + /// + /// Determines whether or not to recurse through and load a topic's children. + /// A topic object. + Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true); + + /// + [ExcludeFromCodeCoverage] + [Obsolete("This overload has been removed in preference for Load(string, Topic, Boolean).")] + Topic? Load(string? uniqueKey, bool isRecursive); + + /// + /// Loads a specific version of a based on its and . + /// + /// + /// This overload does not accept an argument for recursion; it will only load a single instance of a version. Further, + /// it will only load versions for which the unique identifier is known. + /// + /// The topic identifier. + /// The version. + /// + /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic + /// associations—such as references, relationships, and —are integrated with existing entities. + /// + /// A topic object. + Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null); + + /// + Topic? Load(Topic topic, DateTime version); + + /*============================================================================================================================ + | METHOD: ROLLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Rolls back the supplied to a particular point in its version history by reloading legacy + /// attributes and then saving the new version. + /// + /// The current version of the to rollback. + /// The selected Date/Time for the version to which to roll back. + /// + /// !VersionHistory.Contains(version) + /// + void Rollback(Topic topic, DateTime version); + + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Updates the topic graph represented by the by loading any changes the specified . + /// + /// + /// The method is intended to provide basic synchronization of core attributes, + /// indexed attributes, extended attributes, relationships, and topic references. It is not expected to handle deletes + /// or reordering of topics. + /// + void Refresh(Topic referenceTopic, DateTime since); + + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Saves the (and, optionally, its descendants) to the persistence store. + /// + /// The object. + /// + /// Boolean indicator nothing whether to recurse through the topic's descendants and save them as well. + /// + /// + /// topic is not null + /// + /// topic + void Save(Topic topic, bool isRecursive = false); + + /// + [ExcludeFromCodeCoverage] + [Obsolete("The 'isDraft' argument of the Save() method has been removed.")] + int Save(Topic topic, bool isRecursive, bool isDraft); + + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Moves the from its existing parent to a parent, optionally placing + /// it after a supplied topic. + /// + /// + /// May optionally specify a topic. If specified, it is expected that the + /// will be placed immediately after the . + /// + /// The object to be moved. + /// The target object under which to move the source . + /// + /// An optional object representing a sibling adjacent to which the source should + /// be moved. + /// + /// Boolean value representing whether the operation completed successfully. + /// + /// topic is not null + /// + void Move(Topic topic, Topic target, Topic? sibling = null); /*============================================================================================================================ - | INTERFACE: TOPIC REPOSITORY + | METHOD: DELETE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines the interface for reading and writing topics from a data storage repository. + /// Deletes the provided from the topic tree. /// - public interface ITopicRepository { - - /*========================================================================================================================== - | EVENT HANDLERS - \-------------------------------------------------------------------------------------------------------------------------*/ - - /// - /// Raised after a is loaded from the as part of a operation, or one of its overloads. - /// - /// - /// The event should only be raised when a new is loaded from the underlying - /// persistence store. It should not be loaded, for example, if a value is loaded from the cache, or a topicId is - /// queried from the database. Given this, this event will need to be raised in actual implementations, since it is - /// specific to the business logic of each . - /// - event EventHandler TopicLoaded; - - /// - /// Raised after a is saved in the as part of a operation. - /// - event EventHandler TopicSaved; - - /// - /// Raised after a is deleted from the as part of a operation. - /// - event EventHandler TopicDeleted; - - /// - /// Raised after a is moved within the as part of a operation. - /// - event EventHandler TopicMoved; - - /// - /// Raised after a is renamed as ppart of a - /// operation. - /// - event EventHandler TopicRenamed; - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(DeleteEvent)} has been renamed to {nameof(TopicDeleted)}")] - event EventHandler DeleteEvent; - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(MoveEvent)} has been renamed to {nameof(TopicMoved)}")] - event EventHandler MoveEvent; - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(RenameEvent)} has been renamed to {nameof(TopicRenamed)}")] - event EventHandler RenameEvent; - - /*========================================================================================================================== - | GET CONTENT TYPE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Retrieves a collection of Content Type Descriptor objects from the configuration section of the data provider. - /// - ContentTypeDescriptorCollection GetContentTypeDescriptors(); - - /*========================================================================================================================== - | METHOD: LOAD - \-------------------------------------------------------------------------------------------------------------------------*/ - - /// - /// Loads the entire root topic graph, including all descendants. - /// - /// A topic object. - public Topic? Load() => Load(-1); - - /// - /// Loads a (and, optionally, all of its descendants) based on the specified . - /// - /// The topic identifier. - /// - /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic - /// associations—such as references, relationships, and —are integrated with existing entities. - /// - /// Determines whether or not to recurse through and load a topic's children. - /// A topic object. - Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true); - - /// - /// Loads a (and, optionally, all of its descendants) based on the specified . - /// - /// The fully-qualified unique topic key. - /// - /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic - /// associations—such as references, relationships, and —are integrated with existing entities. - /// - /// Determines whether or not to recurse through and load a topic's children. - /// A topic object. - Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true); - - /// - [ExcludeFromCodeCoverage] - [Obsolete("This overload has been removed in preference for Load(string, Topic, Boolean).")] - Topic? Load(string? uniqueKey, bool isRecursive); - - /// - /// Loads a specific version of a based on its and . - /// - /// - /// This overload does not accept an argument for recursion; it will only load a single instance of a version. Further, - /// it will only load versions for which the unique identifier is known. - /// - /// The topic identifier. - /// The version. - /// - /// When loading a single topic or branch, offers a reference topic graph that can be used to ensure that topic - /// associations—such as references, relationships, and —are integrated with existing entities. - /// - /// A topic object. - Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null); - - /// - Topic? Load(Topic topic, DateTime version); - - /*========================================================================================================================== - | METHOD: ROLLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Rolls back the supplied to a particular point in its version history by reloading legacy - /// attributes and then saving the new version. - /// - /// The current version of the to rollback. - /// The selected Date/Time for the version to which to roll back. - /// - /// !VersionHistory.Contains(version) - /// - void Rollback(Topic topic, DateTime version); - - /*========================================================================================================================== - | METHOD: REFRESH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Updates the topic graph represented by the by loading any changes the specified . - /// - /// - /// The method is intended to provide basic synchronization of core attributes, - /// indexed attributes, extended attributes, relationships, and topic references. It is not expected to handle deletes - /// or reordering of topics. - /// - void Refresh(Topic referenceTopic, DateTime since); - - /*========================================================================================================================== - | METHOD: SAVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Saves the (and, optionally, its descendants) to the persistence store. - /// - /// The object. - /// - /// Boolean indicator nothing whether to recurse through the topic's descendants and save them as well. - /// - /// - /// topic is not null - /// - /// topic - void Save(Topic topic, bool isRecursive = false); - - /// - [ExcludeFromCodeCoverage] - [Obsolete("The 'isDraft' argument of the Save() method has been removed.")] - int Save(Topic topic, bool isRecursive, bool isDraft); - - /*========================================================================================================================== - | METHOD: MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Moves the from its existing parent to a parent, optionally placing - /// it after a supplied topic. - /// - /// - /// May optionally specify a topic. If specified, it is expected that the - /// will be placed immediately after the . - /// - /// The object to be moved. - /// The target object under which to move the source . - /// - /// An optional object representing a sibling adjacent to which the source should - /// be moved. - /// - /// Boolean value representing whether the operation completed successfully. - /// - /// topic is not null - /// - void Move(Topic topic, Topic target, Topic? sibling = null); - - /*========================================================================================================================== - | METHOD: DELETE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Deletes the provided from the topic tree. - /// - /// The object to delete. - /// - /// Boolean indicator nothing whether to recurse through the 's descendants and delete them as well. If set to false - /// and the topic has children, including any nested topics, an exception will be thrown. The default is false. - /// - /// - /// topic is not null - /// - /// topic - void Delete(Topic topic, bool isRecursive = false); - - } //Interface -} //Namespace \ No newline at end of file + /// The object to delete. + /// + /// Boolean indicator nothing whether to recurse through the 's descendants and delete them as well. If set to false + /// and the topic has children, including any nested topics, an exception will be thrown. The default is false. + /// + /// + /// topic is not null + /// + /// topic + void Delete(Topic topic, bool isRecursive = false); + +} //Interface \ No newline at end of file diff --git a/OnTopic/Repositories/ObservableTopicRepository.cs b/OnTopic/Repositories/ObservableTopicRepository.cs index 8a257c65..950d9a72 100644 --- a/OnTopic/Repositories/ObservableTopicRepository.cs +++ b/OnTopic/Repositories/ObservableTopicRepository.cs @@ -5,259 +5,277 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: OBSERVABLE TOPIC REPOSITORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides an abstract base class for implementations which implements the event handling +/// logic. +/// +/// +/// All implementations of are expected to need the following logic at minimum. +/// Concrete implementations that are working directly with an underlying data source should prefer to instead derive from +/// the more opinionated , which provides more built-in business logic. +/// +public abstract class ObservableTopicRepository : ITopicRepository { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private EventHandler? _topicLoaded; + private EventHandler? _topicSaved; + private EventHandler? _topicDeleted; + private EventHandler? _topicMoved; + private EventHandler? _topicRenamed; /*============================================================================================================================ - | CLASS: OBSERVABLE TOPIC REPOSITORY + | EVENT HANDLERS + \---------------------------------------------------------------------------------------------------------------------------*/ + + /// + public event EventHandler? TopicLoaded { + add => _topicLoaded += value; + remove => _topicLoaded -= value; + } + + /// + public event EventHandler? TopicSaved { + add => _topicSaved += value; + remove => _topicSaved -= value; + } + + /// + public event EventHandler? TopicDeleted { + add => _topicDeleted += value; + remove => _topicDeleted -= value; + } + + /// + public event EventHandler? TopicMoved { + add => _topicMoved += value; + remove => _topicMoved -= value; + } + + /// + public event EventHandler? TopicRenamed { + add => _topicRenamed += value; + remove => _topicRenamed -= value; + } + + #pragma warning disable CS0067 // Events are never used; retained as an obsolete stub which will be removed in the next major version + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(DeleteEvent)} has been renamed to {nameof(TopicDeleted)}", true)] + public event EventHandler? DeleteEvent; + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(MoveEvent)} has been renamed to {nameof(TopicMoved)}", true)] + public event EventHandler? MoveEvent; + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The {nameof(RenameEvent)} has been renamed to {nameof(TopicRenamed)}", true)] + public event EventHandler? RenameEvent; + + #pragma warning restore CS0067 + + /*============================================================================================================================ + | ON TOPIC LOADED \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Provides an abstract base class for implementations which implements the event handling - /// logic. + /// Raises the event. /// /// - /// All implementations of are expected to need the following logic at minimum. - /// Concrete implementations that are working directly with an underlying data source should prefer to instead derive from - /// the more opinionated , which provides more built-in business logic. + /// + /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. + /// + /// + /// The method also allows derived classes to handle the event without + /// attaching a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// + /// When overriding the method in a derived class, be sure to call the + /// base class's method so that registered delegates receive the event. + /// /// - public abstract class ObservableTopicRepository : ITopicRepository { - - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private EventHandler? _topicLoaded; - private EventHandler? _topicSaved; - private EventHandler? _topicDeleted; - private EventHandler? _topicMoved; - private EventHandler? _topicRenamed; - - /*========================================================================================================================== - | EVENT HANDLERS - \-------------------------------------------------------------------------------------------------------------------------*/ - - /// - public event EventHandler? TopicLoaded { - add => _topicLoaded += value; - remove => _topicLoaded -= value; - } - - /// - public event EventHandler? TopicSaved { - add => _topicSaved += value; - remove => _topicSaved -= value; - } - - /// - public event EventHandler? TopicDeleted { - add => _topicDeleted += value; - remove => _topicDeleted -= value; - } - - /// - public event EventHandler? TopicMoved { - add => _topicMoved += value; - remove => _topicMoved -= value; - } - - /// - public event EventHandler? TopicRenamed { - add => _topicRenamed += value; - remove => _topicRenamed -= value; - } - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(DeleteEvent)} has been renamed to {nameof(TopicDeleted)}", true)] - public event EventHandler? DeleteEvent; - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(MoveEvent)} has been renamed to {nameof(TopicMoved)}", true)] - public event EventHandler? MoveEvent; - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The {nameof(RenameEvent)} has been renamed to {nameof(TopicRenamed)}", true)] - public event EventHandler? RenameEvent; - - /*========================================================================================================================== - | ON TOPIC LOADED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Raises the event. - /// - /// - /// - /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. - /// - /// - /// The method also allows derived classes to handle the event without - /// attaching a delegate. This is the preferred technique for handling the event in a derived class. - /// - /// - /// When overriding the method in a derived class, be sure to call the - /// base class's method so that registered delegates receive the event. - /// - /// - /// An instance of the associated with the event. - protected virtual void OnTopicLoaded(TopicLoadEventArgs args) => _topicLoaded?.Invoke(this, args); - - /*========================================================================================================================== - | ON TOPIC SAVED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Raises the event. - /// - /// - /// - /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. - /// - /// - /// The method also allows derived classes to handle the event without - /// attaching a delegate. This is the preferred technique for handling the event in a derived class. - /// - /// - /// When overriding the method in a derived class, be sure to call the - /// base class's method so that registered delegates receive the event. - /// - /// - /// An instance of the associated with the event. - protected virtual void OnTopicSaved(TopicSaveEventArgs args) => _topicSaved?.Invoke(this, args); - - /*========================================================================================================================== - | ON TOPIC DELETED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Raises the event. - /// - /// - /// - /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. - /// - /// - /// The method also allows derived classes to handle the event without - /// attaching a delegate. This is the preferred technique for handling the event in a derived class. - /// - /// - /// When overriding the method in a derived class, be sure to call the - /// base class's method so that registered delegates receive the event. - /// - /// - /// An instance of the associated with the event. - protected virtual void OnTopicDeleted(TopicEventArgs args) => _topicDeleted?.Invoke(this, args); - - /*========================================================================================================================== - | ON TOPIC MOVED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Raises the event. - /// - /// - /// - /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. - /// - /// - /// The method also allows derived classes to handle the event without - /// attaching a delegate. This is the preferred technique for handling the event in a derived class. - /// - /// - /// When overriding the method in a derived class, be sure to call the - /// base class's method so that registered delegates receive the event. - /// - /// - /// An instance of the associated with the event. - protected virtual void OnTopicMoved(TopicMoveEventArgs args) => _topicMoved?.Invoke(this, args); - - /*========================================================================================================================== - | ON TOPIC RENAMED - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Raises the event. - /// - /// - /// - /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. - /// - /// - /// The method also allows derived classes to handle the event - /// without attaching a delegate. This is the preferred technique for handling the event in a derived class. - /// - /// - /// When overriding the method in a derived class, be sure to call - /// the base class's method so that registered delegates receive the - /// event. - /// - /// - /// An instance of the associated with the event. - protected virtual void OnTopicRenamed(TopicRenameEventArgs args) => _topicRenamed?.Invoke(this, args); - - /*========================================================================================================================== - | GET CONTENT TYPE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public abstract ContentTypeDescriptorCollection GetContentTypeDescriptors(); - - /*========================================================================================================================== - | METHOD: LOAD - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public virtual Topic? Load() => Load(-1); - - /// - public abstract Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true); - - /// - public abstract Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true); - - /// - [ExcludeFromCodeCoverage] - [Obsolete("This overload has been removed in preference for Load(string, Topic, Boolean).")] - public Topic? Load(string? uniqueKey, bool isRecursive) => throw new NotImplementedException(); - - /// - public abstract Topic? Load(Topic topic, DateTime version); - - /// - public abstract Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null); - - /*========================================================================================================================== - | METHOD: REFRESH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public abstract void Refresh(Topic referenceTopic, DateTime since); - - /*========================================================================================================================== - | METHOD: ROLLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public abstract void Rollback(Topic topic, DateTime version); - - /*========================================================================================================================== - | METHOD: SAVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public abstract void Save(Topic topic, bool isRecursive = false); - - /// - [ExcludeFromCodeCoverage] - [Obsolete($"The 'isDraft' argument of the {nameof(Save)} method has been removed.")] - public int Save(Topic topic, bool isRecursive, bool isDraft) => throw new NotImplementedException(); - - /*========================================================================================================================== - | METHOD: MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public abstract void Move(Topic topic, Topic target, Topic? sibling = null); - - /*========================================================================================================================== - | METHOD: DELETE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public abstract void Delete(Topic topic, bool isRecursive = false); - - } //Class -} //Namespace \ No newline at end of file + /// An instance of the associated with the event. + protected virtual void OnTopicLoaded(TopicLoadEventArgs args) => _topicLoaded?.Invoke(this, args); + + /*============================================================================================================================ + | ON TOPIC SAVED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Raises the event. + /// + /// + /// + /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. + /// + /// + /// The method also allows derived classes to handle the event without + /// attaching a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// + /// When overriding the method in a derived class, be sure to call the + /// base class's method so that registered delegates receive the event. + /// + /// + /// An instance of the associated with the event. + protected virtual void OnTopicSaved(TopicSaveEventArgs args) => _topicSaved?.Invoke(this, args); + + /*============================================================================================================================ + | ON TOPIC DELETED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Raises the event. + /// + /// + /// + /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. + /// + /// + /// The method also allows derived classes to handle the event without + /// attaching a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// + /// When overriding the method in a derived class, be sure to call the + /// base class's method so that registered delegates receive the event. + /// + /// + /// An instance of the associated with the event. + protected virtual void OnTopicDeleted(TopicEventArgs args) => _topicDeleted?.Invoke(this, args); + + /*============================================================================================================================ + | ON TOPIC MOVED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Raises the event. + /// + /// + /// + /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. + /// + /// + /// The method also allows derived classes to handle the event without + /// attaching a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// + /// When overriding the method in a derived class, be sure to call the + /// base class's method so that registered delegates receive the event. + /// + /// + /// An instance of the associated with the event. + protected virtual void OnTopicMoved(TopicMoveEventArgs args) => _topicMoved?.Invoke(this, args); + + /*============================================================================================================================ + | ON TOPIC RENAMED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Raises the event. + /// + /// + /// + /// Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. + /// + /// + /// The method also allows derived classes to handle the event + /// without attaching a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// + /// When overriding the method in a derived class, be sure to call + /// the base class's method so that registered delegates receive the + /// event. + /// + /// + /// An instance of the associated with the event. + protected virtual void OnTopicRenamed(TopicRenameEventArgs args) => _topicRenamed?.Invoke(this, args); + + /*============================================================================================================================ + | GET CONTENT TYPE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public abstract ContentTypeDescriptorCollection GetContentTypeDescriptors(); + + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public virtual Topic? Load() => Load(-1); + + /// + public abstract Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true); + + /// + public abstract Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true); + + /// + [ExcludeFromCodeCoverage] + [Obsolete("This overload has been removed in preference for Load(string, Topic, Boolean).")] + public Topic? Load(string? uniqueKey, bool isRecursive) => throw new NotImplementedException(); + + /// + public abstract Topic? Load(Topic topic, DateTime version); + + /// + public abstract Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null); + + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public abstract void Refresh(Topic referenceTopic, DateTime since); + + /*============================================================================================================================ + | METHOD: ROLLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public abstract void Rollback(Topic topic, DateTime version); + + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public abstract void Save(Topic topic, bool isRecursive = false); + + /// + [ExcludeFromCodeCoverage] + [Obsolete($"The 'isDraft' argument of the {nameof(Save)} method has been removed.")] + public int Save(Topic topic, bool isRecursive, bool isDraft) => throw new NotImplementedException(); + + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public abstract void Move(Topic topic, Topic target, Topic? sibling = null); + + /*============================================================================================================================ + | METHOD: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public abstract void Delete(Topic topic, bool isRecursive = false); + + /*============================================================================================================================ + | METHOD: NORMALIZE TO UTC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Normalizes a value to UTC by converting local time or tagging unspecified kind as UTC. + /// + /// + /// Incoming arguments whose is + /// are assumed to already represent UTC; only the tag is updated, not the ticks. Callers are expected to pass UTC values; + /// this helper defends against the common case where the caller omits the kind. + /// + /// The value to normalize. + protected static DateTime NormalizeToUtc(DateTime value) => + value.Kind is DateTimeKind.Local? value.ToUniversalTime() : DateTime.SpecifyKind(value, DateTimeKind.Utc); + +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/TopicRepository.cs b/OnTopic/Repositories/TopicRepository.cs index 351b4466..f01380ec 100644 --- a/OnTopic/Repositories/TopicRepository.cs +++ b/OnTopic/Repositories/TopicRepository.cs @@ -9,940 +9,939 @@ using OnTopic.Metadata; using OnTopic.Querying; -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC DATA PROVIDER +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Provides a base class for which are responsible for persisting data. +/// +/// +/// +/// The is a highly opinionated base implementation of . +/// In addition to validating parameters and raising events on , , and , it also provides a number of (protected) methods to +/// aid implementors in evaluating and parsing data, such as . It is recommended that all concrete implementations of that are responsible for +/// persisting data to a data store use this as a base class. +/// +/// +/// Implementations of which need to use different business logic, or do not need to +/// implement business logic (such as unit test doubles) may instead opt to derive directly from the , which handles the basic event handling, and nothing else. Implementations of decorators +/// should instead derive from the . +/// +/// +public abstract class TopicRepository : ObservableTopicRepository { /*============================================================================================================================ - | CLASS: TOPIC DATA PROVIDER + | PRIVATE VARIABLES \---------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a base class for which are responsible for persisting data. - /// - /// - /// - /// The is a highly opinionated base implementation of . - /// In addition to validating parameters and raising events on , , and , it also provides a number of (protected) methods to - /// aid implementors in evaluating and parsing data, such as . It is recommended that all concrete implementations of that are responsible for - /// persisting data to a data store use this as a base class. - /// - /// - /// Implementations of which need to use different business logic, or do not need to - /// implement business logic (such as unit test doubles) may instead opt to derive directly from the , which handles the basic event handling, and nothing else. Implementations of decorators - /// should instead derive from the . - /// - /// - public abstract class TopicRepository : ObservableTopicRepository { + private readonly ContentTypeDescriptorCollection _contentTypeDescriptors = new(); - /*========================================================================================================================== - | PRIVATE VARIABLES - \-------------------------------------------------------------------------------------------------------------------------*/ - private readonly ContentTypeDescriptorCollection _contentTypeDescriptors = new(); + /*============================================================================================================================ + | GET CONTENT TYPE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override ContentTypeDescriptorCollection GetContentTypeDescriptors() { - /*========================================================================================================================== - | GET CONTENT TYPE DESCRIPTORS + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize content types \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override ContentTypeDescriptorCollection GetContentTypeDescriptors() { + if (_contentTypeDescriptors.Count == 0) { /*------------------------------------------------------------------------------------------------------------------------ - | Initialize content types + | Load configuration data \-----------------------------------------------------------------------------------------------------------------------*/ - if (_contentTypeDescriptors.Count == 0) { - - /*---------------------------------------------------------------------------------------------------------------------- - | Load configuration data - \---------------------------------------------------------------------------------------------------------------------*/ - var configuration = (Topic?)null; - - try { - configuration = Load("Root:Configuration"); - } - catch (TopicNotFoundException) { - //Swallow missing configuration, as this is an expected condition when working with a new database - } - - /*---------------------------------------------------------------------------------------------------------------------- - | Load root content type - \---------------------------------------------------------------------------------------------------------------------*/ - var contentTypes = configuration?.Children.GetValue("ContentTypes") as ContentTypeDescriptor; - - /*---------------------------------------------------------------------------------------------------------------------- - | Add available Content Types to the collection - \---------------------------------------------------------------------------------------------------------------------*/ - _contentTypeDescriptors.Refresh(contentTypes); + var configuration = (Topic?)null; + try { + configuration = Load("Root:Configuration"); + } + catch (TopicNotFoundException) { + //Swallow missing configuration, as this is an expected condition when working with a new database } - - return _contentTypeDescriptors; - - } - - /// - /// Optional overload of allows for a new topic graph to be supplied for - /// updating the list of cached s. - /// - /// - /// By default, the method will load data from the concrete implementation of - /// the 's data store. There are cases, however, where it may be preferrable to instead load - /// these topics from a local, in-memory source. Namely, when first instantiating a new OnTopic database, and when saving - /// modifications to existing content types. As such, this protected overload is useful to call from when the topic graph being saved includes any s. - /// - /// - /// The root of a topic graph to merge into the collection for . The code will process not only the root , but - /// also any descendents. - /// - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"Deprecated. Instead, use the new {nameof(SetContentTypeDescriptors)} method, which provides the same function.", - true - )] - protected virtual ContentTypeDescriptorCollection GetContentTypeDescriptors(ContentTypeDescriptor? contentTypeDescriptors) - => SetContentTypeDescriptors(contentTypeDescriptors); - - /*========================================================================================================================== - | SET CONTENT TYPE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Allows for the content type descriptor cache to be (re)initialized based on an in-memory topic graph, by first - /// identifying the root from within the current content graph. - /// - /// - /// A within the source topic graph. This overload will use this topic to identify the root within the graph. - /// - /// - protected ContentTypeDescriptorCollection SetContentTypeDescriptors(Topic? sourceTopic) => - SetContentTypeDescriptors(sourceTopic?.GetByUniqueKey("Root:Configuration:ContentTypes") as ContentTypeDescriptor); - - /// - /// Allows for the content type descriptor cache to be (re)initialized based on an in-memory topic graph, starting with - /// the root . - /// - /// - /// By default, the method will load data from the - /// concrete implementation of the 's data store. There are cases, however, where it may be - /// preferrable to instead load these topics from a local, in-memory source. Namely, when first instantiating a new - /// OnTopic database, and when saving modifications to existing content types. As such, the protected method is useful to call from when the topic graph being saved includes any new s. - /// - /// - /// The root of a topic graph to merge into the collection for . The code will process not only the root , but also any descendents. - /// - /// - protected ContentTypeDescriptorCollection SetContentTypeDescriptors(ContentTypeDescriptor? rootContentType) { /*------------------------------------------------------------------------------------------------------------------------ - | Establish cache - >------------------------------------------------------------------------------------------------------------------------- - | Instead of attempting to merge the source collection with the cached collection, we'll just recreate the cached - | collection based on the source collection. This is faster, and helps avoid potential versioning conflicts caused by - | mixing objects from different topic graphs. Instead, we always assume that the source collection is the most accurate - | and relevant. + | Load root content type \-----------------------------------------------------------------------------------------------------------------------*/ - _contentTypeDescriptors.Refresh(rootContentType); - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate cache - >------------------------------------------------------------------------------------------------------------------------- - | If the source cache collection is empty then we'll want to defer to the existing version�or retrieve it from the - | persistence layer�via GetContentTypeDescriptors(). - \-----------------------------------------------------------------------------------------------------------------------*/ - if (_contentTypeDescriptors.Count == 0) { - GetContentTypeDescriptors(); - } + var contentTypes = configuration?.Children.GetValue("ContentTypes") as ContentTypeDescriptor; /*------------------------------------------------------------------------------------------------------------------------ | Add available Content Types to the collection \-----------------------------------------------------------------------------------------------------------------------*/ - return _contentTypeDescriptors; + _contentTypeDescriptors.Refresh(contentTypes); } - /*========================================================================================================================== - | GET CONTENT TYPE DESCRIPTOR + return _contentTypeDescriptors; + + } + + /// + /// Optional overload of allows for a new topic graph to be supplied for + /// updating the list of cached s. + /// + /// + /// By default, the method will load data from the concrete implementation of + /// the 's data store. There are cases, however, where it may be preferrable to instead load + /// these topics from a local, in-memory source. Namely, when first instantiating a new OnTopic database, and when saving + /// modifications to existing content types. As such, this protected overload is useful to call from when the topic graph being saved includes any s. + /// + /// + /// The root of a topic graph to merge into the collection for . The code will process not only the root , but + /// also any descendents. + /// + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"Deprecated. Instead, use the new {nameof(SetContentTypeDescriptors)} method, which provides the same function.", + true + )] + protected virtual ContentTypeDescriptorCollection GetContentTypeDescriptors(ContentTypeDescriptor? contentTypeDescriptors) + => SetContentTypeDescriptors(contentTypeDescriptors); + + /*============================================================================================================================ + | SET CONTENT TYPE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Allows for the content type descriptor cache to be (re)initialized based on an in-memory topic graph, by first + /// identifying the root from within the current content graph. + /// + /// + /// A within the source topic graph. This overload will use this topic to identify the root within the graph. + /// + /// + protected ContentTypeDescriptorCollection SetContentTypeDescriptors(Topic? sourceTopic) => + SetContentTypeDescriptors(sourceTopic?.GetByUniqueKey("Root:Configuration:ContentTypes") as ContentTypeDescriptor); + + /// + /// Allows for the content type descriptor cache to be (re)initialized based on an in-memory topic graph, starting with + /// the root . + /// + /// + /// By default, the method will load data from the + /// concrete implementation of the 's data store. There are cases, however, where it may be + /// preferrable to instead load these topics from a local, in-memory source. Namely, when first instantiating a new + /// OnTopic database, and when saving modifications to existing content types. As such, the protected method is useful to call from when the topic graph being saved includes any new s. + /// + /// + /// The root of a topic graph to merge into the collection for . The code will process not only the root , but also any descendents. + /// + /// + protected ContentTypeDescriptorCollection SetContentTypeDescriptors(ContentTypeDescriptor? rootContentType) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish cache + >------------------------------------------------------------------------------------------------------------------------- + | Instead of attempting to merge the source collection with the cached collection, we'll just recreate the cached + | collection based on the source collection. This is faster, and helps avoid potential versioning conflicts caused by + | mixing objects from different topic graphs. Instead, we always assume that the source collection is the most accurate + | and relevant. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attempts to identify the for the provided . - /// - /// - /// The method will attempt to get the - /// from the method using the 's . If that can't be found, however, then it will instead look in the 's topic graph to see if the can be found there. This is - /// useful for cases where new topic graphs are being imported and a new references a new prior to it having been saved. In this case, that new version will be added to the - /// locally cached collection used by . - /// - /// - /// - protected ContentTypeDescriptor? GetContentTypeDescriptor(Topic sourceTopic) { + _contentTypeDescriptors.Refresh(rootContentType); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(sourceTopic, nameof(sourceTopic)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate cache + >------------------------------------------------------------------------------------------------------------------------- + | If the source cache collection is empty then we'll want to defer to the existing version—or retrieve it from the + | persistence layer—via GetContentTypeDescriptors(). + \-------------------------------------------------------------------------------------------------------------------------*/ + if (_contentTypeDescriptors.Count == 0) { + GetContentTypeDescriptors(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve content type - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentType = sourceTopic.ContentType; - var contentTypes = GetContentTypeDescriptors(); - var contentTypeDescriptor = contentTypes.Contains(contentType)? contentTypes[contentType] : null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Add available Content Types to the collection + \-------------------------------------------------------------------------------------------------------------------------*/ + return _contentTypeDescriptors; - if (contentTypeDescriptor is not null) { - return contentTypeDescriptor; - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to update content types from source graph - \-----------------------------------------------------------------------------------------------------------------------*/ - SetContentTypeDescriptors(sourceTopic); + /*============================================================================================================================ + | GET CONTENT TYPE DESCRIPTOR + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attempts to identify the for the provided . + /// + /// + /// The method will attempt to get the + /// from the method using the 's . If that can't be found, however, then it will instead look in the 's topic graph to see if the can be found there. This is + /// useful for cases where new topic graphs are being imported and a new references a new prior to it having been saved. In this case, that new version will be added to the + /// locally cached collection used by . + /// + /// + /// + protected ContentTypeDescriptor? GetContentTypeDescriptor(Topic sourceTopic) { - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve content type - \-----------------------------------------------------------------------------------------------------------------------*/ - return contentTypes.Contains(contentType)? contentTypes[contentType] : null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(sourceTopic, nameof(sourceTopic)); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve content type + \-------------------------------------------------------------------------------------------------------------------------*/ + var contentType = sourceTopic.ContentType; + var contentTypes = GetContentTypeDescriptors(); + var contentTypeDescriptor = contentTypes.Contains(contentType)? contentTypes[contentType] : null; + if (contentTypeDescriptor is not null) { + return contentTypeDescriptor; } - /*========================================================================================================================== - | METHOD: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to update content types from source graph \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load(Topic topic, DateTime version) { - Contract.Requires(topic, nameof(topic)); - Contract.Requires( - !topic.IsNew, - $"The version '{version}' of '{topic.GetUniqueKey()}' cannot be loaded. Topics must be saved in order to load " + - $"previous versions." - ); - return Load(topic.Id, version, topic); - } + SetContentTypeDescriptors(sourceTopic); - /*========================================================================================================================== - | METHOD: ROLLBACK + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve content type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Rollback([ValidatedNotNull]Topic topic, DateTime version) { + return contentTypes.Contains(contentType)? contentTypes[contentType] : null; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires(version, nameof(version)); - Contract.Requires( - topic.VersionHistory.Contains(version), - "The version requested for rollback does not exist in the version history" - ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Retrieve topic from database - \-----------------------------------------------------------------------------------------------------------------------*/ - Load(topic, version); + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load(Topic topic, DateTime version) { + Contract.Requires(topic, nameof(topic)); + Contract.Requires( + !topic.IsNew, + $"The version '{version}' of '{topic.GetUniqueKey()}' cannot be loaded. Topics must be saved in order to load " + + $"previous versions." + ); + return Load(topic.Id, version, topic); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Save as new version - \-----------------------------------------------------------------------------------------------------------------------*/ - Save(topic, false); + /*============================================================================================================================ + | METHOD: ROLLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Rollback([ValidatedNotNull]Topic topic, DateTime version) { - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); + Contract.Requires(version != default, nameof(version)); + Contract.Requires( + topic.VersionHistory.Contains(version), + "The version requested for rollback does not exist in the version history" + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Retrieve topic from database + \-------------------------------------------------------------------------------------------------------------------------*/ + Load(topic, version); - /*========================================================================================================================== - | METHOD: SAVE + /*-------------------------------------------------------------------------------------------------------------------------- + | Save as new version \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override sealed void Save([ValidatedNotNull] Topic topic, bool isRecursive = false) { + Save(topic, false); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - Contract.Requires( - topic.Parent is null || !topic.Parent.IsNew, - $"The parent of '{topic.GetUniqueKey()}' is not saved. Topics can only be saved once their parent is saved." - ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Establish dependencies - \-----------------------------------------------------------------------------------------------------------------------*/ - var version = DateTime.UtcNow; - var unresolvedTopics = new TopicCollection(); - var isNew = topic.IsNew; + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override sealed void Save([ValidatedNotNull] Topic topic, bool isRecursive = false) { - /*------------------------------------------------------------------------------------------------------------------------ - | Handle first pass - \-----------------------------------------------------------------------------------------------------------------------*/ - Save(topic, isRecursive, unresolvedTopics, version); + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); + Contract.Requires( + topic.Parent is null || !topic.Parent.IsNew, + $"The parent of '{topic.GetUniqueKey()}' is not saved. Topics can only be saved once their parent is saved." + ); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish dependencies + \-------------------------------------------------------------------------------------------------------------------------*/ + var version = DateTime.UtcNow; + var unresolvedTopics = new TopicCollection(); + var isNew = topic.IsNew; - /*------------------------------------------------------------------------------------------------------------------------ - | Attempt to resolve outstanding associations - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var unresolvedTopic in unresolvedTopics.ToList()) { - unresolvedTopics.Remove(unresolvedTopic); - Save(unresolvedTopic, false, unresolvedTopics, version); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle first pass + \-------------------------------------------------------------------------------------------------------------------------*/ + Save(topic, isRecursive, unresolvedTopics, version); - /*------------------------------------------------------------------------------------------------------------------------ - | Throw exception if unresolved topics - \-----------------------------------------------------------------------------------------------------------------------*/ - if (unresolvedTopics.Count > 0) { - throw new ReferentialIntegrityException( - $"The call to ITopicRepository.Save() introduced unresolved references on {unresolvedTopics.Count} topics, " + - $"including '{unresolvedTopics.LastOrDefault().GetUniqueKey()}'. This is usually due to relationships or topic " + - $"references outside the scope of the Save() which, themselves, have not yet been persisted to the data store. If " + - $"this is not resolved, these items will not be correctly persisted." - ); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Attempt to resolve outstanding associations + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var unresolvedTopic in unresolvedTopics.ToList()) { + unresolvedTopics.Remove(unresolvedTopic); + Save(unresolvedTopic, false, unresolvedTopics, version); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - OnTopicSaved(new(topic, isRecursive, isNew)); - - } - - /// - /// Recursive method that validates an individual topic, calls the derived implementation, and then recurses over any - /// child topics. - /// - /// - /// When recursively saving a topic graph, it is conceivable that references to other topics—such as or —can't yet be persisted because the target hasn't yet been saved, and thus the is still set to -1. To mitigate - /// this, the allows this private overload to keep track of unresolved - /// associations. The public overload uses this list to resave any topics - /// that include such references. This adds some overhead due to the duplicate , but - /// helps avoid potential data loss when working with complex topic graphs. - /// - /// The source to save. - /// Determines whether or not to recursively save . - /// A list of s with unresolved topic references. - /// The version to assign to the updates. - private void Save([NotNull]Topic topic, bool isRecursive, TopicCollection unresolvedTopics, DateTime version) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Throw exception if unresolved topics + \-------------------------------------------------------------------------------------------------------------------------*/ + if (unresolvedTopics.Count > 0) { + throw new ReferentialIntegrityException( + $"The call to ITopicRepository.Save() introduced unresolved references on {unresolvedTopics.Count} topics, " + + $"including '{unresolvedTopics.Last().GetUniqueKey()}'. This is usually due to relationships or topic " + + $"references outside the scope of the Save() which, themselves, have not yet been persisted to the data store. If " + + $"this is not resolved, these items will not be correctly persisted." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + OnTopicSaved(new(topic, isRecursive, isNew)); - /*------------------------------------------------------------------------------------------------------------------------ - | Establish variables - \-----------------------------------------------------------------------------------------------------------------------*/ - var isNew = topic.IsNew; - var areRelationshipsDirty = topic.Relationships.IsDirty(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate content type - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentTypeDescriptors= GetContentTypeDescriptors(); - var contentTypeDescriptor = GetContentTypeDescriptor(topic); - - if (contentTypeDescriptor is null) { - throw new ReferentialIntegrityException( - $"The Content Type \"{topic.ContentType}\" referenced by \"{topic.Key}\" could not be found under " + - $"\"Configuration:ContentTypes\". There are currently {contentTypeDescriptors.Count} ContentTypes in the Repository." - ); - } + /// + /// Recursive method that validates an individual topic, calls the derived implementation, and then recurses over any + /// child topics. + /// + /// + /// When recursively saving a topic graph, it is conceivable that references to other topics—such as or —can't yet be persisted because the target hasn't yet been saved, and thus the is still set to -1. To mitigate + /// this, the allows this private overload to keep track of unresolved + /// associations. The public overload uses this list to resave any topics + /// that include such references. This adds some overhead due to the duplicate , but + /// helps avoid potential data loss when working with complex topic graphs. + /// + /// The source to save. + /// Determines whether or not to recursively save . + /// A list of s with unresolved topic references. + /// The version to assign to the updates. + private void Save([NotNull]Topic topic, bool isRecursive, TopicCollection unresolvedTopics, DateTime version) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); - /*------------------------------------------------------------------------------------------------------------------------ - | Handle unresolved associations - >------------------------------------------------------------------------------------------------------------------------- - | If it's a recursive save and there are any unresolved associations, come back to this after the topic graph has been - | saved; that ensures that any associations within the topic graph have been saved and can be properly persisted. - \-----------------------------------------------------------------------------------------------------------------------*/ - if ( - topic.Relationships.Any(r => r.Values.Any(t => t.Id < 0)) || - topic.References.Any(t => t.Value?.Id < 0) - ) { - unresolvedTopics.Add(topic); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Establish variables + \-------------------------------------------------------------------------------------------------------------------------*/ + var isNew = topic.IsNew; + var areRelationshipsDirty = topic.Relationships.IsDirty(); - /*------------------------------------------------------------------------------------------------------------------------ - | Execute core implementation - \-----------------------------------------------------------------------------------------------------------------------*/ - SaveTopic(topic, version, !isRecursive || !unresolvedTopics.Contains(topic)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate content type + \-------------------------------------------------------------------------------------------------------------------------*/ + var contentTypeDescriptors= GetContentTypeDescriptors(); + var contentTypeDescriptor = GetContentTypeDescriptor(topic); - /*------------------------------------------------------------------------------------------------------------------------ - | Mark as clean - \-----------------------------------------------------------------------------------------------------------------------*/ - topic.Attributes.MarkClean(version); + if (contentTypeDescriptor is null) { + throw new ReferentialIntegrityException( + $"The Content Type \"{topic.ContentType}\" referenced by \"{topic.Key}\" could not be found under " + + $"\"Configuration:ContentTypes\". There are currently {contentTypeDescriptors.Count} ContentTypes in the Repository." + ); + } - if (!unresolvedTopics.Contains(topic)) { - topic.References.MarkClean(); - topic.Relationships.MarkClean(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Handle unresolved associations + >------------------------------------------------------------------------------------------------------------------------- + | If it's a recursive save and there are any unresolved associations, come back to this after the topic graph has been + | saved; that ensures that any associations within the topic graph have been saved and can be properly persisted. + \-------------------------------------------------------------------------------------------------------------------------*/ + if ( + topic.Relationships.Any(r => r.Values.Any(t => t.Id < 0)) || + topic.References.Any(t => t.Value?.Id < 0) + ) { + unresolvedTopics.Add(topic); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Update version history - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!topic.VersionHistory.Contains(version)) { - topic.VersionHistory.Insert(0, version); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Execute core implementation + \-------------------------------------------------------------------------------------------------------------------------*/ + SaveTopic(topic, version, !isRecursive || !unresolvedTopics.Contains(topic)); - /*---------------------------------------------------------------------------------------------------------------------- - | Perform reordering and/or move - \---------------------------------------------------------------------------------------------------------------------*/ - if (topic.Parent is not null && !topic.IsNew && topic.IsDirty("Parent")) { - var topicIndex = topic.Parent.Children.IndexOf(topic); - if (topicIndex > 0) { - Move(topic, topic.Parent, topic.Parent.Children[topicIndex - 1]); - } - else { - Move(topic, topic.Parent); - } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Mark as clean + \-------------------------------------------------------------------------------------------------------------------------*/ + topic.Attributes.MarkClean(version); - /*------------------------------------------------------------------------------------------------------------------------ - | If new content type, add to cache - \-----------------------------------------------------------------------------------------------------------------------*/ - var asContentType = topic as ContentTypeDescriptor; - if ( - isNew && - asContentType is not null && - _contentTypeDescriptors is not null && - !_contentTypeDescriptors.Contains(topic.Key) - ) { - _contentTypeDescriptors.Add(asContentType); - } + if (!unresolvedTopics.Contains(topic)) { + topic.References.MarkClean(); + topic.Relationships.MarkClean(); + } - /*------------------------------------------------------------------------------------------------------------------------ - | If content type, and relationships have been updated, refresh permitted content types - \-----------------------------------------------------------------------------------------------------------------------*/ - if (asContentType is not null && areRelationshipsDirty) { - asContentType.ResetPermittedContentTypes(); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Update version history + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!topic.VersionHistory.Contains(version)) { + topic.VersionHistory.Insert(0, version); + } - /*------------------------------------------------------------------------------------------------------------------------ - | If new attribute, refresh cache - >------------------------------------------------------------------------------------------------------------------------- - | Every ContentTypeDescriptor has an AttributeDescriptors property which includes references to all local and inherited - | AttributeDescriptors. When a new AttributeDescriptor is added, these collections are reset for the current - | ContentTypeDescriptor and all descendents to ensure that they all reflect the new AttributeDescriptor. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (isNew && IsAttributeDescriptor(topic)) { - ResetAttributeDescriptors(topic); + /*-------------------------------------------------------------------------------------------------------------------------- + | Perform reordering and/or move + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic.Parent is not null && !topic.IsNew && topic.IsDirty("Parent")) { + var topicIndex = topic.Parent.Children.IndexOf(topic); + if (topicIndex > 0) { + Move(topic, topic.Parent, topic.Parent.Children[topicIndex - 1]); } - - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - if (topic.OriginalKey is not null && topic.OriginalKey != topic.Key) { - OnTopicRenamed(new(topic, topic.Key, topic.OriginalKey)); + else { + Move(topic, topic.Parent); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Reset original key - \-----------------------------------------------------------------------------------------------------------------------*/ - topic.OriginalKey = null; + /*-------------------------------------------------------------------------------------------------------------------------- + | If new content type, add to cache + \-------------------------------------------------------------------------------------------------------------------------*/ + var asContentType = topic as ContentTypeDescriptor; + if ( + isNew && + asContentType is not null && + _contentTypeDescriptors is not null && + !_contentTypeDescriptors.Contains(topic.Key) + ) { + _contentTypeDescriptors.Add(asContentType); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Recurse over children - \-----------------------------------------------------------------------------------------------------------------------*/ - if (isRecursive) { - foreach (var childTopic in topic.Children.ToList()) { - Save(childTopic, isRecursive, unresolvedTopics, version); - } - } + /*-------------------------------------------------------------------------------------------------------------------------- + | If content type, and relationships have been updated, refresh permitted content types + \-------------------------------------------------------------------------------------------------------------------------*/ + if (asContentType is not null && areRelationshipsDirty) { + asContentType.ResetPermittedContentTypes(); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | If new attribute, refresh cache + >------------------------------------------------------------------------------------------------------------------------- + | Every ContentTypeDescriptor has an AttributeDescriptors property which includes references to all local and inherited + | AttributeDescriptors. When a new AttributeDescriptor is added, these collections are reset for the current + | ContentTypeDescriptor and all descendents to ensure that they all reflect the new AttributeDescriptor. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (isNew && IsAttributeDescriptor(topic)) { + ResetAttributeDescriptors(topic); } - /*========================================================================================================================== - | METHOD: SAVE TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The core implementation logic for saving an individual during a - /// operation. - /// - /// - /// The main implementation handles advanced validation of the parameters, updating the - /// , attempting to pick up any unresolved topics, updating and instances as appropriate, raising the , if needed, and recursing over children. The derived implementation of is then left to focus exclusively on the core logic of persisting the changes - /// to the individual to the underlying data store, and optionally updating its and , assuming is set to - /// true. - /// - /// The source to save. - /// The version to assign to the updates. - /// - /// Determines whether or not and should be persisted. - /// This may be set to false if not all references have yet been saved, and the - /// call isRecursive; in that case, will circle back and attempt to save them - /// after the rest of the topic graph has been saved. - /// - protected abstract void SaveTopic([NotNull] Topic topic, DateTime version, bool persistRelationships); - - /*========================================================================================================================== - | METHOD: MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override sealed void Move([ValidatedNotNull]Topic topic, [ValidatedNotNull]Topic target, Topic? sibling = null) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + if (topic.OriginalKey is not null && topic.OriginalKey != topic.Key) { + OnTopicRenamed(new(topic, topic.Key, topic.OriginalKey)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(target != topic); - Contract.Requires(topic, nameof(topic)); - Contract.Requires(target, nameof(target)); - Contract.Requires(topic != target, "A topic cannot be its own parent."); - Contract.Requires(topic != sibling, "A topic cannot be moved relative to itself."); + /*-------------------------------------------------------------------------------------------------------------------------- + | Reset original key + \-------------------------------------------------------------------------------------------------------------------------*/ + topic.OriginalKey = null; - /*------------------------------------------------------------------------------------------------------------------------ - | Ignore requests - \-----------------------------------------------------------------------------------------------------------------------*/ - //If the target is already positioned after the sibling, then no actual change is registered - if ( - sibling is not null && - topic.Parent is not null && - topic.Parent == target && - topic.Parent.Children.IndexOf(sibling) == topic.Parent.Children.IndexOf(topic)-1) { - return; + /*-------------------------------------------------------------------------------------------------------------------------- + | Recurse over children + \-------------------------------------------------------------------------------------------------------------------------*/ + if (isRecursive) { + foreach (var childTopic in topic.Children.ToList()) { + Save(childTopic, isRecursive, unresolvedTopics, version); } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Execute core implementation - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!topic.IsNew && !target.IsNew && !(sibling?.IsNew?? true)) { - MoveTopic(topic, target, sibling); - } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Perform base logic - \-----------------------------------------------------------------------------------------------------------------------*/ - var previousParent = topic.Parent; - if (sibling is null) { - topic.SetParent(target); - } - else { - topic.SetParent(target, sibling); - } + /*============================================================================================================================ + | METHOD: SAVE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// The core implementation logic for saving an individual during a + /// operation. + /// + /// + /// The main implementation handles advanced validation of the parameters, updating the + /// , attempting to pick up any unresolved topics, updating and instances as appropriate, raising the , if needed, and recursing over children. The derived implementation of is then left to focus exclusively on the core logic of persisting the changes + /// to the individual to the underlying data store, and optionally updating its and , assuming is set to + /// true. + /// + /// The source to save. + /// The version to assign to the updates. + /// + /// Determines whether or not and should be persisted. + /// This may be set to false if not all references have yet been saved, and the + /// call isRecursive; in that case, will circle back and attempt to save them + /// after the rest of the topic graph has been saved. + /// + protected abstract void SaveTopic([NotNull] Topic topic, DateTime version, bool persistRelationships); - /*------------------------------------------------------------------------------------------------------------------------ - | Mark clean - >------------------------------------------------------------------------------------------------------------------------- - | To prevent the move from being recommitted the next time the topic is saved, mark "Parent" as clean. - \-----------------------------------------------------------------------------------------------------------------------*/ - topic.MarkClean("Parent"); + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override sealed void Move([ValidatedNotNull]Topic topic, [ValidatedNotNull]Topic target, Topic? sibling = null) { - /*------------------------------------------------------------------------------------------------------------------------ - | If a content type descriptor is being moved to a new parent, refresh cache - >------------------------------------------------------------------------------------------------------------------------- - | Attributes are inherited from parent content types, and stored in the ContentTypeDescriptor.AttributeDescriptors - | collection. As such, when a content type is moved to a new location, the attribute descriptors for itself and all - | descendants needs to be reset to ensure the inheritance structure is updated. - \-----------------------------------------------------------------------------------------------------------------------*/ - if (previousParent != target && topic is ContentTypeDescriptor) { - SetContentTypeDescriptors(topic); - ResetAttributeDescriptors(topic); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(target != topic); + Contract.Requires(topic, nameof(topic)); + Contract.Requires(target, nameof(target)); + Contract.Requires(topic != target, "A topic cannot be its own parent."); + Contract.Requires(topic != sibling, "A topic cannot be moved relative to itself."); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Ignore requests + \-------------------------------------------------------------------------------------------------------------------------*/ + //If the target is already positioned after the sibling, then no actual change is registered + if ( + sibling is not null && + topic.Parent is not null && + topic.Parent == target && + topic.Parent.Children.IndexOf(sibling) == topic.Parent.Children.IndexOf(topic)-1) { + return; + } - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - OnTopicMoved(new (topic, previousParent, target, sibling)); + /*-------------------------------------------------------------------------------------------------------------------------- + | Execute core implementation + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!topic.IsNew && !target.IsNew && !(sibling?.IsNew?? true)) { + MoveTopic(topic, target, sibling); + } + /*-------------------------------------------------------------------------------------------------------------------------- + | Perform base logic + \-------------------------------------------------------------------------------------------------------------------------*/ + var previousParent = topic.Parent; + if (sibling is null) { + topic.SetParent(target); + } + else { + topic.SetParent(target, sibling); } - /*========================================================================================================================== - | METHOD: MOVE TOPIC + /*-------------------------------------------------------------------------------------------------------------------------- + | Mark clean + >------------------------------------------------------------------------------------------------------------------------- + | To prevent the move from being recommitted the next time the topic is saved, mark "Parent" as clean. \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// - /// The core implementation logic for moving a . - /// - /// - /// The main implementation handles advanced validation of the parameters, - /// updating the 's location within the topic graph, updating and - /// instances as appropriate, and raising the . - /// The derived implementation of is then left to focus exclusively on the - /// core logic of persisting the change to the underlying data store. - /// - protected abstract void MoveTopic(Topic topic, Topic target, Topic? sibling = null); + topic.MarkClean("Parent"); + + /*-------------------------------------------------------------------------------------------------------------------------- + | If a content type descriptor is being moved to a new parent, refresh cache + >------------------------------------------------------------------------------------------------------------------------- + | Attributes are inherited from parent content types, and stored in the ContentTypeDescriptor.AttributeDescriptors + | collection. As such, when a content type is moved to a new location, the attribute descriptors for itself and all + | descendants needs to be reset to ensure the inheritance structure is updated. + \-------------------------------------------------------------------------------------------------------------------------*/ + if (previousParent != target && topic is ContentTypeDescriptor) { + SetContentTypeDescriptors(topic); + ResetAttributeDescriptors(topic); + } - /*========================================================================================================================== - | METHOD: DELETE + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override sealed void Delete([ValidatedNotNull]Topic topic, bool isRecursive = false) { + OnTopicMoved(new (topic, previousParent, target, sibling)); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Validate descendants - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!isRecursive && topic.Children.Any(t => !t.ContentType.Equals("List", StringComparison.OrdinalIgnoreCase))) { - throw new ReferentialIntegrityException( - $"The topic '{topic.GetUniqueKey()}' cannot be deleted. It has child topics, but '{nameof(isRecursive)}' is set to " + - $"false. To delete '{topic.GetUniqueKey()}' and all of its descendants, set '{nameof(isRecursive)}' to true." - ); - } + /*============================================================================================================================ + | METHOD: MOVE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// + /// The core implementation logic for moving a . + /// + /// + /// The main implementation handles advanced validation of the parameters, + /// updating the 's location within the topic graph, updating and + /// instances as appropriate, and raising the . + /// The derived implementation of is then left to focus exclusively on the + /// core logic of persisting the change to the underlying data store. + /// + protected abstract void MoveTopic(Topic topic, Topic target, Topic? sibling = null); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate base topics - \-----------------------------------------------------------------------------------------------------------------------*/ - var childTopics = topic.FindAll(); - var allTopics = topic.GetRootTopic().FindAll().Except(childTopics); - var baseTopic = allTopics.FirstOrDefault(t => t.BaseTopic is not null && childTopics.Contains(t.BaseTopic)); - - if (baseTopic is not null) { - throw new ReferentialIntegrityException( - $"The topic '{topic.GetUniqueKey()}' cannot be deleted. The topic '{baseTopic.GetUniqueKey()}' derives from the " + - $"topic '{baseTopic.BaseTopic!.GetUniqueKey()}'. Deleting this would cause violate the integrity of the " + - $"persistence store." - ); - } + /*============================================================================================================================ + | METHOD: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override sealed void Delete([ValidatedNotNull]Topic topic, bool isRecursive = false) { - /*------------------------------------------------------------------------------------------------------------------------ - | Execute core implementation - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!topic.IsNew) { - DeleteTopic(topic); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate parameters + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); - /*------------------------------------------------------------------------------------------------------------------------ - | Remove from parent - \-----------------------------------------------------------------------------------------------------------------------*/ - topic.Parent?.Children.Remove(topic.Key); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate descendants + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!isRecursive && topic.Children.Any(t => !t.ContentType.Equals("List", StringComparison.OrdinalIgnoreCase))) { + throw new ReferentialIntegrityException( + $"The topic '{topic.GetUniqueKey()}' cannot be deleted. It has child topics, but '{nameof(isRecursive)}' is set to " + + $"false. To delete '{topic.GetUniqueKey()}' and all of its descendants, set '{nameof(isRecursive)}' to true." + ); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Remove relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - var descendantTopics = topic.FindAll(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate base topics + \-------------------------------------------------------------------------------------------------------------------------*/ + var childTopics = topic.FindAll(); + var allTopics = topic.GetRootTopic().FindAll().Except(childTopics); + var baseTopic = allTopics.FirstOrDefault(t => t.BaseTopic is not null && childTopics.Contains(t.BaseTopic)); + + if (baseTopic is not null) { + throw new ReferentialIntegrityException( + $"The topic '{topic.GetUniqueKey()}' cannot be deleted. The topic '{baseTopic.GetUniqueKey()}' derives from the " + + $"topic '{baseTopic.BaseTopic!.GetUniqueKey()}'. Deleting this would cause violate the integrity of the " + + $"persistence store." + ); + } - foreach (var descendantTopic in descendantTopics) { - foreach (var relationship in descendantTopic.Relationships) { - foreach (var relatedTopic in relationship.Values.ToList()) { - if (!descendantTopics.Contains(relatedTopic)) { - descendantTopic.Relationships.Remove(relationship.Key, relatedTopic); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Execute core implementation + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!topic.IsNew) { + DeleteTopic(topic); + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove from parent + \-------------------------------------------------------------------------------------------------------------------------*/ + topic.Parent?.Children.Remove(topic.Key); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + var descendantTopics = topic.FindAll(); + + foreach (var descendantTopic in descendantTopics) { + foreach (var relationship in descendantTopic.Relationships) { + foreach (var relatedTopic in relationship.Values.ToList()) { + if (!descendantTopics.Contains(relatedTopic)) { + descendantTopic.Relationships.Remove(relationship.Key, relatedTopic); } } } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Remove references - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var descendantTopic in descendantTopics) { - foreach (var reference in descendantTopic.References.ToList()) { - if (reference.Value is not null && !descendantTopics.Contains(reference.Value)) { - descendantTopic.References.Remove(reference.Key); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove references + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var descendantTopic in descendantTopics) { + foreach (var reference in descendantTopic.References.ToList()) { + if (reference.Value is not null && !descendantTopics.Contains(reference.Value)) { + descendantTopic.References.Remove(reference.Key); } } + } - /*------------------------------------------------------------------------------------------------------------------------ - | Remove incoming relationships - \-----------------------------------------------------------------------------------------------------------------------*/ - foreach (var descendantTopic in descendantTopics) { - foreach (var relationship in descendantTopic.IncomingRelationships) { - foreach (var relatedTopic in relationship.Values.ToList()) { - if (!descendantTopics.Contains(relatedTopic)) { - if (relatedTopic.Relationships.Contains(relationship.Key, descendantTopic)) { - relatedTopic.Relationships.Remove(relationship.Key, descendantTopic); - } - else if (relatedTopic.References.Contains(relationship.Key)) { - relatedTopic.References.Remove(relationship.Key); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Remove incoming relationships + \-------------------------------------------------------------------------------------------------------------------------*/ + foreach (var descendantTopic in descendantTopics) { + foreach (var relationship in descendantTopic.IncomingRelationships) { + foreach (var relatedTopic in relationship.Values.ToList()) { + if (!descendantTopics.Contains(relatedTopic)) { + if (relatedTopic.Relationships.Contains(relationship.Key, descendantTopic)) { + relatedTopic.Relationships.Remove(relationship.Key, descendantTopic); + } + else if (relatedTopic.References.Contains(relationship.Key)) { + relatedTopic.References.Remove(relationship.Key); } } } } + } - /*------------------------------------------------------------------------------------------------------------------------ - | If content type, remove from cache - \-----------------------------------------------------------------------------------------------------------------------*/ - SetContentTypeDescriptors(topic.Parent); + /*-------------------------------------------------------------------------------------------------------------------------- + | If content type, remove from cache + \-------------------------------------------------------------------------------------------------------------------------*/ + SetContentTypeDescriptors(topic.Parent); - /*------------------------------------------------------------------------------------------------------------------------ - | If attribute type, refresh cache - \-----------------------------------------------------------------------------------------------------------------------*/ - if (IsAttributeDescriptor(topic)) { - ResetAttributeDescriptors(topic); - } + /*-------------------------------------------------------------------------------------------------------------------------- + | If attribute type, refresh cache + \-------------------------------------------------------------------------------------------------------------------------*/ + if (IsAttributeDescriptor(topic)) { + ResetAttributeDescriptors(topic); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Raise event - \-----------------------------------------------------------------------------------------------------------------------*/ - var args = new TopicEventArgs(topic); - OnTopicDeleted(args); - - } - - /*========================================================================================================================== - | METHOD: DELETE TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// - /// The core implementation logic for deleting a . - /// - /// - /// The main implementation handles advanced validation of the parameters, - /// removing the from the topic graph, updating and instances as appropriate, and raising the . The - /// derived implementation of is then left to focus exclusively on the core logic of - /// persisting the change to the underlying data store. - /// - protected abstract void DeleteTopic(Topic topic); - - /*========================================================================================================================== - | METHOD: GET ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , returns a list of , optionally filtering based on and . - /// - /// The from which to pull the attributes. - /// - /// Whether or not to filter by . If null, all s are returned. - /// - /// - /// Whether or not to filter by . If null, all s - /// are returned. - /// - /// Exclude any attributes that start with LastModified. - protected IEnumerable GetAttributes( - Topic topic, - bool? isExtendedAttribute, - bool? isDirty = null, - bool excludeLastModified = false - ) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Raise event + \-------------------------------------------------------------------------------------------------------------------------*/ + var args = new TopicEventArgs(topic); + OnTopicDeleted(args); - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Get associated content type descriptor - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentType = GetContentTypeDescriptor(topic); + /*============================================================================================================================ + | METHOD: DELETE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// + /// The core implementation logic for deleting a . + /// + /// + /// The main implementation handles advanced validation of the parameters, + /// removing the from the topic graph, updating and instances as appropriate, and raising the . The + /// derived implementation of is then left to focus exclusively on the core logic of + /// persisting the change to the underlying data store. + /// + protected abstract void DeleteTopic(Topic topic); - Contract.Assume( - contentType, - $"The topics repository does not contain a ContentTypeDescriptor for the '{topic.ContentType}' content type." - ); + /*============================================================================================================================ + | METHOD: GET ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , returns a list of , optionally filtering based on and . + /// + /// The from which to pull the attributes. + /// + /// Whether or not to filter by . If null, all s are returned. + /// + /// + /// Whether or not to filter by . If null, all s + /// are returned. + /// + /// Exclude any attributes that start with LastModified. + protected IEnumerable GetAttributes( + Topic topic, + bool? isExtendedAttribute, + bool? isDirty = null, + bool excludeLastModified = false + ) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); - /*------------------------------------------------------------------------------------------------------------------------ - | Get indexed attributes - \-----------------------------------------------------------------------------------------------------------------------*/ - var attributes = new List(); + /*-------------------------------------------------------------------------------------------------------------------------- + | Get associated content type descriptor + \-------------------------------------------------------------------------------------------------------------------------*/ + var contentType = GetContentTypeDescriptor(topic); - foreach (var attributeValue in topic.Attributes) { + Contract.Assume( + contentType, + $"The topics repository does not contain a ContentTypeDescriptor for the '{topic.ContentType}' content type." + ); - var key = attributeValue.Key; - var attribute = (AttributeDescriptor?)null; + /*-------------------------------------------------------------------------------------------------------------------------- + | Get indexed attributes + \-------------------------------------------------------------------------------------------------------------------------*/ + var attributes = new List(); - //Optionally exclude LastModified attributes - if (excludeLastModified && attributeValue.Key.StartsWith("LastModified", StringComparison.OrdinalIgnoreCase)) { - continue; - } + foreach (var attributeValue in topic.Attributes) { - //Reset cached attribute descriptors just in case a new attribute has been added - if (!contentType.AttributeDescriptors.Contains(key)) { - contentType.ResetAttributeDescriptors(); - } + var key = attributeValue.Key; + var attribute = (AttributeDescriptor?)null; - //Attempt to retrieve the corresponding attribute descriptor - if (contentType.AttributeDescriptors.Contains(key)) { - attribute = contentType.AttributeDescriptors[key]; - } + //Optionally exclude LastModified attributes + if (excludeLastModified && attributeValue.Key.StartsWith("LastModified", StringComparison.OrdinalIgnoreCase)) { + continue; + } - //Skip if the value is null or empty; these values are not persisted to storage and should be treated as equivalent to - //non-existent values. - if (String.IsNullOrEmpty(attributeValue.Value)) { - continue; - } + //Reset cached attribute descriptors just in case a new attribute has been added + if (!contentType.AttributeDescriptors.Contains(key)) { + contentType.ResetAttributeDescriptors(); + } - //Skip if attribute's isDirty flag doesn't match the callers preference. Alternatively, if the IsExtendedAttribute value - //doesn't match the source, as this implies the storage location has changed, and the attribute should be treated as - //isDirty implicitly. - var isAttributeDirty = IsExtendedAttributeMismatch(attribute, attributeValue) || attributeValue.IsDirty; - if (isDirty is null || isDirty.Value == isAttributeDirty) { - } - else { - continue; - } + //Attempt to retrieve the corresponding attribute descriptor + if (contentType.AttributeDescriptors.Contains(key)) { + attribute = contentType.AttributeDescriptors[key]; + } - //Add the attribute based on the isExtendedAttribute parameter. Add all parameters if isExtendedAttribute is null. - //Assume an attribute is extended if the corresponding attribute descriptor cannot be located and the value is over 255 - //characters. - if (isExtendedAttribute?.Equals(attribute?.IsExtendedAttribute?? attributeValue.Value.Length > 255)?? true) { - attributes.Add(attributeValue); - } + //Skip if the value is null or empty; these values are not persisted to storage and should be treated as equivalent to + //non-existent values. + if (String.IsNullOrEmpty(attributeValue.Value)) { + continue; + } + //Skip if attribute's isDirty flag doesn't match the callers preference. Alternatively, if the IsExtendedAttribute value + //doesn't match the source, as this implies the storage location has changed, and the attribute should be treated as + //isDirty implicitly. + var isAttributeDirty = IsExtendedAttributeMismatch(attribute, attributeValue) || attributeValue.IsDirty; + if (isDirty is null || isDirty.Value == isAttributeDirty) { + } + else { + continue; } - return attributes; + //Add the attribute based on the isExtendedAttribute parameter. Add all parameters if isExtendedAttribute is null. + //Assume an attribute is extended if the corresponding attribute descriptor cannot be located and the value is over 255 + //characters. + if (isExtendedAttribute?.Equals(attribute?.IsExtendedAttribute?? attributeValue.Value.Length > 255)?? true) { + attributes.Add(attributeValue); + } } - /*========================================================================================================================== - | METHOD: GET UNMATCHED ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , identifies s that are defined based on the , but aren't defined in the . - /// - /// The from which to pull the attributes. - protected IEnumerable GetUnmatchedAttributes(Topic topic) { + return attributes; - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); + } - /*------------------------------------------------------------------------------------------------------------------------ - | Get associated content type descriptor - \-----------------------------------------------------------------------------------------------------------------------*/ - var contentType = GetContentTypeDescriptor(topic); - - Contract.Assume( - contentType, - $"The topics repository does not contain a ContentTypeDescriptor for the '{topic.ContentType}' content type." - ); - - /*------------------------------------------------------------------------------------------------------------------------ - | Get unmatched attribute descriptors - \-----------------------------------------------------------------------------------------------------------------------*/ - var attributes = new AttributeDescriptorCollection(); + /*============================================================================================================================ + | METHOD: GET UNMATCHED ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , identifies s that are defined based on the , but aren't defined in the . + /// + /// The from which to pull the attributes. + protected IEnumerable GetUnmatchedAttributes(Topic topic) { - foreach (var attribute in contentType.AttributeDescriptors) { + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input + \-------------------------------------------------------------------------------------------------------------------------*/ + Contract.Requires(topic, nameof(topic)); - // Ignore unsaved topics - if (topic.IsNew) { - continue; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Get associated content type descriptor + \-------------------------------------------------------------------------------------------------------------------------*/ + var contentType = GetContentTypeDescriptor(topic); - // Ignore (now legacy) core attributes - if (attribute.Key is "Key" or "ContentType" or "ParentID") { - continue; - } + Contract.Assume( + contentType, + $"The topics repository does not contain a ContentTypeDescriptor for the '{topic.ContentType}' content type." + ); - // Ignore valid attributes - if ( - topic.Attributes.Contains(attribute.Key) && - !String.IsNullOrEmpty(topic.Attributes.GetValue(attribute.Key, null, false, false)) - ) { - continue; - }; - - // Ignore associations - if (attribute.ModelType is ModelType.Relationship or ModelType.NestedTopic or ModelType.Reference) { - continue; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Get unmatched attribute descriptors + \-------------------------------------------------------------------------------------------------------------------------*/ + var attributes = new AttributeDescriptorCollection(); - attributes.Add(attribute); + foreach (var attribute in contentType.AttributeDescriptors) { + // Ignore unsaved topics + if (topic.IsNew) { + continue; } - /*------------------------------------------------------------------------------------------------------------------------ - | Get arbitrary attributes - >------------------------------------------------------------------------------------------------------------------------- - | ###HACK JJC20200502: Arbitrary attributes are those that don't map back to the scheme. These aren't picked up by the - | AttributeDescriptors check above. This means there's no way to programmatically delete arbitrary (or orphaned) - | attributes. To mitigate this, any null or empty attribute values should be included. By definition, though, arbitrary - | attributes don't have corresponding AttributeDescriptors. To mitigate this, an ad hoc AttributeDescriptor object will be - | created for each empty AttributeDescriptor. - \-----------------------------------------------------------------------------------------------------------------------*/ - var attributeKeys = topic.Attributes - .Where(a => String.IsNullOrEmpty(a.Value)) - .Select(a => a.Key) - .Union(topic.Attributes.DeletedItems); - foreach (var attributeKey in attributeKeys) { - if (!attributes.Contains(attributeKey)) { - attributes.Add((AttributeDescriptor)TopicFactory.Create(attributeKey, "TextAttributeDescriptor")); - } + // Ignore (now legacy) core attributes + if (attribute.Key is "Key" or "ContentType" or "ParentID") { + continue; } - /*------------------------------------------------------------------------------------------------------------------------ - | Return values - \-----------------------------------------------------------------------------------------------------------------------*/ - return attributes; - - } - - /*========================================================================================================================== - | METHOD: IS ATTRIBUTE DESCRIPTOR? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Given a , determines if it derives from and is associated with - /// a . - /// - /// The to evaluate as an . - private static bool IsAttributeDescriptor(Topic topic) => - topic is AttributeDescriptor and { Parent: { Key: "Attributes", Parent: ContentTypeDescriptor } }; - - /*========================================================================================================================== - | METHOD: IS EXTENDED ATTRIBUTE MISMATCH? - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not there's a mismatch between the and the - /// . - /// - /// - /// - /// The determines where an attribute should be stored; the - /// determines where an attribute was stored. If these two - /// values are in conflict, that suggests the coniguration for has - /// changed since the attribute value was last saved. In that case, it should be treated as even though its value hasn't changed to ensure that its storage location is updated. - /// - /// - /// If cannot be found then the is arbitrary attribute - /// not mapped to the schema. In that case, its storage location is dynamically determined based on its length, and thus - /// it should only change locations when it . Otherwise, its length will remain - /// the same, and thus the storage location should remain unchanged. - /// - /// - /// The source , if available. - /// The target . - /// - private static bool IsExtendedAttributeMismatch(AttributeDescriptor? attributeDescriptor, AttributeRecord attributeValue) => - attributeDescriptor is not null && - attributeValue.IsExtendedAttribute is not null && - attributeDescriptor.IsExtendedAttribute != attributeValue.IsExtendedAttribute; - - /*========================================================================================================================== - | METHOD: RESET ATTRIBUTE DESCRIPTORS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Assuming a topic is either a or an , will - /// reset the cached s on the associated and all - /// children. - /// - /// - /// Each has a collection - /// which includes not only the s associated with that , but also any s from any parent s in the topic graph. This reflects the fact that attributes are inherited from parent - /// content types. As a result, however, when an is added or removed, or a is moved to a new parent, this cache should be reset on the associated and all descendent s to ensure the change is - /// reflected. - /// - /// The to evaluate as an . - private static void ResetAttributeDescriptors(Topic topic) { - if (IsAttributeDescriptor(topic)) { - ((ContentTypeDescriptor)topic.Parent!.Parent!).ResetAttributeDescriptors(); + // Ignore valid attributes + if ( + topic.Attributes.Contains(attribute.Key) && + !String.IsNullOrEmpty(topic.Attributes.GetValue(attribute.Key, null, false, false)) + ) { + continue; + }; + + // Ignore associations + if (attribute.ModelType is ModelType.Relationship or ModelType.NestedTopic or ModelType.Reference) { + continue; } - else if (topic is ContentTypeDescriptor descriptor) { - descriptor.ResetAttributeDescriptors(); + + attributes.Add(attribute); + + } + + /*-------------------------------------------------------------------------------------------------------------------------- + | Get arbitrary attributes + >------------------------------------------------------------------------------------------------------------------------- + | ###HACK JJC20200502: Arbitrary attributes are those that don't map back to the scheme. These aren't picked up by the + | AttributeDescriptors check above. This means there's no way to programmatically delete arbitrary (or orphaned) + | attributes. To mitigate this, any null or empty attribute values should be included. By definition, though, arbitrary + | attributes don't have corresponding AttributeDescriptors. To mitigate this, an ad hoc AttributeDescriptor object will be + | created for each empty AttributeDescriptor. + \-------------------------------------------------------------------------------------------------------------------------*/ + var attributeKeys = topic.Attributes + .Where(a => String.IsNullOrEmpty(a.Value)) + .Select(a => a.Key) + .Union(topic.Attributes.DeletedItems); + foreach (var attributeKey in attributeKeys) { + if (!attributes.Contains(attributeKey)) { + attributes.Add((AttributeDescriptor)TopicFactory.Create(attributeKey, "TextAttributeDescriptor")); } } - } //Class -} //Namespace \ No newline at end of file + /*-------------------------------------------------------------------------------------------------------------------------- + | Return values + \-------------------------------------------------------------------------------------------------------------------------*/ + return attributes; + + } + + /*============================================================================================================================ + | METHOD: IS ATTRIBUTE DESCRIPTOR? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Given a , determines if it derives from and is associated with + /// a . + /// + /// The to evaluate as an . + private static bool IsAttributeDescriptor(Topic topic) => + topic is AttributeDescriptor and { Parent: { Key: "Attributes", Parent: ContentTypeDescriptor } }; + + /*============================================================================================================================ + | METHOD: IS EXTENDED ATTRIBUTE MISMATCH? + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not there's a mismatch between the and the + /// . + /// + /// + /// + /// The determines where an attribute should be stored; the + /// determines where an attribute was stored. If these two + /// values are in conflict, that suggests the coniguration for has + /// changed since the attribute value was last saved. In that case, it should be treated as even though its value hasn't changed to ensure that its storage location is updated. + /// + /// + /// If cannot be found then the is arbitrary attribute + /// not mapped to the schema. In that case, its storage location is dynamically determined based on its length, and thus + /// it should only change locations when it . Otherwise, its length will remain + /// the same, and thus the storage location should remain unchanged. + /// + /// + /// The source , if available. + /// The target . + /// + private static bool IsExtendedAttributeMismatch(AttributeDescriptor? attributeDescriptor, AttributeRecord attributeValue) => + attributeDescriptor is not null && + attributeValue.IsExtendedAttribute is not null && + attributeDescriptor.IsExtendedAttribute != attributeValue.IsExtendedAttribute; + + /*============================================================================================================================ + | METHOD: RESET ATTRIBUTE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Assuming a topic is either a or an , will + /// reset the cached s on the associated and all + /// children. + /// + /// + /// Each has a collection + /// which includes not only the s associated with that , but also any s from any parent s in the topic graph. This reflects the fact that attributes are inherited from parent + /// content types. As a result, however, when an is added or removed, or a is moved to a new parent, this cache should be reset on the associated and all descendent s to ensure the change is + /// reflected. + /// + /// The to evaluate as an . + private static void ResetAttributeDescriptors(Topic topic) { + if (IsAttributeDescriptor(topic)) { + ((ContentTypeDescriptor)topic.Parent!.Parent!).ResetAttributeDescriptors(); + } + else if (topic is ContentTypeDescriptor descriptor) { + descriptor.ResetAttributeDescriptors(); + } + } + +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/TopicRepositoryDecorator.cs b/OnTopic/Repositories/TopicRepositoryDecorator.cs index 9a6a2416..9665d056 100644 --- a/OnTopic/Repositories/TopicRepositoryDecorator.cs +++ b/OnTopic/Repositories/TopicRepositoryDecorator.cs @@ -5,125 +5,124 @@ \=============================================================================================================================*/ using OnTopic.Metadata; -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC REPOSITORY DECORATOR +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// Defines a base abstract class for establishing a decorator of an . +/// +/// +/// Decorators allow implementors to operate off of an underlying version of an , while +/// intercepting calls in order to extend their functionality. They do this by establishing passthrough members to each of +/// the underlying members. The offers a base class for implementing decorators by +/// accepting a via its constructor, and then wiring up each of the members as a passthrough. +/// It also subscribes to the underlying 's events so that they will correctly bubble up +/// through the decorator. This way, derived decorators must only implement the specific methods they wish to override, and +/// can leave everything else as is. +/// +[ExcludeFromCodeCoverage] +public abstract class TopicRepositoryDecorator : ObservableTopicRepository { /*============================================================================================================================ - | CLASS: TOPIC REPOSITORY DECORATOR + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// Defines a base abstract class for establishing a decorator of an . + /// Instantiates a new instance of the with a dependency on an underlying in order to provide necessary data access. /// - /// - /// Decorators allow implementors to operate off of an underlying version of an , while - /// intercepting calls in order to extend their functionality. They do this by establishing passthrough members to each of - /// the underlying members. The offers a base class for implementing decorators by - /// accepting a via its constructor, and then wiring up each of the members as a passthrough. - /// It also subscribes to the underlying 's events so that they will correctly bubble up - /// through the decorator. This way, derived decorators must only implement the specific methods they wish to override, and - /// can leave everything else as is. - /// - [ExcludeFromCodeCoverage] - public abstract class TopicRepositoryDecorator : ObservableTopicRepository { - - /*========================================================================================================================== - | CONSTRUCTOR + /// + /// A concrete instance of an , which will be used for data access. + /// + /// A new instance of the . + protected TopicRepositoryDecorator(ITopicRepository topicRepository) : base() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Instantiates a new instance of the with a dependency on an underlying in order to provide necessary data access. - /// - /// - /// A concrete instance of an , which will be used for data access. - /// - /// A new instance of the . - protected TopicRepositoryDecorator(ITopicRepository topicRepository) : base() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topicRepository, "A concrete implementation of an ITopicRepository is required."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set values locally - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicRepository = topicRepository; - - /*------------------------------------------------------------------------------------------------------------------------ - | Subscribe to underlying events - \-----------------------------------------------------------------------------------------------------------------------*/ - TopicRepository.TopicLoaded += (object sender, TopicLoadEventArgs args) => OnTopicLoaded(args); - TopicRepository.TopicSaved += (object sender, TopicSaveEventArgs args) => OnTopicSaved(args); - TopicRepository.TopicDeleted += (object sender, TopicEventArgs args) => OnTopicDeleted(args); - TopicRepository.TopicMoved += (object sender, TopicMoveEventArgs args) => OnTopicMoved(args); - TopicRepository.TopicRenamed += (object sender, TopicRenameEventArgs args) => OnTopicRenamed(args); - - } - - /*========================================================================================================================== - | DATA PROVIDER - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides access to the underlying that this decorates. - /// - protected ITopicRepository TopicRepository { get; set; } + Contract.Requires(topicRepository, "A concrete implementation of an ITopicRepository is required."); - /*========================================================================================================================== - | GET CONTENT TYPE DESCRIPTORS + /*-------------------------------------------------------------------------------------------------------------------------- + | Set values locally \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override ContentTypeDescriptorCollection GetContentTypeDescriptors() => TopicRepository.GetContentTypeDescriptors(); + TopicRepository = topicRepository; - /*========================================================================================================================== - | METHOD: LOAD + /*-------------------------------------------------------------------------------------------------------------------------- + | Subscribe to underlying events \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override Topic? Load() => Load(-1); + TopicRepository.TopicLoaded += (object? sender, TopicLoadEventArgs args) => OnTopicLoaded(args); + TopicRepository.TopicSaved += (object? sender, TopicSaveEventArgs args) => OnTopicSaved(args); + TopicRepository.TopicDeleted += (object? sender, TopicEventArgs args) => OnTopicDeleted(args); + TopicRepository.TopicMoved += (object? sender, TopicMoveEventArgs args) => OnTopicMoved(args); + TopicRepository.TopicRenamed += (object? sender, TopicRenameEventArgs args) => OnTopicRenamed(args); - /// - public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) => - TopicRepository.Load(topicId, referenceTopic, isRecursive); + } - /// - public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) => - TopicRepository.Load(uniqueKey, referenceTopic, isRecursive); + /*============================================================================================================================ + | DATA PROVIDER + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides access to the underlying that this decorates. + /// + protected ITopicRepository TopicRepository { get; set; } - /// - public override Topic? Load(Topic topic, DateTime version) - => TopicRepository.Load(topic, version); + /*============================================================================================================================ + | GET CONTENT TYPE DESCRIPTORS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override ContentTypeDescriptorCollection GetContentTypeDescriptors() => TopicRepository.GetContentTypeDescriptors(); - /// - public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) => - TopicRepository.Load(topicId, version, referenceTopic); + /*============================================================================================================================ + | METHOD: LOAD + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override Topic? Load() => Load(-1); - /*========================================================================================================================== - | METHOD: REFRESH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Refresh(Topic referenceTopic, DateTime since) => TopicRepository.Refresh(referenceTopic, since); + /// + public override Topic? Load(int topicId, Topic? referenceTopic = null, bool isRecursive = true) => + TopicRepository.Load(topicId, referenceTopic, isRecursive); - /*========================================================================================================================== - | METHOD: ROLLBACK - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Rollback(Topic topic, DateTime version) => TopicRepository.Rollback(topic, version); + /// + public override Topic? Load(string uniqueKey, Topic? referenceTopic = null, bool isRecursive = true) => + TopicRepository.Load(uniqueKey, referenceTopic, isRecursive); - /*========================================================================================================================== - | METHOD: SAVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Save(Topic topic, bool isRecursive = false) => TopicRepository.Save(topic, isRecursive); + /// + public override Topic? Load(Topic topic, DateTime version) + => TopicRepository.Load(topic, version); - /*========================================================================================================================== - | METHOD: MOVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Move(Topic topic, Topic target, Topic? sibling = null) => TopicRepository.Move(topic, target, sibling); + /// + public override Topic? Load(int topicId, DateTime version, Topic? referenceTopic = null) => + TopicRepository.Load(topicId, version, referenceTopic); - /*========================================================================================================================== - | METHOD: DELETE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - public override void Delete(Topic topic, bool isRecursive = false) => TopicRepository.Delete(topic, isRecursive); + /*============================================================================================================================ + | METHOD: REFRESH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Refresh(Topic referenceTopic, DateTime since) => TopicRepository.Refresh(referenceTopic, since); + + /*============================================================================================================================ + | METHOD: ROLLBACK + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Rollback(Topic topic, DateTime version) => TopicRepository.Rollback(topic, version); + + /*============================================================================================================================ + | METHOD: SAVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Save(Topic topic, bool isRecursive = false) => TopicRepository.Save(topic, isRecursive); + + /*============================================================================================================================ + | METHOD: MOVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Move(Topic topic, Topic target, Topic? sibling = null) => TopicRepository.Move(topic, target, sibling); + + /*============================================================================================================================ + | METHOD: DELETE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + public override void Delete(Topic topic, bool isRecursive = false) => TopicRepository.Delete(topic, isRecursive); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_eventArgs/TopicEventArgs.cs b/OnTopic/Repositories/_eventArgs/TopicEventArgs.cs index 697ba7cc..8179a751 100644 --- a/OnTopic/Repositories/_eventArgs/TopicEventArgs.cs +++ b/OnTopic/Repositories/_eventArgs/TopicEventArgs.cs @@ -4,61 +4,60 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC EVENT ARGUMENTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The class defines an event argument type shared among +/// events. It contains the being operated against. +/// +/// +/// All events share at least one shared element: the being operated +/// against. Some, such as the , only relate to that information. Others, +/// such as , need additional information, and thus offer derived classes, such as +/// , to capture additional information. +/// +public class TopicEventArgs : EventArgs { /*============================================================================================================================ - | CLASS: TOPIC EVENT ARGUMENTS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The class defines an event argument type shared among - /// events. It contains the being operated against. + /// Initializes a new instance of the class. /// - /// - /// All events share at least one shared element: the being operated - /// against. Some, such as the , only relate to that information. Others, - /// such as , need additional information, and thus offer derived classes, such as - /// , to capture additional information. - /// - public class TopicEventArgs : EventArgs { + /// The being operated against. + /// Whether or not descendants of the were also loaded. + public TopicEventArgs(Topic topic, bool isRecursive = true) : base() { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Vaidate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class. - /// - /// The being operated against. - /// Whether or not descendants of the were also loaded. - public TopicEventArgs(Topic topic, bool isRecursive = true) : base() { + Contract.Requires(topic, nameof(topic)); - /*------------------------------------------------------------------------------------------------------------------------ - | Vaidate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(topic, nameof(topic)); - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Topic = topic; - IsRecursive = isRecursive; + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize properties + \-------------------------------------------------------------------------------------------------------------------------*/ + Topic = topic; + IsRecursive = isRecursive; - } + } - /*========================================================================================================================== - | PROPERTY: TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Getter that returns the Topic object associated with the event - /// - public Topic Topic { get; set; } + /*============================================================================================================================ + | PROPERTY: TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Getter that returns the Topic object associated with the event + /// + public Topic Topic { get; set; } - /*========================================================================================================================== - | PROPERTY: IS RECURSIVE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the descendents of the are also impacted by this operation. - /// - public bool IsRecursive { get; set; } + /*============================================================================================================================ + | PROPERTY: IS RECURSIVE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the descendents of the are also impacted by this operation. + /// + public bool IsRecursive { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_eventArgs/TopicLoadEventArgs.cs b/OnTopic/Repositories/_eventArgs/TopicLoadEventArgs.cs index 6433369e..f0b4fc93 100644 --- a/OnTopic/Repositories/_eventArgs/TopicLoadEventArgs.cs +++ b/OnTopic/Repositories/_eventArgs/TopicLoadEventArgs.cs @@ -4,42 +4,41 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC LOAD EVENT ARGUMENTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The object defines an event argument type specific to load events. +/// +public class TopicLoadEventArgs : TopicEventArgs { /*============================================================================================================================ - | CLASS: TOPIC LOAD EVENT ARGUMENTS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The object defines an event argument type specific to load events. + /// The object defines the event arguments relevant to a operation and its overloads. /// - public class TopicLoadEventArgs : TopicEventArgs { + /// The object associated with the rename event. + /// Whether or not descendants of the were also loaded. + /// If a specific version was loaded, specified that version. + public TopicLoadEventArgs(Topic topic, bool isRecursive, DateTime? version = null): base(topic, isRecursive) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The object defines the event arguments relevant to a operation and its overloads. - /// - /// The object associated with the rename event. - /// Whether or not descendants of the were also loaded. - /// If a specific version was loaded, specified that version. - public TopicLoadEventArgs(Topic topic, bool isRecursive, DateTime? version = null): base(topic, isRecursive) { + Version = version; - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Version = version; + } - } - - /*========================================================================================================================== - | PROPERTY: VERSION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the specific version of the that has been loaded. - /// - public DateTime? Version { get; set; } + /*============================================================================================================================ + | PROPERTY: VERSION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the specific version of the that has been loaded. + /// + public DateTime? Version { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_eventArgs/TopicMoveEventArgs.cs b/OnTopic/Repositories/_eventArgs/TopicMoveEventArgs.cs index 274f38d6..7f85faec 100644 --- a/OnTopic/Repositories/_eventArgs/TopicMoveEventArgs.cs +++ b/OnTopic/Repositories/_eventArgs/TopicMoveEventArgs.cs @@ -4,84 +4,83 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC MOVE EVENT ARGUMENTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The object defines an event arguments relevant to a operation. +/// +/// +/// Allows tracking of the source and destination topics. +/// +public class TopicMoveEventArgs : TopicEventArgs { /*============================================================================================================================ - | CLASS: TOPIC MOVE EVENT ARGUMENTS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The object defines an event arguments relevant to a operation. + /// Initializes a new instance of the class and sets the and properties based on the specified objects. /// - /// - /// Allows tracking of the source and destination topics. - /// - public class TopicMoveEventArgs : TopicEventArgs { + /// The object being moved. + /// The original of the . + /// The new of the . + /// The optional the will be moved after. + /// + /// is not null + /// + /// + /// is not null + /// + /// + /// != + /// + public TopicMoveEventArgs(Topic topic, Topic? source, Topic target, Topic? sibling = null): base(topic, true) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Vaidate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of the class and sets the and properties based on the specified objects. - /// - /// The object being moved. - /// The original of the . - /// The new of the . - /// The optional the will be moved after. - /// - /// is not null - /// - /// - /// is not null - /// - /// - /// != - /// - public TopicMoveEventArgs(Topic topic, Topic? source, Topic target, Topic? sibling = null): base(topic, true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Vaidate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(target, "target"); - Contract.Requires(topic != target, "The topic cannot be its own parent."); - Contract.Requires(topic != source, "The topic cannot be its own parent."); - Contract.Requires(topic != sibling, "The topic cannot be moved next to itself."); + Contract.Requires(target, "target"); + Contract.Requires(topic != target, "The topic cannot be its own parent."); + Contract.Requires(topic != source, "The topic cannot be its own parent."); + Contract.Requires(topic != sibling, "The topic cannot be moved next to itself."); - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Source = source; - Target = target; - Sibling = sibling; + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize properties + \-------------------------------------------------------------------------------------------------------------------------*/ + Source = source; + Target = target; + Sibling = sibling; - } + } - /*========================================================================================================================== - | PROPERTY: SOURCE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the new parent that the is being moved from. - /// - public Topic? Source { get; set; } + /*============================================================================================================================ + | PROPERTY: SOURCE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the new parent that the is being moved from. + /// + public Topic? Source { get; set; } - /*========================================================================================================================== - | PROPERTY: TARGET - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the new parent that the is being moved to. - /// - public Topic Target { get; set; } + /*============================================================================================================================ + | PROPERTY: TARGET + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the new parent that the is being moved to. + /// + public Topic Target { get; set; } - /*========================================================================================================================== - | PROPERTY: SIBLING - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the sibling that the is being moved after, if specified. - /// - public Topic? Sibling { get; set; } + /*============================================================================================================================ + | PROPERTY: SIBLING + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the sibling that the is being moved after, if specified. + /// + public Topic? Sibling { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_eventArgs/TopicRenameEventArgs.cs b/OnTopic/Repositories/_eventArgs/TopicRenameEventArgs.cs index b1fc5a81..f36543f5 100644 --- a/OnTopic/Repositories/_eventArgs/TopicRenameEventArgs.cs +++ b/OnTopic/Repositories/_eventArgs/TopicRenameEventArgs.cs @@ -4,58 +4,57 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC RENAME EVENT ARGUMENTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The RenameEventArgs object defines an event argument type specific to rename events. +/// +public class TopicRenameEventArgs : TopicEventArgs { /*============================================================================================================================ - | CLASS: TOPIC RENAME EVENT ARGUMENTS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The RenameEventArgs object defines an event argument type specific to rename events. + /// The object defines the event arguments relevant to a operation where the has changed. /// - public class TopicRenameEventArgs : TopicEventArgs { + /// The object associated with the rename event. + /// The original key of the prior to being renamed. + /// The new key of the after being renamed. + public TopicRenameEventArgs(Topic topic, string originalKey, string newKey): base(topic, true) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Vaidate parameters \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The object defines the event arguments relevant to a operation where the has changed. - /// - /// The object associated with the rename event. - /// The original key of the prior to being renamed. - /// The new key of the after being renamed. - public TopicRenameEventArgs(Topic topic, string originalKey, string newKey): base(topic, true) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Vaidate parameters - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(originalKey, nameof(originalKey)); - Contract.Requires(newKey, nameof(newKey)); - Contract.Requires(originalKey != newKey, "The new key cannot be the same as the old key."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize properties - \-----------------------------------------------------------------------------------------------------------------------*/ - OriginalKey = originalKey; - NewKey = newKey; - - } - - /*========================================================================================================================== - | PROPERTY: ORIGINAL KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the original of the that is being renamed. - /// - public string OriginalKey { get; set; } + Contract.Requires(originalKey, nameof(originalKey)); + Contract.Requires(newKey, nameof(newKey)); + Contract.Requires(originalKey != newKey, "The new key cannot be the same as the old key."); - /*========================================================================================================================== - | PROPERTY: NEW KEY + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the new of the that is being renamed. - /// - public string NewKey { get; set; } + OriginalKey = originalKey; + NewKey = newKey; + + } + + /*============================================================================================================================ + | PROPERTY: ORIGINAL KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the original of the that is being renamed. + /// + public string OriginalKey { get; set; } + + /*============================================================================================================================ + | PROPERTY: NEW KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the new of the that is being renamed. + /// + public string NewKey { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_eventArgs/TopicSaveEventArgs.cs b/OnTopic/Repositories/_eventArgs/TopicSaveEventArgs.cs index 2f3f6827..73f251aa 100644 --- a/OnTopic/Repositories/_eventArgs/TopicSaveEventArgs.cs +++ b/OnTopic/Repositories/_eventArgs/TopicSaveEventArgs.cs @@ -4,43 +4,42 @@ | Project Topics Library \=============================================================================================================================*/ -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC SAVE EVENT ARGUMENTS +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The object defines an event argument type specific to save events. +/// +public class TopicSaveEventArgs : TopicEventArgs { /*============================================================================================================================ - | CLASS: TOPIC SAVE EVENT ARGUMENTS + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The object defines an event argument type specific to save events. + /// The object defines the event arguments relevant to a operation. /// - public class TopicSaveEventArgs : TopicEventArgs { + /// The object associated with the rename event. + /// Whether or not descendants of the were also saved. + /// Whether or not this was a newly created . + public TopicSaveEventArgs(Topic topic, bool isRecursive, bool isNew): base(topic, isRecursive) { - /*========================================================================================================================== - | CONSTRUCTOR + /*-------------------------------------------------------------------------------------------------------------------------- + | Initialize properties \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// The object defines the event arguments relevant to a operation. - /// - /// The object associated with the rename event. - /// Whether or not descendants of the were also saved. - /// Whether or not this was a newly created . - public TopicSaveEventArgs(Topic topic, bool isRecursive, bool isNew): base(topic, isRecursive) { + IsNew = isNew; - /*------------------------------------------------------------------------------------------------------------------------ - | Initialize properties - \-----------------------------------------------------------------------------------------------------------------------*/ - IsNew = isNew; + } - } - - /*========================================================================================================================== - | PROPERTY: IS NEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether the was newly created, or if it was an existing that has been updated. - /// - public bool IsNew { get; set; } + /*============================================================================================================================ + | PROPERTY: IS NEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether the was newly created, or if it was an existing that has been updated. + /// + public bool IsNew { get; set; } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_exceptions/ReferentialIntegrityException.cs b/OnTopic/Repositories/_exceptions/ReferentialIntegrityException.cs index 631cc9da..accb963a 100644 --- a/OnTopic/Repositories/_exceptions/ReferentialIntegrityException.cs +++ b/OnTopic/Repositories/_exceptions/ReferentialIntegrityException.cs @@ -3,58 +3,44 @@ | Client Ignia, LLC | Project Topics Library \=============================================================================================================================*/ -using System.Runtime.Serialization; +namespace OnTopic.Repositories; -namespace OnTopic.Repositories { +/*============================================================================================================================== +| CLASS: REFERENTIAL INTEGRITY EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The will be thrown when an operation violates the referential integrity of +/// the underlying persistence layer. +/// +/// +/// Generally, the will occur when a is being +/// deleted, but the topic or one of its descendents is the of another . +/// In that case, deleting the topic will violate the referential integrity of the target topic. +/// +[ExcludeFromCodeCoverage] +public class ReferentialIntegrityException: TopicRepositoryException { /*============================================================================================================================ - | CLASS: REFERENTIAL INTEGRITY EXCEPTION + | CONSTRUCTOR: REFERENTIAL INTEGRITY EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The will be thrown when an operation violates the referential integrity of - /// the underlying persistence layer. + /// Initializes a new instance. /// - /// - /// Generally, the will occur when a is being - /// deleted, but the topic or one of its descendents is the of another . - /// In that case, deleting the topic will violate the referential integrity of the target topic. - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class ReferentialIntegrityException: TopicRepositoryException { + public ReferentialIntegrityException() : base() { } - /*========================================================================================================================== - | CONSTRUCTOR: REFERENTIAL INTEGRITY EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance. - /// - public ReferentialIntegrityException() : base() { } - - /// - /// Initializes a new instance based on a . - /// - /// The error message to associate with the exception. - public ReferentialIntegrityException(string message) : base(message) { } - - /// - /// Initializes a new instance based on a . - /// - /// The error message to associate with the exception. - /// The reference to the original, underlying exception. - public ReferentialIntegrityException(string message, Exception innerException) : base(message, innerException) { } + /// + /// Initializes a new instance based on a . + /// + /// The error message to associate with the exception. + public ReferentialIntegrityException(string message) : base(message) { } - /// - /// Instantiates a new instance for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected ReferentialIntegrityException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Initializes a new instance based on a . + /// + /// The error message to associate with the exception. + /// The reference to the original, underlying exception. + public ReferentialIntegrityException(string message, Exception innerException) : base(message, innerException) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_exceptions/TopicNotFoundException.cs b/OnTopic/Repositories/_exceptions/TopicNotFoundException.cs index 741eeba6..50c18add 100644 --- a/OnTopic/Repositories/_exceptions/TopicNotFoundException.cs +++ b/OnTopic/Repositories/_exceptions/TopicNotFoundException.cs @@ -4,73 +4,60 @@ | Project Topics Library \=============================================================================================================================*/ using System.Data.Common; -using System.Runtime.Serialization; -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC NOT FOUND EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The will be thrown when a topic is requested from the repository, but one cannot be +/// found and there is not a logical fallback. +/// +/// +/// As the derives from both and , it retains compatability with previous exception handling, while offering callers the option of +/// capturing a more specific error for this individual use case. +/// +[ExcludeFromCodeCoverage] +public class TopicNotFoundException: TopicRepositoryException { /*============================================================================================================================ - | CLASS: TOPIC NOT FOUND EXCEPTION + | CONSTRUCTOR: TOPIC NOT FOUND EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The will be thrown when a topic is requested from the repository, but one cannot be - /// found and there is not a logical fallback. + /// Initializes a new instance. /// - /// - /// As the derives from both and , it retains compatability with previous exception handling, while offering callers the option of - /// capturing a more specific error for this individual use case. - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class TopicNotFoundException: TopicRepositoryException { + public TopicNotFoundException() : base() { } - /*========================================================================================================================== - | CONSTRUCTOR: TOPIC NOT FOUND EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance. - /// - public TopicNotFoundException() : base() { } - - /// - /// Initializes a new instance based on a missing topic ID. - /// - /// The requested which cannot be found. - public TopicNotFoundException(int topicId): - base($"The topic {topicId} cannot be found in the repository.") { } - - /// - /// Initializes a new instance based on a missing topic ID. - /// - /// The requested which cannot be found. - /// The reference to the original, underlying exception. - public TopicNotFoundException(int topicId, Exception innerException): - base($"The topic {topicId} cannot be found in the repository.", innerException) { } + /// + /// Initializes a new instance based on a missing topic ID. + /// + /// The requested which cannot be found. + public TopicNotFoundException(int topicId): + base($"The topic {topicId} cannot be found in the repository.") { } - /// - /// Initializes a new instance based on a missing topic key. - /// - /// The requests which cannot be found. - public TopicNotFoundException(string? topicKey): - base($"The topic {topicKey} cannot be found in the repository.") { } + /// + /// Initializes a new instance based on a missing topic ID. + /// + /// The requested which cannot be found. + /// The reference to the original, underlying exception. + public TopicNotFoundException(int topicId, Exception innerException): + base($"The topic {topicId} cannot be found in the repository.", innerException) { } - /// - /// Initializes a new instance based on a missing topic key. - /// - /// The requests which cannot be found. - /// The reference to the original, underlying exception. - public TopicNotFoundException(string? topicKey, Exception innerException): - base($"The topic {topicKey} cannot be found in the repository.", innerException) { } + /// + /// Initializes a new instance based on a missing topic key. + /// + /// The requests which cannot be found. + public TopicNotFoundException(string? topicKey): + base($"The topic {topicKey} cannot be found in the repository.") { } - /// - /// Instantiates a new instance for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected TopicNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Initializes a new instance based on a missing topic key. + /// + /// The requests which cannot be found. + /// The reference to the original, underlying exception. + public TopicNotFoundException(string? topicKey, Exception innerException): + base($"The topic {topicKey} cannot be found in the repository.", innerException) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Repositories/_exceptions/TopicRepositoryException.cs b/OnTopic/Repositories/_exceptions/TopicRepositoryException.cs index d14f8a84..933bffba 100644 --- a/OnTopic/Repositories/_exceptions/TopicRepositoryException.cs +++ b/OnTopic/Repositories/_exceptions/TopicRepositoryException.cs @@ -4,58 +4,45 @@ | Project Topics Library \=============================================================================================================================*/ using System.Data.Common; -using System.Runtime.Serialization; -namespace OnTopic.Repositories { +namespace OnTopic.Repositories; + +/*============================================================================================================================== +| CLASS: TOPIC REPOSITORY EXCEPTION +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The provides a general exception that can be thrown for any persistence errors +/// that arise from concrete implementations. +/// +/// +/// Microsoft provides a set of classes, such as SqlException, which are specific to their +/// target implementations. Since , however, is intended to be database agnostic, none of +/// these are appropriate to catch when implementing . Instead, the provides a database agnostic version of an exception that can provide a wrapper around +/// any of these more concrete exceptions. +/// +[ExcludeFromCodeCoverage] +public class TopicRepositoryException : DbException { /*============================================================================================================================ - | CLASS: TOPIC REPOSITORY EXCEPTION + | CONSTRUCTOR: TOPIC REPOSITORY EXCEPTION \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The provides a general exception that can be thrown for any persistence errors - /// that arise from concrete implementations. + /// Initializes a new instance. /// - /// - /// Microsoft provides a set of classes, such as SqlException, which are specific to their - /// target implementations. Since , however, is intended to be database agnostic, none of - /// these are appropriate to catch when implementing . Instead, the provides a database agnostic version of an exception that can provide a wrapper around - /// any of these more concrete exceptions. - /// - [Serializable] - [ExcludeFromCodeCoverage] - public class TopicRepositoryException : DbException { - - /*========================================================================================================================== - | CONSTRUCTOR: TOPIC REPOSITORY EXCEPTION - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance. - /// - public TopicRepositoryException() : base() { } + public TopicRepositoryException() : base() { } - /// - /// Initializes a new instance with a specific error message. - /// - /// The message to display for this exception. - public TopicRepositoryException(string message) : base(message) { } - - /// - /// Initializes a new instance with a specific error message and nested exception. - /// - /// The message to display for this exception. - /// The reference to the original, underlying exception. - public TopicRepositoryException(string message, Exception innerException) : base(message, innerException) { } + /// + /// Initializes a new instance with a specific error message. + /// + /// The message to display for this exception. + public TopicRepositoryException(string message) : base(message) { } - /// - /// Instantiates a new instance for serialization. - /// - /// A instance with details about the serialization requirements. - /// A instance with details about the request context. - /// A new instance. - protected TopicRepositoryException(SerializationInfo info, StreamingContext context) : base(info, context) { - Contract.Requires(info); - } + /// + /// Initializes a new instance with a specific error message and nested exception. + /// + /// The message to display for this exception. + /// The reference to the original, underlying exception. + public TopicRepositoryException(string message, Exception innerException) : base(message, innerException) { } - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file diff --git a/OnTopic/Topic.cs b/OnTopic/Topic.cs index 0a958bcf..2bb751af 100644 --- a/OnTopic/Topic.cs +++ b/OnTopic/Topic.cs @@ -4,845 +4,845 @@ | Project Topics Library \=============================================================================================================================*/ using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using OnTopic.Collections; using OnTopic.Collections.Specialized; using OnTopic.Metadata; using OnTopic.Associations; -namespace OnTopic { +namespace OnTopic; + +/*============================================================================================================================== +| CLASS: TOPIC +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// The Topic object is a simple container for a particular node in the topic hierarchy. It contains the metadata associated +/// with the particular node, a list of children, etc. +/// +public class Topic: ITrackDirtyKeys { + + /*============================================================================================================================ + | PRIVATE VARIABLES + \---------------------------------------------------------------------------------------------------------------------------*/ + private string _key; + private string _contentType; + private string? _originalKey; + private Topic? _parent; + readonly DirtyKeyCollection _dirtyKeys = new(); /*============================================================================================================================ - | CLASS: TOPIC + | CONSTRUCTOR \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// The Topic object is a simple container for a particular node in the topic hierarchy. It contains the metadata associated - /// with the particular node, a list of children, etc. + /// Initializes a new instance of a class with a , , and, + /// optionally, , . /// - public class Topic: ITrackDirtyKeys { - - /*========================================================================================================================== - | PRIVATE VARIABLES + /// + /// By default, when creating new attributes, the s for both and will be set to , which is required in order to correctly save new + /// topics to the database. When the parameter is set, however, the property is set to falseon and , as it is assumed these + /// are being set to the same values currently used in the persistence store. + /// + /// A string representing the key for the new topic instance. + /// A string representing the key of the target content type. + /// The unique identifier assigned by the data store for an existing topic. + /// Optional topic to set as the new topic's parent. + /// + /// Thrown when the class representing the content type is found, but doesn't derive from . + /// + /// A strongly-typed instance of the class based on the target content type. + public Topic(string key, string contentType, Topic? parent = null, int id = -1) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set collections \-------------------------------------------------------------------------------------------------------------------------*/ - private string _key; - private string _contentType; - private int _id = -1; - private string? _originalKey; - private Topic? _parent; - readonly DirtyKeyCollection _dirtyKeys = new(); - - /*========================================================================================================================== - | CONSTRUCTOR + Children = new(); + Attributes = new(this); + IncomingRelationships = new(this, true); + Relationships = new(this, false); + References = new(this); + VersionHistory = new(); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Set entity identifier, if present \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Initializes a new instance of a class with a , , and, - /// optionally, , . - /// - /// - /// By default, when creating new attributes, the s for both and will be set to , which is required in order to correctly save new - /// topics to the database. When the parameter is set, however, the property is set to falseon and , as it is assumed these - /// are being set to the same values currently used in the persistence store. - /// - /// A string representing the key for the new topic instance. - /// A string representing the key of the target content type. - /// The unique identifier assigned by the data store for an existing topic. - /// Optional topic to set as the new topic's parent. - /// - /// Thrown when the class representing the content type is found, but doesn't derive from . - /// - /// A strongly-typed instance of the class based on the target content type. - public Topic(string key, string contentType, Topic? parent = null, int id = -1) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Set collections - \-----------------------------------------------------------------------------------------------------------------------*/ - Children = new(); - Attributes = new(this); - IncomingRelationships = new(this, true); - Relationships = new(this, false); - References = new(this); - VersionHistory = new(); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set entity identifier, if present - \-----------------------------------------------------------------------------------------------------------------------*/ - if (id >= 0) { - Id = id; - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Set core properties - \-----------------------------------------------------------------------------------------------------------------------*/ - Key = key; - ContentType = contentType; + if (id >= 0) { + Id = id; + } - if (parent is not null) { - Parent = parent; - } + /*-------------------------------------------------------------------------------------------------------------------------- + | Set core properties + \-------------------------------------------------------------------------------------------------------------------------*/ + Key = key; + ContentType = contentType; - /*------------------------------------------------------------------------------------------------------------------------ - | If existing, mark clean - \-----------------------------------------------------------------------------------------------------------------------*/ - if (!IsNew) { - MarkClean(); - } + if (parent is not null) { + Parent = parent; + } + /*-------------------------------------------------------------------------------------------------------------------------- + | If existing, mark clean + \-------------------------------------------------------------------------------------------------------------------------*/ + if (!IsNew) { + MarkClean(); } - #region Core Properties + } - /*========================================================================================================================== - | PROPERTY: ID - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's integer identifier according to the data provider. - /// - /// - /// The unique identifier for the . - /// - /// - /// The value of this topic has already been set to {_id}; it cannot be changed. - /// - /// - /// value > 0 - /// - public int Id { - get => _id; - set { - Contract.Requires(value > 0, "The id is expected to be a positive value."); - if (_id > 0 && !_id.Equals(value)) { - throw new InvalidOperationException($"The value of this topic has already been set to {_id}; it cannot be changed."); - } - _id = value; + #region Core Properties + + /*============================================================================================================================ + | PROPERTY: ID + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the topic's integer identifier according to the data provider. + /// + /// + /// The unique identifier for the . + /// + /// + /// The value of this topic has already been set to {_id}; it cannot be changed. + /// + /// + /// value > 0 + /// + public int Id { + get => field; + set { + Contract.Requires(value > 0, "The id is expected to be a positive value."); + if (field > 0 && !field.Equals(value)) { + throw new InvalidOperationException($"The value of this topic has already been set to {field}; it cannot be changed."); } + field = value; } + } = -1; - /*========================================================================================================================== - | PROPERTY: PARENT - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Reference to the parent topic of this node, allowing code to traverse topics as a linked list. - /// - /// - /// The current 's parent . - /// - /// - /// While topics may be represented as a network graph via associations, they are physically stored and primarily - /// represented via a hierarchy. As such, each topic may have at most a single parent. Note that the root node will - /// have a null parent. - /// - /// - /// value is not null - /// - /// - /// value != this - /// - [DisallowNull] - public Topic? Parent { - get => _parent; - set { - if (_parent != value) { - Contract.Requires(value, "Parent cannot be explicitly set to null."); - SetParent(value, value.Children.LastOrDefault()); - } + /*============================================================================================================================ + | PROPERTY: PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Reference to the parent topic of this node, allowing code to traverse topics as a linked list. + /// + /// + /// The current 's parent . + /// + /// + /// While topics may be represented as a network graph via associations, they are physically stored and primarily + /// represented via a hierarchy. As such, each topic may have at most a single parent. Note that the root node will + /// have a null parent. + /// + /// + /// value is not null + /// + /// + /// value != this + /// + [DisallowNull] + public Topic? Parent { + get => _parent; + set { + if (_parent != value) { + Contract.Requires(value, "Parent cannot be explicitly set to null."); + SetParent(value, value.Children.LastOrDefault()); } } + } - /*========================================================================================================================== - | PROPERTY: CHILDREN - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a keyed collection of child instances associated with the current . - /// - /// - /// The children of the current . - /// - public KeyedTopicCollection Children { get; } - - /*========================================================================================================================== - | PROPERTY: CONTENT TYPE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the key name of the content type that the current topic represents. - /// - /// - /// Each topic is associated with a content type. The content type determines which attributes are displayed in the Topics - /// Editor (via the property). - /// - /// - /// The key of the current 's . - /// - public string ContentType { - get => _contentType; - [MemberNotNull(nameof(_contentType))] - set { - TopicFactory.ValidateKey(value); - if (_contentType == value) { - return; - } - else if (_contentType is not null || IsNew) { - _dirtyKeys.MarkDirty("ContentType"); - } - _contentType = value; + /*============================================================================================================================ + | PROPERTY: CHILDREN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a keyed collection of child instances associated with the current . + /// + /// + /// The children of the current . + /// + public KeyedTopicCollection Children { get; } + + /*============================================================================================================================ + | PROPERTY: CONTENT TYPE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the key name of the content type that the current topic represents. + /// + /// + /// Each topic is associated with a content type. The content type determines which attributes are displayed in the Topics + /// Editor (via the property). + /// + /// + /// The key of the current 's . + /// + public string ContentType { + get => _contentType; + [MemberNotNull(nameof(_contentType))] + set { + TopicFactory.ValidateKey(value); + if (_contentType == value) { + return; + } + else if (_contentType is not null || IsNew) { + _dirtyKeys.MarkDirty("ContentType"); } + _contentType = value; } + } - /*========================================================================================================================== - | PROPERTY: KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's Key attribute, the primary text identifier for the topic. - /// - /// - /// The current 's key, which is guaranteed to be unique among its siblings. - /// - /// - /// value is not null - /// - /// - /// !value.Contains(" ") - /// - public string Key { - get => _key; - [MemberNotNull(nameof(_key))] - set { - TopicFactory.ValidateKey(value); - if (_key == value) { - return; - } - else if (_key is not null || IsNew) { - _dirtyKeys.MarkDirty("Key"); - } - _originalKey ??= _key; - //If an established key value is changed, the parent's index must be manually updated; this won't happen automatically. - if (_originalKey is not null && !value.Equals(_key, StringComparison.OrdinalIgnoreCase) && Parent is not null) { - Parent.Children.ChangeKey(this, value); - } - _key = value; + /*============================================================================================================================ + | PROPERTY: KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the topic's Key attribute, the primary text identifier for the topic. + /// + /// + /// The current 's key, which is guaranteed to be unique among its siblings. + /// + /// + /// value is not null + /// + /// + /// !value.Contains(" ") + /// + public string Key { + get => _key; + [MemberNotNull(nameof(_key))] + set { + TopicFactory.ValidateKey(value); + if (_key == value) { + return; + } + else if (_key is not null || IsNew) { + _dirtyKeys.MarkDirty("Key"); } + _originalKey ??= _key; + //If an established key value is changed, the parent's index must be manually updated; this won't happen automatically. + if (_originalKey is not null && !value.Equals(_key, StringComparison.OrdinalIgnoreCase) && Parent is not null) { + Parent.Children.ChangeKey(this, value); + } + _key = value; } + } - /*========================================================================================================================== - | PROPERTY: ORIGINAL KEY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's original key. - /// - /// - /// The original key is automatically set by when its value is updated (assuming the original key isn't - /// already set). This is, in turn, used by the to represent the original - /// value, and thus allow the (or derived providers) from updating the data - /// store appropriately. - /// - /// - /// The key, as represented in the persistence layer. - /// - /// - /// !value?.Contains(" ")?? true - /// - internal string? OriginalKey { - get => _originalKey; - set { - TopicFactory.ValidateKey(value, true); - _originalKey = value; - } + /*============================================================================================================================ + | PROPERTY: ORIGINAL KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the topic's original key. + /// + /// + /// The original key is automatically set by when its value is updated (assuming the original key isn't + /// already set). This is, in turn, used by the to represent the original + /// value, and thus allow the (or derived providers) from updating the data + /// store appropriately. + /// + /// + /// The key, as represented in the persistence layer. + /// + /// + /// !value?.Contains(" ")?? true + /// + internal string? OriginalKey { + get => _originalKey; + set { + TopicFactory.ValidateKey(value, true); + _originalKey = value; } + } - #endregion + #endregion - #region Convenience Properties + #region Convenience Properties - /*========================================================================================================================== - | PROPERTY: VIEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the View attribute, representing the default view to be used for the topic. - /// - /// - /// This value can be set via the query string (via the TopicViewResultExecutor class), via the Accepts header - /// (also via the TopicViewResultExecutor class), on the topic itself (via this property). By default, it will - /// be set to the name of the ; e.g., if the Content Type is "Page", then the view will be - /// "Page". This will cause the TopicViewResultExecutor to look for a view at, for instance, - /// /Views/Page/Page.cshtml. - /// - /// - /// The view, as specified by the current . - /// - /// - /// !value?.Contains(" ")?? true - /// - [AttributeSetter] - public string? View { - get => - Attributes.GetValue("View", ""); - set { - TopicFactory.ValidateKey(value, true); - SetAttributeValue("View", value); - } + /*============================================================================================================================ + | PROPERTY: VIEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the View attribute, representing the default view to be used for the topic. + /// + /// + /// This value can be set via the query string (via the TopicViewResultExecutor class), via the Accepts header + /// (also via the TopicViewResultExecutor class), on the topic itself (via this property). By default, it will + /// be set to the name of the ; e.g., if the Content Type is "Page", then the view will be + /// "Page". This will cause the TopicViewResultExecutor to look for a view at, for instance, + /// /Views/Page/Page.cshtml. + /// + /// + /// The view, as specified by the current . + /// + /// + /// !value?.Contains(" ")?? true + /// + [AttributeSetter] + public string? View { + get => + Attributes.GetValue("View", ""); + set { + TopicFactory.ValidateKey(value, true); + SetAttributeValue("View", value); } + } - /*========================================================================================================================== - | PROPERTY: IS NEW - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not the current has been saved to an underlying . If not, returns true. - /// - /// - /// This property does not reflect whether the current state of the topic has been saved. It only - /// determines if the maps to an existing entity in the underlying . - /// - /// - /// true if it has been saved; otherwise, false. - /// - public bool IsNew => Id < 0; - - /*========================================================================================================================== - | PROPERTY: IS HIDDEN + /*============================================================================================================================ + | PROPERTY: IS NEW + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not the current has been saved to an underlying . If not, returns true. + /// + /// + /// This property does not reflect whether the current state of the topic has been saved. It only + /// determines if the maps to an existing entity in the underlying . + /// + /// + /// true if it has been saved; otherwise, false. + /// + public bool IsNew => Id < 0; + + /*============================================================================================================================ + | PROPERTY: IS HIDDEN + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether the current topic is hidden. + /// + /// + /// true if this instance is hidden; otherwise, false. + /// + [AttributeSetter] + public bool IsHidden { + get => Attributes.GetBoolean("IsHidden"); + set => SetAttributeValue("IsHidden", value ? "1" : "0"); + } + + /*============================================================================================================================ + | PROPERTY: IS DISABLED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets whether the current topic is disabled. + /// + /// + /// true if this instance is disabled; otherwise, false. + /// + [AttributeSetter] + [ExcludeFromCodeCoverage] + public bool IsDisabled { + get => Attributes.GetBoolean("IsDisabled"); + set => SetAttributeValue("IsDisabled", value ? "1" : "0"); + } + + /*============================================================================================================================ + | METHOD: IS VISIBLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Determines whether or not a topic should be visible based on IsHidden, IsDisabled, and an optional parameter + /// specifying whether or not to show disabled items (which may by triggered if, for example, a user is an administrator). + /// + /// + /// If an item is not marked as IsVisible, then the item will not be visible independent of whether showDisabled is set. + /// + /// Determines whether or not items marked as IsDisabled should be displayed. + /// + /// true if the is visible; otherwise, false. + /// + public bool IsVisible(bool showDisabled = false) => !IsHidden && (showDisabled || !IsDisabled); + + /*============================================================================================================================ + | PROPERTY: TITLE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the Title attribute, which represents the friendly name of the topic. + /// + /// + /// While the may not contain, for instance, spaces or symbols, there are no restrictions on what + /// characters can be used in the title. For this reason, it provides the default public value for referencing topics. If + /// the title is not set, then this property falls back to the topic's . + /// + /// + /// The current 's title. + /// + /// + /// !string.IsNullOrWhiteSpace(value) + /// + public string Title { + get => Attributes.GetValue("Title", Key); + set => SetAttributeValue("Title", value); + } + + /*============================================================================================================================ + | PROPERTY: DESCRIPTION + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the Description attribute. + /// + /// + /// The Description attribute is primarily used by the editor to display help content for an attribute topic, noting + /// how the attribute is used, what is the expected input format or value, etc. + /// + /// + /// The current 's description. + /// + /// + /// !string.IsNullOrWhiteSpace(value) + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"The Description convenience property will be removed in OnTopic Library 5.0. Use " + + $"{nameof(AttributeCollection.SetValue)} instead.", + true + )] + public string? Description { + get => Attributes.GetValue("Description"); + set => SetAttributeValue("Description", value); + } + + /*============================================================================================================================ + | PROPERTY: LAST MODIFIED + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets or sets the topic's last modified attribute. + /// + /// + /// The value is stored in the database as a string (Attribute) value, but converted to DateTime for use in the system. It + /// is important to note that the last modified attribute is not tied to the system versioning (which operates at an + /// attribute level) nor is it guaranteed to be correct for auditing purposes; for example, the author may explicitly + /// overwrite this value for various reasons (such as backdating a web page). + /// + /// + /// The date that the current was last modified. + /// + /// + /// !string.IsNullOrWhiteSpace(value.ToString()) + /// + public DateTime LastModified { + get => Attributes.GetDateTime("LastModified", VersionHistory.DefaultIfEmpty(DateTime.MinValue).LastOrDefault()); + set => SetAttributeValue("LastModified", value.ToString(CultureInfo.InvariantCulture)); + } + + #endregion + + #region Relationship and Collection Methods + + /*============================================================================================================================ + | METHOD: SET PARENT + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Changes the current while simultaneously ensuring that the sort order of the topics is + /// maintained, assuming a is set. + /// + /// + /// If no is provided, then the item is added to the beginning of the collection. If + /// the intent is to add it to the end of the collection, then set the to e.g. + /// parent.Children.LastOrDefault(). + /// + /// The to move this under. + /// The to move this to the right of. + /// parent - A descendant cannot be its own parent. + /// + /// Duplicate key when setting Parent property: the topic with the name '{Key}' already exists in the '{parent.Key}' + /// topic. + /// + public void SetParent(Topic parent, Topic? sibling = null) { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Check preconditions \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether the current topic is hidden. - /// - /// - /// true if this instance is hidden; otherwise, false. - /// - [AttributeSetter] - public bool IsHidden { - get => Attributes.GetBoolean("IsHidden"); - set => SetAttributeValue("IsHidden", value ? "1" : "0"); - } + Contract.Requires(parent, "The value for Parent must not be null."); + Contract.Requires(parent != this, "A topic cannot be its own parent."); - /*========================================================================================================================== - | PROPERTY: IS DISABLED + /*-------------------------------------------------------------------------------------------------------------------------- + | Check to ensure that the topic isn't being moved to a descendant (topics cannot be their own grandpa) \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets whether the current topic is disabled. - /// - /// - /// true if this instance is disabled; otherwise, false. - /// - [AttributeSetter] - [ExcludeFromCodeCoverage] - public bool IsDisabled { - get => Attributes.GetBoolean("IsDisabled"); - set => SetAttributeValue("IsDisabled", value ? "1" : "0"); + if (parent.GetUniqueKey().StartsWith(GetUniqueKey(), StringComparison.OrdinalIgnoreCase)) { + throw new ArgumentOutOfRangeException(nameof(parent), "A descendant cannot be its own parent."); } - /*========================================================================================================================== - | METHOD: IS VISIBLE + /*-------------------------------------------------------------------------------------------------------------------------- + | Check to ensure that the topic isn't being moved to a parent with a duplicate key \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Determines whether or not a topic should be visible based on IsHidden, IsDisabled, and an optional parameter - /// specifying whether or not to show disabled items (which may by triggered if, for example, a user is an administrator). - /// - /// - /// If an item is not marked as IsVisible, then the item will not be visible independent of whether showDisabled is set. - /// - /// Determines whether or not items marked as IsDisabled should be displayed. - /// - /// true if the is visible; otherwise, false. - /// - public bool IsVisible(bool showDisabled = false) => !IsHidden && (showDisabled || !IsDisabled); - - /*========================================================================================================================== - | PROPERTY: TITLE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Title attribute, which represents the friendly name of the topic. - /// - /// - /// While the may not contain, for instance, spaces or symbols, there are no restrictions on what - /// characters can be used in the title. For this reason, it provides the default public value for referencing topics. If - /// the title is not set, then this property falls back to the topic's . - /// - /// - /// The current 's title. - /// - /// - /// !string.IsNullOrWhiteSpace(value) - /// - public string Title { - get => Attributes.GetValue("Title", Key); - set => SetAttributeValue("Title", value); + if (parent != _parent && parent.Children.Contains(Key)) { + throw new InvalidKeyException( + $"Duplicate key when setting Parent property: the topic with the name '{Key}' already exists in the '{parent.Key}' " + + $"topic." + ); } - /*========================================================================================================================== - | PROPERTY: DESCRIPTION + /*-------------------------------------------------------------------------------------------------------------------------- + | Move topic to new location \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the Description attribute. - /// - /// - /// The Description attribute is primarily used by the editor to display help content for an attribute topic, noting - /// how the attribute is used, what is the expected input format or value, etc. - /// - /// - /// The current 's description. - /// - /// - /// !string.IsNullOrWhiteSpace(value) - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The Description convenience property will be removed in OnTopic Library 5.0. Use " + - $"{nameof(AttributeCollection.SetValue)} instead.", - true - )] - public string? Description { - get => Attributes.GetValue("Description"); - set => SetAttributeValue("Description", value); - } + _parent?.Children.Remove(Key); + var insertAt = (sibling is not null)? parent.Children.IndexOf(sibling)+1 : 0; + parent.Children.Insert(insertAt, this); + _dirtyKeys.MarkDirty("Parent"); - /*========================================================================================================================== - | PROPERTY: LAST MODIFIED + /*-------------------------------------------------------------------------------------------------------------------------- + | Set parent values \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets or sets the topic's last modified attribute. - /// - /// - /// The value is stored in the database as a string (Attribute) value, but converted to DateTime for use in the system. It - /// is important to note that the last modified attribute is not tied to the system versioning (which operates at an - /// attribute level) nor is it guaranteed to be correct for auditing purposes; for example, the author may explicitly - /// overwrite this value for various reasons (such as backdating a web page). - /// - /// - /// The date that the current was last modified. - /// - /// - /// !string.IsNullOrWhiteSpace(value.ToString()) - /// - public DateTime LastModified { - get => Attributes.GetDateTime("LastModified", VersionHistory.DefaultIfEmpty(DateTime.MinValue).LastOrDefault()); - set => SetAttributeValue("LastModified", value.ToString(CultureInfo.InvariantCulture)); + if (_parent != parent) { + _parent = parent; } - #endregion - - #region Relationship and Collection Methods + } - /*========================================================================================================================== - | METHOD: SET PARENT + /*============================================================================================================================ + | METHOD: GET UNIQUE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the full, hierarchical identifier for the topic, including parents. + /// + /// + /// The value for the UniqueKey property is a collated, colon-delimited representation of the topic and its parent(s). + /// Example: "Root:Configuration:ContentTypes:Page". + /// + /// The unique key of the current . + [SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "This walks the parent hierarchy and performs string concatenation, so it isn't appropriate as a property.")] + public string GetUniqueKey() { + + /*-------------------------------------------------------------------------------------------------------------------------- + | Crawl up tree to define uniqueKey \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Changes the current while simultaneously ensuring that the sort order of the topics is - /// maintained, assuming a is set. - /// - /// - /// If no is provided, then the item is added to the beginning of the collection. If - /// the intent is to add it to the end of the collection, then set the to e.g. - /// parent.Children.LastOrDefault(). - /// - /// The to move this under. - /// The to move this to the right of. - /// parent - A descendant cannot be its own parent. - /// - /// Duplicate key when setting Parent property: the topic with the name '{Key}' already exists in the '{parent.Key}' - /// topic. - /// - public void SetParent(Topic parent, Topic? sibling = null) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Check preconditions - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(parent, "The value for Parent must not be null."); - Contract.Requires(parent != this, "A topic cannot be its own parent."); - - /*------------------------------------------------------------------------------------------------------------------------ - | Check to ensure that the topic isn't being moved to a descendant (topics cannot be their own grandpa) - \-----------------------------------------------------------------------------------------------------------------------*/ - if (parent.GetUniqueKey().StartsWith(GetUniqueKey(), StringComparison.OrdinalIgnoreCase)) { - throw new ArgumentOutOfRangeException(nameof(parent), "A descendant cannot be its own parent."); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Check to ensure that the topic isn't being moved to a parent with a duplicate key - \-----------------------------------------------------------------------------------------------------------------------*/ - if (parent != _parent && parent.Children.Contains(Key)) { - throw new InvalidKeyException( - $"Duplicate key when setting Parent property: the topic with the name '{Key}' already exists in the '{parent.Key}' " + - $"topic." - ); - } - - /*------------------------------------------------------------------------------------------------------------------------ - | Move topic to new location - \-----------------------------------------------------------------------------------------------------------------------*/ - _parent?.Children.Remove(Key); - var insertAt = (sibling is not null)? parent.Children.IndexOf(sibling)+1 : 0; - parent.Children.Insert(insertAt, this); - _dirtyKeys.MarkDirty("Parent"); - - /*------------------------------------------------------------------------------------------------------------------------ - | Set parent values - \-----------------------------------------------------------------------------------------------------------------------*/ - if (_parent != parent) { - _parent = parent; - } + var uniqueKey = ""; + var topic = (Topic?)this; + while (topic is not null) { + if (uniqueKey.Length > 0) uniqueKey = $":{uniqueKey}"; + uniqueKey = topic.Key + uniqueKey; + topic = topic.Parent; } - /*========================================================================================================================== - | METHOD: GET UNIQUE KEY + /*-------------------------------------------------------------------------------------------------------------------------- + | Return value \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the full, hierarchical identifier for the topic, including parents. - /// - /// - /// The value for the UniqueKey property is a collated, colon-delimited representation of the topic and its parent(s). - /// Example: "Root:Configuration:ContentTypes:Page". - /// - /// The unique key of the current . - public string GetUniqueKey() { - - /*------------------------------------------------------------------------------------------------------------------------ - | Crawl up tree to define uniqueKey - \-----------------------------------------------------------------------------------------------------------------------*/ - var uniqueKey = ""; - var topic = (Topic?)this; - - while (topic is not null) { - if (uniqueKey.Length > 0) uniqueKey = $":{uniqueKey}"; - uniqueKey = topic.Key + uniqueKey; - topic = topic.Parent; - } + return uniqueKey; - /*------------------------------------------------------------------------------------------------------------------------ - | Return value - \-----------------------------------------------------------------------------------------------------------------------*/ - return uniqueKey; + } + /*============================================================================================================================ + | METHOD: GET WEB PATH + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Gets the root-relative web path of the Topic, based on an assumption that the root topic is bound to the root of the + /// site. + /// + /// + /// Note: If the topic root is not bound to the root of the site, this needs to specifically accounted for in any views + /// that reference the web path (e.g., by providing a prefix). + /// + /// The HTTP-based path to the current . + public string GetWebPath() { + var uniqueKey = GetUniqueKey() + .Replace("Root:", "/", StringComparison.Ordinal) + .Replace(":", "/", StringComparison.Ordinal) + "/"; + if (!uniqueKey.StartsWith('/')) { + uniqueKey = $"/{uniqueKey}"; } + return uniqueKey; + } - /*========================================================================================================================== - | METHOD: GET WEB PATH - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Gets the root-relative web path of the Topic, based on an assumption that the root topic is bound to the root of the - /// site. - /// - /// - /// Note: If the topic root is not bound to the root of the site, this needs to specifically accounted for in any views - /// that reference the web path (e.g., by providing a prefix). - /// - /// The HTTP-based path to the current . - public string GetWebPath() { - var uniqueKey = GetUniqueKey() - .Replace("Root:", "/", StringComparison.Ordinal) - .Replace(":", "/", StringComparison.Ordinal) + "/"; - if (!uniqueKey.StartsWith("/", StringComparison.Ordinal)) { - uniqueKey = $"/{uniqueKey}"; - } - return uniqueKey; - } + /*============================================================================================================================ + | METHOD: IS DIRTY? + \---------------------------------------------------------------------------------------------------------------------------*/ - /*========================================================================================================================== - | METHOD: IS DIRTY? - \-------------------------------------------------------------------------------------------------------------------------*/ + /// + public bool IsDirty() => IsDirty(false, false); - /// - public bool IsDirty() => IsDirty(false, false); - - /// - /// Determines if the topic is dirty, optionally checking and . - /// - /// - /// Determines if , , and should be checked. - /// - /// - /// Optionally excludes s whose keys start with LastModified. This is useful for - /// excluding the byline (LastModifiedBy) and dateline (LastModified) since these values are automatically - /// generated by e.g. the OnTopic Editor and, thus, may be irrelevant updates if no other attribute values have changed. - /// - /// - /// Returns true if the , , or, optionally, any collections have been - /// modified. - /// - public bool IsDirty(bool checkCollections, bool excludeLastModified = false) { - if (IsNew || _dirtyKeys.IsDirty()) { - return true; - } - else if (!checkCollections) { - return false; - } - else if ( - Attributes.IsDirty(excludeLastModified) || - Relationships.IsDirty() || - References.IsDirty() - ) { - return true; - } + /// + /// Determines if the topic is dirty, optionally checking and . + /// + /// + /// Determines if , , and should be checked. + /// + /// + /// Optionally excludes s whose keys start with LastModified. This is useful for + /// excluding the byline (LastModifiedBy) and dateline (LastModified) since these values are automatically + /// generated by e.g. the OnTopic Editor and, thus, may be irrelevant updates if no other attribute values have changed. + /// + /// + /// Returns true if the , , or, optionally, any collections have been + /// modified. + /// + public bool IsDirty(bool checkCollections, bool excludeLastModified = false) { + if (IsNew || _dirtyKeys.IsDirty()) { + return true; + } + else if (!checkCollections) { return false; } + else if ( + Attributes.IsDirty(excludeLastModified) || + Relationships.IsDirty() || + References.IsDirty() + ) { + return true; + } + return false; + } - /// - public bool IsDirty(string key) => IsDirty(key, false); + /// + public bool IsDirty(string key) => IsDirty(key, false); - /// - public bool IsDirty(string key, bool checkCollections) { - if (IsNew || _dirtyKeys.IsDirty(key)) { - return true; - } - else if (!checkCollections) { - return false; - } - else if ( - Attributes.IsDirty(key) || - Relationships.IsDirty(key) || - References.IsDirty(key) - ) { - return true; - } + /// + public bool IsDirty(string key, bool checkCollections) { + if (IsNew || _dirtyKeys.IsDirty(key)) { + return true; + } + else if (!checkCollections) { return false; } + else if ( + Attributes.IsDirty(key) || + Relationships.IsDirty(key) || + References.IsDirty(key) + ) { + return true; + } + return false; + } - /*========================================================================================================================== - | METHOD: MARK CLEAN - \-------------------------------------------------------------------------------------------------------------------------*/ + /*============================================================================================================================ + | METHOD: MARK CLEAN + \---------------------------------------------------------------------------------------------------------------------------*/ - /// - public void MarkClean() => MarkClean(false); - - /// - /// Resets the status of the —and, optionally, that of all collections, using - /// the parameter. - /// - /// - /// Determines if , , and should be included. - /// - /// - /// The value that the attributes were last saved. This corresponds to the . - /// - public void MarkClean(bool includeCollections, DateTime? version = null) { - if (IsNew) { - return; - } - _dirtyKeys.MarkClean(); - if (includeCollections) { - Attributes.MarkClean(version); - Relationships.MarkClean(); - References.MarkClean(); - } + /// + public void MarkClean() => MarkClean(false); + + /// + /// Resets the status of the —and, optionally, that of all collections, using + /// the parameter. + /// + /// + /// Determines if , , and should be included. + /// + /// + /// The value that the attributes were last saved. This corresponds to the . + /// + public void MarkClean(bool includeCollections, DateTime? version = null) { + if (IsNew) { + return; + } + _dirtyKeys.MarkClean(); + if (includeCollections) { + Attributes.MarkClean(version); + Relationships.MarkClean(); + References.MarkClean(); } + } - /// - public void MarkClean(string key) { - if (IsNew) { - return; - } - MarkClean(key, false); + /// + public void MarkClean(string key) { + if (IsNew) { + return; } + MarkClean(key, false); + } - /// - public void MarkClean(string key, bool includeCollections) { - if (IsNew) { - return; - } - _dirtyKeys.MarkClean(key); - if (includeCollections) { - Attributes.MarkClean(key); - Relationships.MarkClean(key); - References.MarkClean(key); - } + /// + public void MarkClean(string key, bool includeCollections) { + if (IsNew) { + return; + } + _dirtyKeys.MarkClean(key); + if (includeCollections) { + Attributes.MarkClean(key); + Relationships.MarkClean(key); + References.MarkClean(key); } + } - #endregion + #endregion - #region Relationship and Collection Properties + #region Relationship and Collection Properties - /*========================================================================================================================== - | PROPERTY: BASE TOPIC - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Reference to the topic that this topic inherits from, if available. - /// - /// - /// - /// Base topics allow attribute values to be inherited from another topic. When a is configured - /// as a BaseTopic , values from that are used when the method is unable to find a - /// local value for the attribute. - /// - /// - /// Be aware that while multiple levels of s can be configured, the method defaults to a maximum level - /// of five "hops" in order to help avoid an infinite loop. - /// - /// - /// The underlying value of the is stored as a topic reference with the of BaseTopic in . If the hasn't been - /// saved, then the reference will be established, but the BaseTopic won't be persisted to the underlying - /// repository upon . That said, when is called, the will be reevaluated - /// and, if it has subsequently been saved, and the BaseTopic will be updated accordingly. This allows in-memory - /// topic graphs to be constructed, while preventing invalid s from being persisted to the - /// underlying data storage. As a result, however, a referencing an that is - /// unsaved will need to be saved again once the has been saved, assuming it's otherwise outside - /// the scope of the original call. - /// - /// - /// The that values should be inherited from, if not otherwise available. - /// - /// value != this - /// - [ReferenceSetter] - public Topic? BaseTopic { - get => References.Contains("BaseTopic") ? References["BaseTopic"].Value : null; - set { - Contract.Requires( - value != this, - "A topic may not derive from itself." - ); - References.SetValue("BaseTopic", value); - } + /*============================================================================================================================ + | PROPERTY: BASE TOPIC + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Reference to the topic that this topic inherits from, if available. + /// + /// + /// + /// Base topics allow attribute values to be inherited from another topic. When a is configured + /// as a BaseTopic , values from that are used when the method is unable to find a + /// local value for the attribute. + /// + /// + /// Be aware that while multiple levels of s can be configured, the method defaults to a maximum level + /// of five "hops" in order to help avoid an infinite loop. + /// + /// + /// The underlying value of the is stored as a topic reference with the of BaseTopic in . If the hasn't been + /// saved, then the reference will be established, but the BaseTopic won't be persisted to the underlying + /// repository upon . That said, when is called, the will be reevaluated + /// and, if it has subsequently been saved, and the BaseTopic will be updated accordingly. This allows in-memory + /// topic graphs to be constructed, while preventing invalid s from being persisted to the + /// underlying data storage. As a result, however, a referencing an that is + /// unsaved will need to be saved again once the has been saved, assuming it's otherwise outside + /// the scope of the original call. + /// + /// + /// The that values should be inherited from, if not otherwise available. + /// + /// value != this + /// + [ReferenceSetter] + public Topic? BaseTopic { + get => References.Contains("BaseTopic") ? References["BaseTopic"].Value : null; + set { + Contract.Requires( + value != this, + "A topic may not derive from itself." + ); + References.SetValue("BaseTopic", value); } + } + + /// + [ExcludeFromCodeCoverage] + [Obsolete( + $"The DerivedTopic property has been renamed to {nameof(BaseTopic)}. Please update references.", + true + )] + public Topic? DerivedTopic { + get => BaseTopic; + set => BaseTopic = value; + } - /// - [ExcludeFromCodeCoverage] - [Obsolete( - $"The DerivedTopic property has been renamed to {nameof(BaseTopic)}. Please update references.", - true - )] - public Topic? DerivedTopic { - get => BaseTopic; - set => BaseTopic = value; - } + /*============================================================================================================================ + | PROPERTY: ATTRIBUTES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Attributes is a generic property bag for keeping track of either named or arbitrary attributes, thus providing + /// significant extensibility. + /// + /// + /// Attributes are stored via an class which, in addition to the Attribute Key and Value, + /// also track other metadata for the attribute, such as the version (via the + /// property) and whether it has been persisted to the database or not (via the + /// property). + /// + /// The current 's attributes. + public AttributeCollection Attributes { get; } - /*========================================================================================================================== - | PROPERTY: ATTRIBUTES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Attributes is a generic property bag for keeping track of either named or arbitrary attributes, thus providing - /// significant extensibility. - /// - /// - /// Attributes are stored via an class which, in addition to the Attribute Key and Value, - /// also track other metadata for the attribute, such as the version (via the - /// property) and whether it has been persisted to the database or not (via the - /// property). - /// - /// The current 's attributes. - public AttributeCollection Attributes { get; } - - /*========================================================================================================================== - | PROPERTY: RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A façade for accessing related topics based on a relationship key; can be used for tags, related topics, etc. - /// - /// - /// The relationships property exposes a with child topics representing named relationships (e.g., - /// "Related" for related topics); those child topics in turn have child topics representing references to each related - /// topic, thus allowing the topic hierarchy to be represented as a network graph. - /// - /// The current 's relationships. - public TopicRelationshipMultiMap Relationships { get; } - - /*========================================================================================================================== - | PROPERTY: REFERENCES - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A façade for accessing referenced topics based on a reference key; can be used for base topics, etc. - /// - /// - /// The references property exposes a with child topics representing named references (e.g., - /// BaseTopic for a ). - /// - /// The current 's references. - public TopicReferenceCollection References { get; } - - /*========================================================================================================================== - | PROPERTY: INCOMING RELATIONSHIPS - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// A façade for accessing related topics based on a relationship key; can be used for tags, related topics, etc. - /// - /// - /// The incoming relationships property provides a reverse index of the property, in order to - /// indicate which topics point to the current topic. This can be useful for traversing the topic tree as a network graph. - /// This is of particular use for tags, where the current topic represents a tag, and the incoming relationships - /// represents all topics associated with that tag. - /// - /// The current 's incoming relationships. - public TopicRelationshipMultiMap IncomingRelationships { get; } - - /*========================================================================================================================== - | PROPERTY: VERSION HISTORY - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Provides a collection of dates representing past versions of the topic, which can be rolled back to. - /// - /// - /// It is expected that this collection will be populated by the (or one of - /// its derived providers). - /// - /// The current 's version history. - public Collection VersionHistory { get; } - - #endregion - - #region Collection Methods - - /*========================================================================================================================== - | METHOD: SET ATTRIBUTE VALUE - \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Protected helper method that either adds a new object or updates the value of an - /// existing one, depending on whether that value already exists. - /// - /// - /// When an attribute value is set and a corresponding, writable property exists on the topic, that property will be - /// called by the . This is intended to enforce local business logic, and prevent callers - /// from introducing invalid data.To prevent a redirect loop, however, local properties need to inform the that the business logic has already been enforced. To do that, they must either call with the - /// enforceBusinessLogic flag set to false, or, if they're in a separate assembly, call this overload. - /// - /// The string identifier for the . - /// The text value for the . - /// - /// Specified whether the value should be marked as . By default, it will be marked - /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is - /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being - /// persisted to the data store on . - /// - /// - /// !String.IsNullOrWhiteSpace(key) - /// - /// - /// !String.IsNullOrWhiteSpace(value) - /// - /// - /// !value.Contains(" ") - /// - protected void SetAttributeValue(string key, string? value, bool? isDirty = null) { - Contract.Requires(!String.IsNullOrWhiteSpace(key)); - Attributes.SetValue(key, value, isDirty, false); - } + /*============================================================================================================================ + | PROPERTY: RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A façade for accessing related topics based on a relationship key; can be used for tags, related topics, etc. + /// + /// + /// The relationships property exposes a with child topics representing named relationships (e.g., + /// "Related" for related topics); those child topics in turn have child topics representing references to each related + /// topic, thus allowing the topic hierarchy to be represented as a network graph. + /// + /// The current 's relationships. + public TopicRelationshipMultiMap Relationships { get; } + + /*============================================================================================================================ + | PROPERTY: REFERENCES + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A façade for accessing referenced topics based on a reference key; can be used for base topics, etc. + /// + /// + /// The references property exposes a with child topics representing named references (e.g., + /// BaseTopic for a ). + /// + /// The current 's references. + public TopicReferenceCollection References { get; } + + /*============================================================================================================================ + | PROPERTY: INCOMING RELATIONSHIPS + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// A façade for accessing related topics based on a relationship key; can be used for tags, related topics, etc. + /// + /// + /// The incoming relationships property provides a reverse index of the property, in order to + /// indicate which topics point to the current topic. This can be useful for traversing the topic tree as a network graph. + /// This is of particular use for tags, where the current topic represents a tag, and the incoming relationships + /// represents all topics associated with that tag. + /// + /// The current 's incoming relationships. + public TopicRelationshipMultiMap IncomingRelationships { get; } + + /*============================================================================================================================ + | PROPERTY: VERSION HISTORY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a collection of dates representing past versions of the topic, which can be rolled back to. + /// + /// + /// It is expected that this collection will be populated by the (or one of + /// its derived providers). + /// + /// The current 's version history. + public Collection VersionHistory { get; } + + #endregion - #endregion + #region Collection Methods - } //Class -} //Namespace \ No newline at end of file + /*============================================================================================================================ + | METHOD: SET ATTRIBUTE VALUE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Protected helper method that either adds a new object or updates the value of an + /// existing one, depending on whether that value already exists. + /// + /// + /// When an attribute value is set and a corresponding, writable property exists on the topic, that property will be + /// called by the . This is intended to enforce local business logic, and prevent callers + /// from introducing invalid data.To prevent a redirect loop, however, local properties need to inform the that the business logic has already been enforced. To do that, they must either call with the + /// enforceBusinessLogic flag set to false, or, if they're in a separate assembly, call this overload. + /// + /// The string identifier for the . + /// The text value for the . + /// + /// Specified whether the value should be marked as . By default, it will be marked + /// as dirty if the value is new or has changed from a previous value. By setting this parameter, that behavior is + /// overwritten to accept whatever value is submitted. This can be used, for instance, to prevent an update from being + /// persisted to the data store on . + /// + /// + /// !String.IsNullOrWhiteSpace(key) + /// + /// + /// !String.IsNullOrWhiteSpace(value) + /// + /// + /// !value.Contains(" ") + /// + protected void SetAttributeValue(string key, string? value, bool? isDirty = null) { + Contract.Requires(!String.IsNullOrWhiteSpace(key)); + Attributes.SetValue(key, value, isDirty, false); + } + + #endregion + +} //Class \ No newline at end of file diff --git a/OnTopic/TopicFactory.cs b/OnTopic/TopicFactory.cs index d135f0e0..3a07819c 100644 --- a/OnTopic/TopicFactory.cs +++ b/OnTopic/TopicFactory.cs @@ -8,106 +8,114 @@ using OnTopic.Lookup; using OnTopic.Metadata; -namespace OnTopic { +namespace OnTopic; + +/*============================================================================================================================== +| CLASS: TOPIC FACTORY +\-----------------------------------------------------------------------------------------------------------------------------*/ +/// +/// A static class for centralizing logic for creating strongly-typed instances based on their content +/// type. +/// +public static partial class TopicFactory { + + /*============================================================================================================================ + | PROPERTY: TYPE LOOKUP SERVICE + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Establishes static variables for the . + /// + public static ITypeLookupService TypeLookupService { get; set; } = new DynamicTopicLookupService(); /*============================================================================================================================ - | CLASS: TOPIC FACTORY + | METHOD: CREATE \---------------------------------------------------------------------------------------------------------------------------*/ /// - /// A static class for centralizing logic for creating strongly-typed instances based on their content - /// type. + /// Factory method for creating new strongly-typed instances of the topics class, assuming a strongly-typed subclass is + /// available. Used for cases where a is being deserialized from an existing instance, as indicated + /// by the parameter. /// - public static class TopicFactory { + /// + /// When the parameter is set the property is set to + /// false on as well as on , since it is assumed these are + /// being set to the same values currently used in the persistence store. + /// + /// A string representing the key for the new topic instance. + /// A string representing the key of the target content type. + /// Optional topic to set as the new topic's parent. + /// The unique identifier assigned by the data store for an existing topic. + /// + /// Thrown when the class representing the content type is found, but doesn't derive from . + /// + /// A strongly-typed instance of the class based on the target content type. + public static Topic Create(string key, string contentType, Topic? parent = null, int id = -1) { - /*========================================================================================================================== - | PROPERTY: TYPE LOOKUP SERVICE + /*-------------------------------------------------------------------------------------------------------------------------- + | Validate input \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Establishes static variables for the . - /// - public static ITypeLookupService TypeLookupService { get; set; } = new DynamicTopicLookupService(); + Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); + Contract.Requires(!String.IsNullOrWhiteSpace(contentType), nameof(contentType)); - /*========================================================================================================================== - | METHOD: CREATE + ValidateKey(key); + ValidateKey(contentType); + + /*-------------------------------------------------------------------------------------------------------------------------- + | Determine target type \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Factory method for creating new strongly-typed instances of the topics class, assuming a strongly-typed subclass is - /// available. Used for cases where a is being deserialized from an existing instance, as indicated - /// by the parameter. - /// - /// - /// When the parameter is set the property is set to - /// false on as well as on , since it is assumed these are - /// being set to the same values currently used in the persistence store. - /// - /// A string representing the key for the new topic instance. - /// A string representing the key of the target content type. - /// Optional topic to set as the new topic's parent. - /// The unique identifier assigned by the data store for an existing topic. - /// - /// Thrown when the class representing the content type is found, but doesn't derive from . - /// - /// A strongly-typed instance of the class based on the target content type. - public static Topic Create(string key, string contentType, Topic? parent = null, int id = -1) { - - /*------------------------------------------------------------------------------------------------------------------------ - | Validate input - \-----------------------------------------------------------------------------------------------------------------------*/ - Contract.Requires(!String.IsNullOrWhiteSpace(key), nameof(key)); - Contract.Requires(!String.IsNullOrWhiteSpace(contentType), nameof(contentType)); - - ValidateKey(key); - ValidateKey(contentType); - - /*------------------------------------------------------------------------------------------------------------------------ - | Determine target type - \-----------------------------------------------------------------------------------------------------------------------*/ - var targetType = TypeLookupService.Lookup(contentType); - - //Fallback to generic AttributeDescriptor if the specific attribute descriptor cannot be found - if (targetType is null && contentType.EndsWith("AttributeDescriptor", StringComparison.OrdinalIgnoreCase)) { - targetType = typeof(AttributeDescriptor); - } - - targetType ??= typeof(Topic); - - /*------------------------------------------------------------------------------------------------------------------------ - | Identify the appropriate topic - \---------------------------------------------------------------------------------------------------------------------*/ - return (Topic)Activator.CreateInstance(targetType, key, contentType, parent, id)!; + var targetType = TypeLookupService.Lookup(contentType); + //Fallback to generic AttributeDescriptor if the specific attribute descriptor cannot be found + if (targetType is null && contentType.EndsWith("AttributeDescriptor", StringComparison.OrdinalIgnoreCase)) { + targetType = typeof(AttributeDescriptor); } - /// - [ExcludeFromCodeCoverage] - [Obsolete("The 'id' parameter has been moved to the end of the parameter list.", true)] - public static Topic Create(string key, string contentType, int id, Topic? parent) => - throw new NotImplementedException(); - - /// - public static Topic Create(string key, string contentType, int id) => - Create(key, contentType, null, id); + targetType ??= typeof(Topic); - /*========================================================================================================================== - | METHOD: VALIDATE KEY + /*-------------------------------------------------------------------------------------------------------------------------- + | Identify the appropriate topic \-------------------------------------------------------------------------------------------------------------------------*/ - /// - /// Validates the format of a key used for an individual topic. - /// - /// - /// Topic keys may be exposed as, for example, virtual routes and, thus, should not contain spaces, slashes, question - /// marks or other symbols reserved for URLs. This method is marked static so that it can also be used by the static Code - /// Contract Checker. - /// - /// The topic key that should be validated. - /// Allows the topicKey to be optional (i.e., a null reference). - public static void ValidateKey(string? topicKey, bool isOptional = false) { - Contract.Requires(isOptional || !String.IsNullOrEmpty(topicKey)); - Contract.Requires( - String.IsNullOrEmpty(topicKey) || Regex.IsMatch(topicKey, @"^[a-zA-Z0-9\.\-_]+$"), - "Key names should only contain letters, numbers, hyphens, periods, and/or underscores." - ); - } + return (Topic)Activator.CreateInstance(targetType, key, contentType, parent, id)!; + + } + + /// + [ExcludeFromCodeCoverage] + [Obsolete("The 'id' parameter has been moved to the end of the parameter list.", true)] + public static Topic Create(string key, string contentType, int id, Topic? parent) => + throw new NotImplementedException(); + + /// + public static Topic Create(string key, string contentType, int id) => + Create(key, contentType, null, id); + + /*============================================================================================================================ + | METHOD: VALIDATE KEY + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Validates the format of a key used for an individual topic. + /// + /// + /// Topic keys may be exposed as, for example, virtual routes and, thus, should not contain spaces, slashes, question + /// marks or other symbols reserved for URLs. This method is marked static so that it can also be used by the static Code + /// Contract Checker. + /// + /// The topic key that should be validated. + /// Allows the topicKey to be optional (i.e., a null reference). + public static void ValidateKey(string? topicKey, bool isOptional = false) { + Contract.Requires(isOptional || !String.IsNullOrEmpty(topicKey)); + Contract.Requires( + String.IsNullOrEmpty(topicKey) || KeyRegex().IsMatch(topicKey), + "Key names should only contain letters, numbers, hyphens, periods, and/or underscores." + ); + } + + /*============================================================================================================================ + | METHOD: KEY REGEX + \---------------------------------------------------------------------------------------------------------------------------*/ + /// + /// Provides a compiled regular expression for validating topic keys. + /// + [GeneratedRegex(@"^[a-zA-Z0-9\.\-_]+$")] + private static partial Regex KeyRegex(); - } //Class -} //Namespace \ No newline at end of file +} //Class \ No newline at end of file