Complete Step 1.1: ValidatePDF Application Layer

Updated PHASENPLAN and ROADMAP to reflect progress on Feature 1 - ValidatePDF (75% complete). Marked Step 1.1 as completed, including MediatR setup, pipeline behaviors (`ValidationBehavior`, `LoggingBehavior`), ValidatePDF feature (Query, Handler, Validator), and DTOs.

Added `DependencyInjection.cs` for Application Layer DI configuration. Introduced `LoggingBehavior` and `ValidationBehavior` for MediatR pipelines. Implemented `ValidatePdfHandler`, `ValidatePdfQuery`, and `ValidatePdfValidator`.

Created DTOs (`ValidatePdfRequest`, `ValidatePdfResponse`) for the ValidatePDF feature. Added unit tests for `ValidatePdfHandler` to verify metadata handling and exception propagation.

Removed unused folder references in `DocumentOperator.Application.csproj`.
This commit is contained in:
OlgunR
2026-06-25 15:23:58 +02:00
parent 62c67d86d4
commit afc0e34312
12 changed files with 367 additions and 48 deletions

View File

@@ -0,0 +1,66 @@
using MediatR;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace DocumentOperator.Application.Common.Behaviors;
/// <summary>
/// MediatR Pipeline Behavior that logs requests and tracks performance
/// Executes AFTER ValidationBehavior, BEFORE Handler
/// </summary>
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
// Request Start
_logger.LogInformation("Handling {RequestName}: {@Request}", requestName, request);
// Performance Tracking
var stopwatch = Stopwatch.StartNew();
try
{
// Handler ausführen
var response = await next();
stopwatch.Stop();
// Request Success
_logger.LogInformation(
"Handled {RequestName} in {ElapsedMs}ms",
requestName,
stopwatch.ElapsedMilliseconds
);
return response;
}
catch (Exception ex)
{
stopwatch.Stop();
// Request Failed
_logger.LogError(
ex,
"Error handling {RequestName} after {ElapsedMs}ms: {ErrorMessage}",
requestName,
stopwatch.ElapsedMilliseconds,
ex.Message
);
throw; // Exception weiterwerfen (wird von Exception Middleware gefangen)
}
}
}

View File

@@ -0,0 +1,54 @@
using FluentValidation;
using MediatR;
namespace DocumentOperator.Application.Common.Behaviors;
/// <summary>
/// MediatR Pipeline Behavior that validates requests using FluentValidation
/// Executes BEFORE the Handler
/// </summary>
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
// Wenn keine Validators registriert sind, direkt weiter zum Handler
if (!_validators.Any())
{
return await next();
}
// Validation Context erstellen
var context = new ValidationContext<TRequest>(request);
// Alle Validators parallel ausführen
var validationResults = await Task.WhenAll(
_validators.Select(v => v.ValidateAsync(context, cancellationToken))
);
// Fehler sammeln
var failures = validationResults
.Where(r => !r.IsValid)
.SelectMany(r => r.Errors)
.ToList();
// Bei Fehlern: ValidationException werfen (wird von Exception Middleware gefangen)
if (failures.Any())
{
throw new ValidationException(failures);
}
// Validation erfolgreich ? weiter zum Handler
return await next();
}
}

View File

@@ -0,0 +1,7 @@
namespace DocumentOperator.Application.Common.DTOs;
/// <summary>
/// Request DTO for ValidatePdf endpoint
/// </summary>
/// <param name="Base64Pdf">PDF content as Base64 string</param>
public record ValidatePdfRequest(string Base64Pdf);

View File

@@ -0,0 +1,14 @@
namespace DocumentOperator.Application.Common.DTOs;
/// <summary>
/// Response DTO for ValidatePdf endpoint
/// Contains PDF metadata
/// </summary>
public record ValidatePdfResponse(
int PageCount,
long FileSizeBytes,
double FileSizeMB,
string PdfVersion,
bool HasAttachments,
int AttachmentCount
);

View File

@@ -0,0 +1,33 @@
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
namespace DocumentOperator.Application;
/// <summary>
/// Dependency Injection configuration for Application Layer
/// </summary>
public static class DependencyInjection
{
/// <summary>
/// Registers Application Layer services (MediatR, FluentValidation, Behaviors)
/// </summary>
public static IServiceCollection AddApplication(this IServiceCollection services)
{
var assembly = typeof(DependencyInjection).Assembly;
// Register MediatR (scannt Assembly nach Handlers)
services.AddMediatR(config =>
{
config.RegisterServicesFromAssembly(assembly);
// Pipeline Behaviors (Reihenfolge wichtig!)
config.AddOpenBehavior(typeof(Common.Behaviors.ValidationBehavior<,>));
config.AddOpenBehavior(typeof(Common.Behaviors.LoggingBehavior<,>));
});
// Register FluentValidation (scannt Assembly nach Validators)
services.AddValidatorsFromAssembly(assembly);
return services;
}
}

View File

@@ -17,15 +17,12 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Common\Behaviors\" />
<Folder Include="Common\DTOs\" />
<Folder Include="Common\Mappings\" />
<Folder Include="DependencyInjection\" />
<Folder Include="Features\Documents\ExtractAttachments\" />
<Folder Include="Features\Documents\ConcatenatePdfs\" />
<Folder Include="Features\Documents\ApplyStamp\" />
<Folder Include="Features\Documents\EmbedCertificate\" />
<Folder Include="Features\Documents\ValidatePdf\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,33 @@
using DocumentOperator.Application.Common.Interfaces;
using DocumentOperator.Domain.Models.ValueObjects;
using MediatR;
namespace DocumentOperator.Application.Features.Documents.ValidatePdf;
/// <summary>
/// Handler for ValidatePdfQuery
/// Orchestrates PDF validation using IPdfProcessor
/// </summary>
public class ValidatePdfHandler : IRequestHandler<ValidatePdfQuery, PdfMetadata>
{
private readonly IPdfProcessor _pdfProcessor;
public ValidatePdfHandler(IPdfProcessor pdfProcessor)
{
_pdfProcessor = pdfProcessor;
}
/// <summary>
/// Validates PDF and returns metadata
/// </summary>
public async Task<PdfMetadata> Handle(ValidatePdfQuery request, CancellationToken cancellationToken)
{
// Value Object ? Byte Array
byte[] pdfBytes = request.PdfContent.ToByteArray();
// DevExpress Service aufrufen (kann PdfProcessingException werfen)
var metadata = await _pdfProcessor.ValidateAsync(pdfBytes);
return metadata;
}
}

View File

@@ -0,0 +1,10 @@
using DocumentOperator.Domain.Models.ValueObjects;
using MediatR;
namespace DocumentOperator.Application.Features.Documents.ValidatePdf;
/// <summary>
/// Query to validate a PDF document and return metadata
/// </summary>
/// <param name="PdfContent">PDF content as Base64 string (validated by Value Object)</param>
public record ValidatePdfQuery(Base64String PdfContent) : IRequest<PdfMetadata>;

View File

@@ -0,0 +1,17 @@
using FluentValidation;
namespace DocumentOperator.Application.Features.Documents.ValidatePdf;
/// <summary>
/// Validator for ValidatePdfQuery
/// Validates that PdfContent is not null (Base64String already validates format in its constructor)
/// </summary>
public class ValidatePdfValidator : AbstractValidator<ValidatePdfQuery>
{
public ValidatePdfValidator()
{
RuleFor(x => x.PdfContent)
.NotNull()
.WithMessage("PDF content is required");
}
}