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.062eb85bf-f802-4afd-8bec-3d344e1cfc79false
+ 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.0false
+ 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.0Exefalse
+ 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.0Exefalse
+ 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