diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md
new file mode 100644
index 00000000..855119b4
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md
@@ -0,0 +1,134 @@
+# Architecture Decision Record (ADR): 0011 - Replace MediatR with Custom CQRS Abstractions
+
+## Status
+
+**Accepted** (2026-08-13)
+
+## Context
+
+The solution uses MediatR as a lightweight mediator to encapsulate command and query handling across the application layer. Following MediatR's shift to a commercial licensing model starting with .NET 8, continued use introduces an unacceptable external dependency on a paid third-party library for functionality that is entirely implementable in-house.
+
+Key constraints that shaped this decision:
+
+1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems.
+
+2. **Narrow Usage Scope**: MediatR is used exclusively for command and query dispatching - only one pipeline behavior (automatic application validation) and no notification publishing or stream requests are in use anywhere in the solution.
+
+3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, MediatR provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection.
+
+4. **Ownership and Transparency**: A custom implementation is fully owned, inspectable, and carries no transitive dependency risk or future licensing exposure.
+
+## Decision
+
+Replace MediatR with minimal, hand-written CQRS abstractions placed in `Lumina.Application.Common.CQRS`. Handlers are resolved directly via the .NET dependency injection container - no mediator object, no runtime reflection dispatch.
+
+### Core Abstractions
+
+```csharp
+// src/Lumina.Application/Common/CQRS/ICommand.cs
+
+///
+/// Marker interface for command types handled by .
+///
+public interface ICommand
+{
+}
+
+///
+/// Defines a contract for handling commands in the application layer.
+/// Commands represent operations that modify application state.
+///
+/// The type of command to handle.
+/// The type of result returned after handling the command.
+public interface ICommandHandler where TCommand : ICommand
+{
+ Task HandleAsync(TCommand command, CancellationToken cancellationToken = default);
+}
+```
+
+```csharp
+// src/Lumina.Application/Common/CQRS/IQuery.cs
+
+///
+/// Marker interface for query types handled by .
+///
+public interface IQuery
+{
+}
+
+///
+/// Defines a contract for handling queries in the application layer.
+/// Queries represent read operations that do not modify application state.
+///
+/// The type of query to handle.
+/// The type of result returned after handling the query.
+public interface IQueryHandler where TQuery : IQuery
+{
+ Task HandleAsync(TQuery query, CancellationToken cancellationToken = default);
+}
+```
+
+### Usage at Call Site
+
+Handlers are injected directly - no `ISender` or mediator intermediary:
+
+```csharp
+// Before (MediatR)
+internal sealed record GetConfiguredNismsQuery : IRequest>>;
+internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
+{
+ private readonly ISender _sender;
+
+ public GetConfiguredNismsEndpoint(ISender sender)
+ {
+ _sender = sender;
+ }
+
+ public async Task>> ExecuteAsync(CancellationToken cancellationToken)
+ {
+ return await _sender.Send(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false);
+ }
+}
+
+// After (custom abstraction)
+internal sealed record GetConfiguredNismsQuery : IQuery;
+internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
+{
+ private readonly IQueryHandler>> _handler;
+
+ public GetConfiguredNismsEndpoint(IQueryHandler>> handler)
+ {
+ _handler = handler;
+ }
+
+ public async Task>> ExecuteAsync(CancellationToken cancellationToken)
+ {
+ return await _handler.HandleAsync(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false);
+ }
+}
+```
+
+## Consequences
+
+### Positive Outcomes
+
+| Aspect | Benefit |
+|---|---|
+| Licensing | Eliminates commercial dependency and associated cost/compliance risk |
+| Simplicity | Removes an indirection layer unused beyond basic dispatch |
+| Transparency | Full ownership of dispatch logic; no hidden reflection or dynamic proxy behavior |
+| Testability | Handlers are tested directly via their interface, no mock mediator required |
+| DI Alignment | Leverages the existing .NET DI container idioms already present in the solution |
+| Performance | No runtime reflection, other than the startup registration of application use case handlers |
+
+### Risks and Mitigations
+
+| Risk | Mitigation Strategy |
+|---|---|
+| Loss of pipeline behavior support | Application validation will be performed manually, as an orchestration step |
+| Handler resolution errors surfacing at runtime | Covered by existing integration test suite that exercises the DI container on startup |
+| Increased boilerplate per feature | Marginal - one interface injection vs. `ISender`; offset by elimination of `IRequest` marker on every command/query |
+
+## Alternatives Considered
+
+No alternative libraries were evaluated. The sole driver for replacing MediatR was the licensing change, and the solution's usage is narrow enough that a first-party implementation is both sufficient and lower risk than adopting a different third-party mediator library.
diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md
new file mode 100644
index 00000000..27bf386e
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md
@@ -0,0 +1,184 @@
+# Architecture Decision Record (ADR): 0012 - Replace FluentValidation with Custom Validation Abstractions
+
+## Status
+
+**Accepted** (2026-08-13)
+
+## Context
+
+The solution uses FluentValidation to validate commands and queries at the application boundary. A review of its usage across the codebase reveals a deliberately constrained subset of its feature set:
+
+1. **Narrow API Surface**: Only `RuleFor`, `Must`, `When`, and `WithMessage`-equivalent patterns are used. Advanced FluentValidation features - cascading rules, `RuleSets`, async validators, `SetValidator`, `Transform`, and the `AbstractValidator` inheritance tree beyond basic use - are absent throughout.
+
+2. **`Error`-typed Results**: The solution uses `ErrorOr` as its result type. FluentValidation returns `ValidationResult` / `ValidationFailure`, requiring a translation layer on every usage site to produce `Error` values, with some information loss in the process. A first-party validator can return `ErrorOr.Error` directly, with full metadata, eliminating that friction.
+
+3. **External Dependency Surface**: FluentValidation is a well-maintained library, but the danger of it going commercial, like other open source popular libraries in recent times, and the lack of usage of its advanced features mandates an in-house replacement.
+
+4. **Placement in SharedKernel**: Validation logic is cross-cutting and lives in `Lumina.Application.Common.Infrastructure.Validation`. Owning the abstraction entirely means the validation model stays aligned with the domain's `Error` type without any adapter.
+
+## Decision
+
+Replace FluentValidation with a minimal, first-party validation framework placed in `Lumina.Application.Common.Infrastructure.Validation`. The API mirrors FluentValidation's familiar fluent surface (`RuleFor`, `Must`, `When`, `WithError`) to minimize migration friction.
+
+### Core Abstractions
+
+```csharp
+// IValidator.cs - public contract consumed by application handlers
+public interface IValidator
+{
+ List Validate(TRequest instance);
+}
+
+// IValidationRule.cs - internal rule evaluation contract
+internal interface IValidationRule
+{
+ Error? Validate(TRequest instance);
+}
+
+// IRuleBuilder.cs - fluent configuration surface
+public interface IRuleBuilder
+{
+ IRuleBuilder Must(Func predicate);
+ IRuleBuilder When(Func condition);
+ IRuleBuilder WithError(Error error);
+}
+```
+
+### Base Validator
+
+```csharp
+// AbstractValidator.cs
+public abstract class AbstractValidator : IValidator
+{
+ private readonly List> _rules = [];
+
+ protected IRuleBuilder RuleFor(
+ Func propertySelector)
+ {
+ ValidationRule rule = new(propertySelector);
+ _rules.Add(rule);
+ return rule;
+ }
+
+ public List Validate(TRequest instance)
+ {
+ List errors = [];
+ foreach (IValidationRule rule in _rules)
+ {
+ Error? error = rule.Validate(instance);
+ if (error.HasValue)
+ errors.Add(error.Value);
+ }
+ return errors;
+ }
+}
+```
+
+### Concrete Rule Implementation
+
+```csharp
+// ValidationRule.cs - internal sealed, not exposed to consumers
+internal sealed class ValidationRule
+ : IValidationRule, IRuleBuilder
+{
+ private readonly Func _propertySelector;
+ private readonly List> _predicates = [];
+ private Error _error = Error.Validation();
+ private Func? _condition;
+
+ public ValidationRule(Func propertySelector)
+ => _propertySelector = propertySelector;
+
+ public IRuleBuilder Must(Func predicate)
+ {
+ _predicates.Add(predicate);
+ return this;
+ }
+
+ public IRuleBuilder When(Func condition)
+ {
+ _condition = condition;
+ return this;
+ }
+
+ public IRuleBuilder WithError(Error error)
+ {
+ _error = error;
+ return this;
+ }
+
+ public Error? Validate(TRequest instance)
+ {
+ if (_condition is not null && !_condition(instance))
+ return null;
+
+ TProperty value = _propertySelector(instance);
+ foreach (var predicate in _predicates)
+ if (!predicate(value))
+ return _error;
+
+ return null;
+ }
+}
+```
+
+### Built-in Extension Methods
+
+Common predicates are provided as extension methods on `IRuleBuilder` via `ValidatorUtilities`, placed in `Lumina.Application.Common.Utilities`:
+
+| Extension | Overloads | Behaviour |
+|---|---|---|
+| `NotEmpty()` | `string`, `List` | Fails if `null`, empty, or whitespace-only |
+| `GreaterThan(value)` | `int`, `int?`, `TimeSpan` | Fails if property ≤ value; nullable variant passes on `null` |
+| `IsInEnum()` | `TEnum`, `TEnum?` | Fails if value is not a defined enum member; nullable variant passes on `null` |
+
+### Usage Example
+
+```csharp
+internal sealed class CreateSensorCommandValidator : AbstractValidator
+{
+ public CreateSensorCommandValidator()
+ {
+ RuleFor(x => x.Name)
+ .NotEmpty()
+ .WithError(Errors.Sensor.NameRequired);
+
+ RuleFor(x => x.IntervalSeconds)
+ .GreaterThan(0)
+ .WithError(Errors.Sensor.InvalidInterval);
+
+ RuleFor(x => x.Type)
+ .IsInEnum()
+ .WithError(Errors.Sensor.InvalidType);
+
+ RuleFor(x => x.ThresholdOverride)
+ .GreaterThan(0)
+ .When(x => x.ThresholdOverride.HasValue)
+ .WithError(Errors.Sensor.InvalidThreshold);
+ }
+}
+```
+
+## Consequences
+
+### Positive Outcomes
+
+| Aspect | Benefit |
+|---|---|
+| `Error` Alignment | Validators return `List` directly - no `ValidationResult` → `Error` translation layer at call sites |
+| Dependency Reduction | Removes FluentValidation NuGet package and all transitive dependencies |
+| API Ownership | Full control over rule semantics, error shape, and future extension |
+| Familiar Surface | `RuleFor` / `Must` / `When` / `WithError` pattern is intentionally close to FluentValidation, minimising cognitive load during migration |
+| Encapsulation | `IValidationRule` and `ValidationRule` are `internal`; consumers only interact with `IValidator` and `IRuleBuilder` |
+
+### Risks and Mitigations
+
+| Risk | Mitigation Strategy |
+|---|---|
+| Missing built-in rules surfacing post-migration | Audit all existing FluentValidation rule usages before removal; add corresponding `ValidatorUtilities` extensions as needed |
+| Async validation not supported | No async validators exist, because this pertains to application use cases validation concerns (user input, etc), not business rules validations or invariants, which might require asynchronous or IO operations |
+| Loss of FluentValidation test helpers (`TestValidate`) | Replace with direct `ValidatorTestExtensions.TestValidate` calls in unit tests |
+
+## Alternatives Considered
+
+No alternative third-party validation libraries were evaluated, as this decision was not about replacing the FluentValidation libary with another library. The solution's validation usage is sufficiently narrow (property-level predicates, conditional execution, typed error results) that the cost of adopting and adapting another external library exceeds the cost of ownership of a purpose-built implementation aligned with the `ErrorOr` result model already in use.
diff --git a/src/Lumina.Application/Common/CQRS/ICommand.cs b/src/Lumina.Application/Common/CQRS/ICommand.cs
new file mode 100644
index 00000000..c74204dc
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/ICommand.cs
@@ -0,0 +1,8 @@
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Marker interface for command types handled by .
+///
+public interface ICommand
+{
+}
diff --git a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs
new file mode 100644
index 00000000..19e0018d
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Defines a contract for handling commands in the application layer.
+/// Commands represent operations that modify application state.
+///
+/// The type of command to handle.
+/// The type of result returned after handling the command.
+public interface ICommandHandler where TCommand : ICommand
+{
+ ///
+ /// Handles the specified command and returns a result.
+ ///
+ /// The command to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the result of the command execution.
+ Task HandleAsync(TCommand command, CancellationToken cancellationToken = default);
+}
diff --git a/src/Lumina.Application/Common/CQRS/IQuery.cs b/src/Lumina.Application/Common/CQRS/IQuery.cs
new file mode 100644
index 00000000..dd2f42ed
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/IQuery.cs
@@ -0,0 +1,8 @@
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Marker interface for query types handled by .
+///
+public interface IQuery
+{
+}
diff --git a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs
new file mode 100644
index 00000000..8b5fadde
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Defines a contract for handling queries in the application layer.
+/// Queries represent read-only operations that retrieve data without modifying application state.
+///
+/// The type of query to handle.
+/// The type of result returned after handling the query.
+public interface IQueryHandler where TQuery : IQuery
+{
+ ///
+ /// Handles the specified query and returns a result.
+ ///
+ /// The query to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the result of the query execution.
+ Task HandleAsync(TQuery query, CancellationToken cancellationToken = default);
+}
diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
index 905573aa..2887a02b 100644
--- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
+++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
@@ -3,7 +3,11 @@ using FluentValidation;
using Lumina.Application.Common.Behaviors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Reflection;
#endregion
namespace Lumina.Application.Common.DependencyInjection;
@@ -33,6 +37,32 @@ public static class ApplicationLayerServices
// register fluent validators
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
+ Type[] handlers =
+ [
+ typeof(CQRS.ICommandHandler<,>),
+ typeof(CQRS.IQueryHandler<,>),
+ typeof(Infrastructure.Validation.IValidator<>),
+ ];
+
+ IEnumerable types = Assembly.GetExecutingAssembly()
+ .GetTypes()
+ .Where(type => !type.IsInterface && !type.IsAbstract);
+
+ var registrations = types
+ .SelectMany(type => type.GetInterfaces(),
+ (implementation, service) => new { Service = service, Implmentation = implementation })
+ .Where(type => type.Service.IsGenericType && handlers.Contains(type.Service.GetGenericTypeDefinition()));
+
+ foreach (var registration in registrations)
+ {
+ if (!services.Any(service => service.ServiceType == registration.Service))
+ {
+ if (registration.Service.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
+ services.AddSingleton(registration.Service, registration.Implmentation);
+ else
+ services.AddScoped(registration.Service, registration.Implmentation);
+ }
+ }
return services;
}
}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs
new file mode 100644
index 00000000..275cc1a7
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs
@@ -0,0 +1,57 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Base class for creating validators for commands and queries.
+///
+/// The type of the request (command or query) to be validated.
+public abstract class AbstractValidator : IValidator
+{
+ private readonly List> _rules = [];
+
+ ///
+ /// Defines a validation rule for a specific property on the request being validated.
+ ///
+ /// The type of the property being validated.
+ /// A function that selects the property to validate from the request instance.
+ /// An instance to configure the rule fluently.
+ protected IRuleBuilder RuleFor(Func propertySelector)
+ {
+ ValidationRule rule = new(propertySelector);
+ _rules.Add(rule);
+ return rule;
+ }
+
+ ///
+ /// Defines a validation rule that is evaluated against each item within a collection property on the request being validated.
+ ///
+ /// The type of the items in the collection being validated.
+ /// A function that selects the collection to validate from the request instance.
+ /// An instance to configure the per-item rule fluently.
+ protected IRuleBuilder RuleForEach(Func?> collectionSelector)
+ {
+ ValidationRuleForEach rule = new(collectionSelector);
+ _rules.Add(rule);
+ return rule;
+ }
+
+ ///
+ /// Validates the specified request instance against all defined rules.
+ ///
+ /// The request instance to validate.
+ /// A list of validation errors. If the instance is valid, the list will be empty.
+ public List Validate(TRequest instance)
+ {
+ List errors = [];
+
+ foreach (IValidationRule rule in _rules)
+ errors.AddRange(rule.Validate(instance));
+
+ return errors;
+ }
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs
new file mode 100644
index 00000000..8da4fcfb
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Provides a fluent API for building validation rules for commands and queries.
+///
+/// The type of the request (command or query) being validated.
+/// The type of the specific property on the request that the rule applies to.
+public interface IRuleBuilder
+{
+ ///
+ /// Specifies a condition that the property must satisfy to be considered valid.
+ ///
+ /// A function to test the property value.
+ /// The current instance for method chaining.
+ IRuleBuilder Must(Func predicate);
+
+ ///
+ /// Specifies a condition that must be met for the validation rule to be executed.
+ ///
+ /// A function evaluating the request instance.
+ /// The current instance for method chaining.
+ IRuleBuilder When(Func condition);
+
+ ///
+ /// Specifies a custom object to be returned when the validation fails.
+ ///
+ /// The specific error to return upon failure.
+ /// The current instance for method chaining.
+ IRuleBuilder WithError(Error error);
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs
new file mode 100644
index 00000000..a914dfd2
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs
@@ -0,0 +1,20 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Interface for triggering commands and queries validator evaluation.
+///
+/// The type of the request (command or query) being evaluated.
+internal interface IValidationRule
+{
+ ///
+ /// Evaluates the validation rule against the specified request instance.
+ ///
+ /// The request instance to validate.
+ /// The s produced by this rule; empty if the rule passes.
+ IEnumerable Validate(TRequest instance);
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs
new file mode 100644
index 00000000..59467cb7
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs
@@ -0,0 +1,20 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Interface for validating requests of commands and queries.
+///
+/// The type of the request (command or query) to be validated.
+public interface IValidator
+{
+ ///
+ /// Validates the specified request instance against the defined rules.
+ ///
+ /// The request instance to validate.
+ /// A list of validation errors. If the instance is valid, the list will be empty.
+ List Validate(TRequest instance);
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs
new file mode 100644
index 00000000..bc9352f8
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs
@@ -0,0 +1,85 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Defines a validation rule for commands and queries that evaluates a specific property of a request.
+///
+/// The type of the request (command or query) being validated.
+/// The type of the specific property on the request that the rule applies to.
+internal sealed class ValidationRule : IValidationRule, IRuleBuilder
+{
+ private readonly Func _propertySelector;
+ private readonly List> _predicates = [];
+ private Error error = Error.Validation();
+ private Func? condition;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// A function that extracts the property value from the request instance.
+ public ValidationRule(Func propertySelector)
+ {
+ _propertySelector = propertySelector;
+ }
+
+ ///
+ /// Adds a condition that the property must satisfy to be considered valid.
+ ///
+ /// A function to test the property value.
+ /// The current instance for method chaining.
+ public IRuleBuilder Must(Func predicate)
+ {
+ _predicates.Add(predicate);
+ return this;
+ }
+
+ ///
+ /// Specifies a condition that must be met for the validation rule to be executed.
+ ///
+ /// A function evaluating the request instance.
+ /// The current instance for method chaining.
+ public IRuleBuilder When(Func condition)
+ {
+ this.condition = condition;
+ return this;
+ }
+
+ ///
+ /// Specifies a custom object to be returned when the validation fails.
+ ///
+ /// The specific error to return upon failure.
+ /// The current instance for method chaining.
+ public IRuleBuilder WithError(Error error)
+ {
+ this.error = error;
+ return this;
+ }
+
+ ///
+ /// Evaluates all configured predicates against the specified request instance.
+ ///
+ /// The request instance to validate.
+ /// The if any predicate fails; empty if the rule passes.
+ public IEnumerable Validate(TRequest instance)
+ {
+ // evaluate the condition first, if it returns false, skip validation entirely.
+ if (condition is not null && !condition(instance))
+ yield break;
+
+ TProperty value = _propertySelector(instance);
+
+ foreach (Func predicate in _predicates)
+ {
+ if (!predicate(value))
+ {
+ yield return error;
+ yield break;
+ }
+ }
+ }
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs
new file mode 100644
index 00000000..560b2712
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs
@@ -0,0 +1,90 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Defines a validation rule for commands and queries that evaluates each item within a collection property of a request.
+///
+/// The type of the request (command or query) being validated.
+/// The type of the items in the collection that the rule applies to.
+internal sealed class ValidationRuleForEach : IValidationRule, IRuleBuilder
+{
+ private readonly Func?> _collectionSelector;
+ private readonly List> _predicates = [];
+ private Error error = Error.Validation();
+ private Func? condition;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// A function that extracts the collection to iterate from the request instance.
+ public ValidationRuleForEach(Func?> collectionSelector)
+ {
+ _collectionSelector = collectionSelector;
+ }
+
+ ///
+ /// Adds a condition that each item in the collection must satisfy to be considered valid.
+ ///
+ /// A function to test each item value.
+ /// The current instance for method chaining.
+ public IRuleBuilder Must(Func predicate)
+ {
+ _predicates.Add(predicate);
+ return this;
+ }
+
+ ///
+ /// Specifies a condition that must be met for the validation rule to be executed.
+ ///
+ /// A function evaluating the request instance.
+ /// The current instance for method chaining.
+ public IRuleBuilder When(Func condition)
+ {
+ this.condition = condition;
+ return this;
+ }
+
+ ///
+ /// Specifies a custom object to be returned when the validation fails.
+ ///
+ /// The specific error to return upon failure.
+ /// The current instance for method chaining.
+ public IRuleBuilder WithError(Error error)
+ {
+ this.error = error;
+ return this;
+ }
+
+ ///
+ /// Evaluates all configured predicates against each item in the collection.
+ ///
+ /// The request instance to validate.
+ /// One per item that fails a predicate; empty if every item passes.
+ public IEnumerable Validate(TRequest instance)
+ {
+ // evaluate the condition first, if it returns false, skip validation entirely.
+ if (condition is not null && !condition(instance))
+ yield break;
+
+ IEnumerable? collection = _collectionSelector(instance);
+ if (collection is null)
+ yield break;
+
+ foreach (TItem item in collection)
+ {
+ foreach (Func predicate in _predicates)
+ {
+ if (!predicate(item))
+ {
+ yield return error;
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
new file mode 100644
index 00000000..42b96f5f
--- /dev/null
+++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
@@ -0,0 +1,133 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Utilities;
+
+///
+/// Validator extension methods for the to define common validation rules.
+///
+public static class ValidatorUtilities
+{
+ ///
+ /// Defines a validation rule that ensures the integer property is greater than the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare)
+ {
+ return ruleBuilder.Must(value => value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable integer property is greater than the specified value.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the time span property is greater than the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, TimeSpan valueToCompare)
+ {
+ return ruleBuilder.Must(value => value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the property is not .
+ ///
+ ///
+ /// This rule checks reference/nullable-value nullness only. Combine with
+ /// or
+ /// to also reject empty values.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder NotNull(this IRuleBuilder ruleBuilder)
+ {
+ return ruleBuilder.Must(value => value is not null);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property is not empty or consisting only of white-space characters.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder)
+ {
+ return ruleBuilder.Must(value => value is null || value.Trim().Length > 0);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the List property is not empty.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The type of the items in the list being validated.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder> NotEmpty(this IRuleBuilder> ruleBuilder)
+ {
+ return ruleBuilder.Must(value => value is null || value.Count > 0);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the property is not .
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder)
+ {
+ return ruleBuilder.Must(value => value != Guid.Empty);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the value is a defined member of the specified enumeration type.
+ ///
+ /// The type of the request being validated.
+ /// The type of the enumeration.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum
+ {
+ return ruleBuilder.Must(value => Enum.IsDefined(value));
+ }
+
+ ///
+ /// Defines a validation rule that ensures a nullable enum value is either or a defined member of the specified enumeration type.
+ ///
+ /// The type of the request being validated.
+ /// The type of the enumeration.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum
+ {
+ return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value));
+ }
+}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs
index bdbd33aa..840e75eb 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -18,4 +16,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
public record AddRoleCommand(
string RoleName,
List Permissions
-) : IRequest>;
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs
index 74c13ceb..ecc324ac 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
///
/// Handler for the command to add an authorization role.
///
-public class AddRoleCommandHandler : IRequestHandler>
+public class AddRoleCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
@@ -31,11 +34,13 @@ public class AddRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality.
/// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
+ _validator = validator;
}
///
@@ -46,8 +51,12 @@ public class AddRoleCommandHandler : IRequestHandler
/// An containing either a successfully created , or an error message.
///
- public async ValueTask> Handle(AddRoleCommand request, CancellationToken cancellationToken)
+ public async Task> HandleAsync(AddRoleCommand request, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(request);
+ if (validationResult.Count > 0)
+ return validationResult;
+
// only admins can create authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -59,13 +68,13 @@ public class AddRoleCommandHandler : IRequestHandler new RolePermissionEntity()
+ RolePermissions = [.. request.Permissions.Select(permissionId => new RolePermissionEntity()
{
PermissionId = permissionId,
Permission = null!,
Role = null!,
RoleId = default
- }).ToList()
+ })]
};
// save the new role in the repository
ErrorOr insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs
index a2b2f01f..ab5804db 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -17,14 +18,15 @@ public class AddRoleCommandValidator : AbstractValidator
public AddRoleCommandValidator()
{
RuleFor(x => x.RoleName)
- .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
- .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
+ .NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull)
+ .NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty);
RuleFor(x => x.Permissions)
- .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
- .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
+ .NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull)
+ .NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty);
+
RuleForEach(x => x.Permissions)
- .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
+ .NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs
index 6050dc46..38202928 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi
[DebuggerDisplay("RoleId: {RoleId}")]
public record GetRolePermissionsQuery(
Guid RoleId
-) : IRequest>;
+) : IQuery;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
index 7305064c..c1735073 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,11 +20,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi
///
/// Handler for the query to retrieve the list of authorization permissions for a role.
///
-public class GetRolePermissionsQueryHandler : IRequestHandler>
+public class GetRolePermissionsQueryHandler : IQueryHandler>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IRoleRepository _roleRepository;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
@@ -30,11 +33,13 @@ public class GetRolePermissionsQueryHandler : IRequestHandlerInjected service for authorization related functionality.
/// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_roleRepository = unitOfWork.GetRepository();
+ _validator = validator;
}
///
@@ -45,8 +50,12 @@ public class GetRolePermissionsQueryHandler : IRequestHandler
/// An containing either a collection of , or an error message.
///
- public async ValueTask> Handle(GetRolePermissionsQuery request, CancellationToken cancellationToken)
+ public async Task> HandleAsync(GetRolePermissionsQuery request, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(request);
+ if (validationResult.Count > 0)
+ return validationResult;
+
// only admins can see the list of authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs
index 107b65d3..565cc7fb 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -17,7 +18,7 @@ public class GetRolePermissionsQueryValidator : AbstractValidator x.RoleId)
- .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
+ .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj
index 137f8c15..23264fd5 100644
--- a/src/Lumina.Application/Lumina.Application.csproj
+++ b/src/Lumina.Application/Lumina.Application.csproj
@@ -32,4 +32,8 @@
+
+
+
+
diff --git a/src/Lumina.Infrastructure/Common/Utilities/ExceptionUtilities.cs b/src/Lumina.Infrastructure/Common/Utilities/ExceptionUtilities.cs
new file mode 100644
index 00000000..95139811
--- /dev/null
+++ b/src/Lumina.Infrastructure/Common/Utilities/ExceptionUtilities.cs
@@ -0,0 +1,59 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+#endregion
+
+namespace Lumina.Infrastructure.Common.Utilities;
+
+///
+/// Exception extension methods.
+///
+///
+/// Based on https://stackoverflow.com/a/62283895.
+///
+public static class ExceptionUtilities
+{
+ ///
+ /// Concatenates all inner exception(s) messages of .
+ ///
+ /// The exception for which to get the inner exception(s) message.
+ /// A string representing the concatenated messages of all inner expcetion(s) of .
+ public static string AggregateMessages(this Exception ex)
+ {
+ return ex.GetInnerExceptions().Aggregate(new StringBuilder(), (stringBuilder, exception) => stringBuilder.AppendLine(exception.Message + " -> "), stringBuilder => stringBuilder.ToString());
+ }
+
+ ///
+ /// Recursively gets the inner exception(s) of , at depth.
+ ///
+ /// The exception for which to get the inner exception(s).
+ /// The depth of the recursivity of getting the inner exception(s) of .
+ /// A list of exceptions representing the list of inner exception(s) of .
+ public static IEnumerable GetInnerExceptions(this Exception exception, int maximumDepth = 5)
+ {
+ // check if there are any more inner exceptions to return
+ if (exception == null || maximumDepth <= 0)
+ yield break;
+ // yield the current level exception itself
+ yield return exception;
+ // if the exception is an AggregateException, treat it differently and get its all exceptions
+ if (exception is AggregateException aggregateException)
+ foreach (Exception? innerException in aggregateException.InnerExceptions.SelectMany(innerException => innerException.GetInnerExceptions(maximumDepth - 1)))
+ yield return innerException;
+ // if it's a normal exception, recursively get its list of inner exceptions and yield them
+ foreach (Exception innerException in exception.InnerException?.GetInnerExceptions(maximumDepth - 1) ?? [])
+ yield return innerException;
+ }
+
+ ///
+ /// Concatenates the relevant properties of .
+ ///
+ /// The exception for which to get the relevant properties.
+ /// A string representing the concatenated relevant properties of .
+ public static string AggregateMessage(this Exception ex)
+ {
+ return $"Message: {ex.Message}; CallStack: {ex.StackTrace}";
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs
index c285c2d8..d8754a30 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpoint.cs
@@ -1,12 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
-using FastEndpoints;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Authorization;
+using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
-using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.AddRo
///
public class AddRoleEndpoint : BaseEndpoint
{
- private readonly ISender _sender;
+ private readonly ICommandHandler> _addRoleCommandHandler;
///
/// Initializes a new instance of the class.
///
- /// Injected service for mediating commands and queries.
- public AddRoleEndpoint(ISender sender)
+ /// Injected service for handling add role commands.
+ public AddRoleEndpoint(ICommandHandler> addRoleCommandHandler)
{
- _sender = sender;
+ _addRoleCommandHandler = addRoleCommandHandler;
}
///
@@ -35,7 +35,7 @@ public class AddRoleEndpoint : BaseEndpoint
///
public override void Configure()
{
- Verbs(Http.POST);
+ Verbs(FastEndpoints.Http.POST);
Routes(ApiRoutes.Roles.CREATE_ROLE);
Version(1);
DontCatchExceptions();
@@ -48,7 +48,7 @@ public class AddRoleEndpoint : BaseEndpoint
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(AddRoleRequest request, CancellationToken cancellationToken)
{
- ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
+ ErrorOr result = await _addRoleCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs
index bfb48d71..bf158a74 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpoint.cs
@@ -1,12 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
-using FastEndpoints;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Authorization;
+using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
-using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -19,15 +19,15 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRo
///
public class GetRolePermissionsEndpoint : BaseEndpoint
{
- private readonly ISender _sender;
+ private readonly IQueryHandler> _addRoleQueryHandler;
///
/// Initializes a new instance of the class.
///
- /// Injected service for mediating commands and queries.
- public GetRolePermissionsEndpoint(ISender sender)
+ /// Injected service for handling add role commands.
+ public GetRolePermissionsEndpoint(IQueryHandler> addRoleQueryHandler)
{
- _sender = sender;
+ _addRoleQueryHandler = addRoleQueryHandler;
}
///
@@ -35,7 +35,7 @@ public class GetRolePermissionsEndpoint : BaseEndpoint
public override void Configure()
{
- Verbs(Http.GET);
+ Verbs(FastEndpoints.Http.GET);
Routes(ApiRoutes.Roles.GET_ROLE_PERMISSIONS_BY_ROLE_ID);
Version(1);
DontCatchExceptions();
@@ -48,7 +48,7 @@ public class GetRolePermissionsEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(GetRolePermissionsRequest request, CancellationToken cancellationToken)
{
- ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
+ ErrorOr result = await _addRoleQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj
index 6114a9a6..624f6344 100644
--- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj
+++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj
@@ -1,4 +1,4 @@
-
+
net10.0
enable
@@ -13,7 +13,10 @@
lumina-api
..\docker-compose.dcproj
-
+
+ en
+
+
diff --git a/src/Lumina.sln b/src/Lumina.sln
index d29d523a..705b4779 100644
--- a/src/Lumina.sln
+++ b/src/Lumina.sln
@@ -191,6 +191,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log",
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0001.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0001.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0002.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0002.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0003.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0003.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0004.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0004.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0005.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0005.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0006.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0006.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0007.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0007.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0008.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0008.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0009.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0009.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0010.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0010.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Contracts", "Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj", "{8CF6FEA4-624C-4EC9-93D6-EB7626059D7C}"
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs
new file mode 100644
index 00000000..f45abf46
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Setup/ValidatorTestExtensions.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Application.Common.Infrastructure.Validation;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Setup;
+
+///
+/// Validator extension methods for for unit tests.
+///
+public static class ValidatorTestExtensions
+{
+ ///
+ /// Executes the validator against the specified request instance and returns the resulting errors.
+ ///
+ /// The type of the request being validated.
+ /// The validator instance to execute.
+ /// The request instance to validate.
+ /// A list of produced by the validator. If the request is valid, the list will be empty.
+ public static List TestValidate(this IValidator validator, TRequest request)
+ {
+ return validator.Validate(request);
+ }
+
+ ///
+ /// Asserts that the validation results do not contain the specified error.
+ ///
+ /// The list of errors returned by the validator.
+ /// The error that should not be present in the validation results.
+ public static void ShouldNotHaveValidationError(this List errors, Error expectedError)
+ {
+ Assert.DoesNotContain(errors, error => error.Code == expectedError.Code);
+ }
+
+ ///
+ /// Asserts that the validation results contain the specified error.
+ ///
+ /// The list of errors returned by the validator.
+ /// The error that should be present in the validation results.
+ public static void ShouldHaveValidationError(this List errors, Error expectedError)
+ {
+ Assert.Contains(errors, error => error.Code == expectedError.Code);
+ }
+
+ ///
+ /// Asserts that the validation results are completely empty, indicating the request is valid.
+ ///
+ /// The list of errors returned by the validator.
+ public static void ShouldNotHaveAnyValidationErrors(this List errors)
+ {
+ Assert.Empty(errors);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs
index 66799e0f..6a880d02 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures;
using Lumina.Contracts.Responses.Authorization;
@@ -39,6 +40,9 @@ public class AddRoleCommandHandlerTests
///
public AddRoleCommandHandlerTests()
{
+ IValidator mockValidator = Substitute.For>();
+ mockValidator.Validate(Arg.Any())
+ .Returns([]);
_mockUnitOfWork = Substitute.For();
_mockAuthorizationService = Substitute.For();
_mockCurrentUserService = Substitute.For();
@@ -52,7 +56,8 @@ public class AddRoleCommandHandlerTests
_sut = new AddRoleCommandHandler(
_mockAuthorizationService,
_mockCurrentUserService,
- _mockUnitOfWork);
+ _mockUnitOfWork,
+ mockValidator);
}
[Fact]
@@ -64,7 +69,7 @@ public class AddRoleCommandHandlerTests
.Returns(false);
// Act
- ErrorOr result = await _sut.Handle(command, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -85,7 +90,7 @@ public class AddRoleCommandHandlerTests
.Returns(error);
// Act
- ErrorOr result = await _sut.Handle(command, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -108,7 +113,7 @@ public class AddRoleCommandHandlerTests
.Returns(error);
// Act
- ErrorOr result = await _sut.Handle(command, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -129,7 +134,7 @@ public class AddRoleCommandHandlerTests
.Returns((RoleEntity?)null);
// Act
- ErrorOr result = await _sut.Handle(command, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -146,7 +151,7 @@ public class AddRoleCommandHandlerTests
{
Id = roleId,
RoleName = command.RoleName,
- RolePermissions = command.Permissions.Select(p => new RolePermissionEntity
+ RolePermissions = [.. command.Permissions.Select(p => new RolePermissionEntity
{
RoleId = roleId,
PermissionId = p,
@@ -156,7 +161,7 @@ public class AddRoleCommandHandlerTests
Id = p,
PermissionName = AuthorizationPermission.CanViewUsers
}
- }).ToList()
+ })]
};
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any())
@@ -167,7 +172,7 @@ public class AddRoleCommandHandlerTests
.Returns(role);
// Act
- ErrorOr result = await _sut.Handle(command, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsError);
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs
index 9e4c4f24..c7d0e932 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidatorTests.cs
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
+using ErrorOr;
using FluentValidation.TestHelper;
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
+using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures;
using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -35,11 +38,10 @@ public class AddRoleCommandValidatorTests
command = command with { RoleName = null! };
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
- result.ShouldHaveValidationErrorFor(x => x.RoleName)
- .WithErrorMessage(Errors.Authorization.RoleNameCannotBeNull.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeNull);
}
[Fact]
@@ -50,11 +52,10 @@ public class AddRoleCommandValidatorTests
command = command with { RoleName = string.Empty };
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
- result.ShouldHaveValidationErrorFor(x => x.RoleName)
- .WithErrorMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeEmpty);
}
[Fact]
@@ -65,11 +66,10 @@ public class AddRoleCommandValidatorTests
command = command with { RoleName = " " };
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
- result.ShouldHaveValidationErrorFor(x => x.RoleName)
- .WithErrorMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.RoleNameCannotBeEmpty);
}
[Fact]
@@ -80,11 +80,10 @@ public class AddRoleCommandValidatorTests
command = command with { Permissions = null! };
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
- result.ShouldHaveValidationErrorFor(x => x.Permissions)
- .WithErrorMessage(Errors.Authorization.PermissionsListCannotBeNull.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.PermissionsListCannotBeNull);
}
[Fact]
@@ -95,11 +94,10 @@ public class AddRoleCommandValidatorTests
command = command with { Permissions = [] };
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
- result.ShouldHaveValidationErrorFor(x => x.Permissions)
- .WithErrorMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.PermissionsListCannotBeEmpty);
}
[Fact]
@@ -110,11 +108,10 @@ public class AddRoleCommandValidatorTests
command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] };
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
- result.ShouldHaveValidationErrorFor("Permissions[0]")
- .WithErrorMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.PermissionIdCannotBeEmpty);
}
[Fact]
@@ -124,7 +121,7 @@ public class AddRoleCommandValidatorTests
AddRoleCommand command = _fixture.CreateCommand();
// Act
- TestValidationResult result = _validator.TestValidate(command);
+ List result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs
index 4eb91472..2b106d8e 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures;
using Lumina.Contracts.Responses.Authorization;
@@ -38,6 +39,9 @@ public class GetRolePermissionsQueryHandlerTests
///
public GetRolePermissionsQueryHandlerTests()
{
+ IValidator mockValidator = Substitute.For>();
+ mockValidator.Validate(Arg.Any())
+ .Returns([]);
_mockUnitOfWork = Substitute.For();
_mockAuthorizationService = Substitute.For();
_mockCurrentUserService = Substitute.For();
@@ -51,7 +55,8 @@ public class GetRolePermissionsQueryHandlerTests
_sut = new GetRolePermissionsQueryHandler(
_mockAuthorizationService,
_mockCurrentUserService,
- _mockUnitOfWork);
+ _mockUnitOfWork,
+ mockValidator);
}
[Fact]
@@ -63,7 +68,7 @@ public class GetRolePermissionsQueryHandlerTests
.Returns(false);
// Act
- ErrorOr result = await _sut.Handle(query, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -84,7 +89,7 @@ public class GetRolePermissionsQueryHandlerTests
.Returns(error);
// Act
- ErrorOr result = await _sut.Handle(query, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -103,7 +108,7 @@ public class GetRolePermissionsQueryHandlerTests
.Returns((RoleEntity?)null);
// Act
- ErrorOr result = await _sut.Handle(query, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsError);
@@ -141,7 +146,7 @@ public class GetRolePermissionsQueryHandlerTests
.Returns(role);
// Act
- ErrorOr result = await _sut.Handle(query, CancellationToken.None);
+ ErrorOr result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsError);
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs
index 3d1483a7..2028d4e7 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidatorTests.cs
@@ -1,8 +1,11 @@
#region ========================================================================= USING =====================================================================================
+using ErrorOr;
using FluentValidation.TestHelper;
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
+using Lumina.Application.UnitTests.Common.Setup;
using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -31,11 +34,10 @@ public class GetRolePermissionsQueryValidatorTests
GetRolePermissionsQuery query = new(Guid.Empty);
// Act
- TestValidationResult result = _validator.TestValidate(query);
+ List result = _validator.TestValidate(query);
// Assert
- result.ShouldHaveValidationErrorFor(x => x.RoleId)
- .WithErrorMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
+ result.ShouldHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty);
}
[Fact]
@@ -45,9 +47,9 @@ public class GetRolePermissionsQueryValidatorTests
GetRolePermissionsQuery query = new(Guid.NewGuid());
// Act
- TestValidationResult result = _validator.TestValidate(query);
+ List result = _validator.TestValidate(query);
// Assert
- result.ShouldNotHaveValidationErrorFor(x => x.RoleId);
+ result.ShouldNotHaveValidationError(Errors.Authorization.RoleIdCannotBeEmpty);
}
}
diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs
index e5fcf3d5..88dc40e0 100644
--- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs
+++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs
@@ -1,23 +1,15 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
-using FastEndpoints;
-using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
-using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization;
using Lumina.Contracts.DTO.Authentication;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
-using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Permissions.GetPermissions;
using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.AddRole;
-using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authorization.GetAuthorization;
-using Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Authorization.GetAuthorization.Fixtures;
-using Mediator;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
-using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
@@ -32,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R
[ExcludeFromCodeCoverage]
public class AddRoleEndpointTests
{
- private readonly ISender _mockSender;
+ private readonly ICommandHandler> _mockHandler;
private readonly AddRoleEndpoint _sut;
///
@@ -40,8 +32,8 @@ public class AddRoleEndpointTests
///
public AddRoleEndpointTests()
{
- _mockSender = Substitute.For();
- _sut = Factory.Create(_mockSender);
+ _mockHandler = Substitute.For>>();
+ _sut = FastEndpoints.Factory.Create(_mockHandler);
}
[Fact]
@@ -51,7 +43,7 @@ public class AddRoleEndpointTests
AddRoleRequest request = new("Admin", [Guid.NewGuid()]);
CancellationToken cancellationToken = CancellationToken.None;
RolePermissionsResponse expectedResponse = new(new RoleDto(Guid.NewGuid(), "Admin"), []);
- _mockSender.Send(Arg.Any(), Arg.Any())
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(ErrorOrFactory.From(expectedResponse));
// Act
@@ -69,7 +61,7 @@ public class AddRoleEndpointTests
AddRoleRequest request = new("Admin", [Guid.NewGuid()]);
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("Role.Creation.Failed", "Failed to create role.");
- _mockSender.Send(Arg.Any(), Arg.Any())
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(expectedError);
// Act
@@ -94,14 +86,14 @@ public class AddRoleEndpointTests
// Arrange
AddRoleRequest request = new("Admin", [Guid.NewGuid()]);
CancellationToken cancellationToken = CancellationToken.None;
- _mockSender.Send(Arg.Any(), Arg.Any())
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), [])));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
- await _mockSender.Received(1).Send(
+ await _mockHandler.Received(1).HandleAsync(
Arg.Is(cmd =>
cmd.RoleName == request.RoleName &&
cmd.Permissions.SequenceEqual(request.Permissions!)),
@@ -116,16 +108,14 @@ public class AddRoleEndpointTests
TaskCompletionSource operationStarted = new();
TaskCompletionSource cancellationRequested = new();
- _mockSender.Send(Arg.Any(), Arg.Any())
- .Returns(info => new ValueTask>(
- Task.Run(async () =>
- {
- operationStarted.SetResult(true);
- await cancellationRequested.Task;
- info.Arg().ThrowIfCancellationRequested();
- return ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), []));
- }, info.Arg())
- ));
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(info => Task.Run(async () =>
+ {
+ operationStarted.SetResult(true);
+ await cancellationRequested.Task;
+ info.Arg().ThrowIfCancellationRequested();
+ return ErrorOrFactory.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), []));
+ }, info.Arg()));
// Act
Task operationTask = _sut.ExecuteAsync(new AddRoleRequest("Admin", []), cts.Token);
diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs
index 98bcb904..9cadf1c4 100644
--- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs
+++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs
@@ -1,13 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
-using FastEndpoints;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
using Lumina.Contracts.DTO.Authentication;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions;
-using Mediator;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
@@ -25,7 +24,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Admin.Authorization.R
[ExcludeFromCodeCoverage]
public class GetRolePermissionsEndpointTests
{
- private readonly ISender _mockSender;
+ private readonly IQueryHandler> _mockHandler;
private readonly GetRolePermissionsEndpoint _sut;
///
@@ -33,8 +32,8 @@ public class GetRolePermissionsEndpointTests
///
public GetRolePermissionsEndpointTests()
{
- _mockSender = Substitute.For();
- _sut = Factory.Create(_mockSender);
+ _mockHandler = Substitute.For>>();
+ _sut = FastEndpoints.Factory.Create(_mockHandler);
}
[Fact]
@@ -47,7 +46,7 @@ public class GetRolePermissionsEndpointTests
new RoleDto(Guid.NewGuid(), "Admin"),
[new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)]
);
- _mockSender.Send(Arg.Any(), Arg.Any())
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(ErrorOrFactory.From(expectedResponse));
// Act
@@ -65,7 +64,7 @@ public class GetRolePermissionsEndpointTests
GetRolePermissionsRequest request = new(Guid.NewGuid());
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("Role.Permissions.NotFound", "Role permissions not found.");
- _mockSender.Send(Arg.Any(), Arg.Any())
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(expectedError);
// Act
@@ -91,7 +90,7 @@ public class GetRolePermissionsEndpointTests
Guid roleId = Guid.NewGuid();
GetRolePermissionsRequest request = new(roleId);
CancellationToken cancellationToken = CancellationToken.None;
- _mockSender.Send(Arg.Any(), Arg.Any())
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
.Returns(ErrorOrFactory.From(new RolePermissionsResponse(
new RoleDto(Guid.NewGuid(), "Admin"),
[]
@@ -101,7 +100,7 @@ public class GetRolePermissionsEndpointTests
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
- await _mockSender.Received(1).Send(
+ await _mockHandler.Received(1).HandleAsync(
Arg.Is(cmd => cmd.RoleId == request.RoleId),
Arg.Is(cancellationToken));
}
@@ -114,19 +113,17 @@ public class GetRolePermissionsEndpointTests
TaskCompletionSource operationStarted = new();
TaskCompletionSource cancellationRequested = new();
- _mockSender.Send(Arg.Any(), Arg.Any())
- .Returns(info => new ValueTask>(
- Task.Run(async () =>
- {
- operationStarted.SetResult(true);
- await cancellationRequested.Task;
- info.Arg().ThrowIfCancellationRequested();
- return ErrorOrFactory.From(new RolePermissionsResponse(
- new RoleDto(Guid.NewGuid(), "Admin"),
- []
- ));
- }, info.Arg())
- ));
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(info => Task.Run(async () =>
+ {
+ operationStarted.SetResult(true);
+ await cancellationRequested.Task;
+ info.Arg().ThrowIfCancellationRequested();
+ return ErrorOrFactory.From(new RolePermissionsResponse(
+ new RoleDto(Guid.NewGuid(), "Admin"),
+ []
+ ));
+ }, info.Arg()));
// Act
Task operationTask = _sut.ExecuteAsync(new GetRolePermissionsRequest(Guid.NewGuid()), cts.Token);