Compare commits

...

9 Commits

Author SHA1 Message Date
Developer 02
6a4f8a12c7 add not-found exception to handle on endpoint 2025-08-03 09:31:36 +02:00
Developer 02
1b9dac93a5 add ExceptionHandlingMiddleware 2025-08-03 09:27:19 +02:00
Developer 02
2bdc8ebafd feat(ActiveDirectoryController): add with GetAll endpoint 2025-08-03 09:18:07 +02:00
Developer 02
52d36004ae feat(API): Initialisierung, um .NET 7, 8 und 9 unterstützen zu können 2025-08-03 09:07:10 +02:00
Developer 02
452cc6345c feat(DirectorySearchQuery): Implementierung von DirectorySearchQueryHandler mit Eigenschaftsfilterung und Ergebnissammlung
- Aktualisierung von DirectorySearchQuery, um Eigenschaften zu akzeptieren und IEnumerable<ResultPropertyCollection> zurückzugeben
- Implementierung von DirectorySearchQueryHandler, um die Suche mit benutzerdefinierten Filtern, Bereichen und Eigenschaftsauswahl auszuführen
- Hinzufügen einer Logik, um nur angeforderte Eigenschaften zu laden, wenn diese angegeben sind
- Ersetzen von NotImplementedException durch die tatsächliche DirectorySearcher-Logik
2025-08-03 08:53:23 +02:00
Developer 02
e75127c74e feat(DirectorySearchQuery): create to handle directory search
- define query model
2025-08-02 21:24:19 +02:00
Developer 02
39982139d3 refactor(ADConfigurationOptions): rename MediatRLicense as MediatRLicenseKey 2025-08-02 19:33:10 +02:00
Developer 02
409e43460d feat(DependencyInjection): Add MediatR and configure dependency injection 2025-08-02 19:29:53 +02:00
Developer 02
78021a95a4 feat(ActiveDirectoryOptions): add configuration inc connection parameters 2025-08-02 11:06:35 +02:00
11 changed files with 258 additions and 50 deletions

View File

@ -7,7 +7,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.ActiveDirectory", "src\DigitalData.ActiveDirectory\DigitalData.ActiveDirectory.csproj", "{26B810C2-8D06-42CF-999F-CB508C9D2D01}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.ActiveDirectory.API", "src\DigitalData.ActiveDirectory.API\DigitalData.ActiveDirectory.API.csproj", "{2B3A9620-E298-00ED-CC4B-A6A83F822A01}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.ActiveDirectory.API", "src\DigitalData.ActiveDirectory.API\DigitalData.ActiveDirectory.API.csproj", "{4994DDB6-8106-4290-85B3-99C9C98FA0A7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -31,25 +33,25 @@ Global
{26B810C2-8D06-42CF-999F-CB508C9D2D01}.Release|x64.Build.0 = Release|Any CPU
{26B810C2-8D06-42CF-999F-CB508C9D2D01}.Release|x86.ActiveCfg = Release|Any CPU
{26B810C2-8D06-42CF-999F-CB508C9D2D01}.Release|x86.Build.0 = Release|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Debug|x64.ActiveCfg = Debug|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Debug|x64.Build.0 = Debug|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Debug|x86.ActiveCfg = Debug|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Debug|x86.Build.0 = Debug|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Release|Any CPU.Build.0 = Release|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Release|x64.ActiveCfg = Release|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Release|x64.Build.0 = Release|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Release|x86.ActiveCfg = Release|Any CPU
{2B3A9620-E298-00ED-CC4B-A6A83F822A01}.Release|x86.Build.0 = Release|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Debug|x64.ActiveCfg = Debug|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Debug|x64.Build.0 = Debug|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Debug|x86.ActiveCfg = Debug|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Debug|x86.Build.0 = Debug|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Release|Any CPU.Build.0 = Release|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Release|x64.ActiveCfg = Release|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Release|x64.Build.0 = Release|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Release|x86.ActiveCfg = Release|Any CPU
{4994DDB6-8106-4290-85B3-99C9C98FA0A7}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{26B810C2-8D06-42CF-999F-CB508C9D2D01} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{2B3A9620-E298-00ED-CC4B-A6A83F822A01} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{4994DDB6-8106-4290-85B3-99C9C98FA0A7} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2F00C94F-CA5D-4F53-A608-B935F0FD4B46}

View File

@ -0,0 +1,20 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.DirectoryServices;
namespace DigitalData.ActiveDirectory.API.Controllers;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
[Route("api/[controller]")]
[ApiController]
public class ActiveDirectoryController : ControllerBase
{
private readonly IMediator _mediator;
public ActiveDirectoryController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IEnumerable<ResultPropertyCollection>> GetAll([FromQuery] DirectorySearchQuery query) => await _mediator.Send(query);
}

View File

@ -1,14 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.18" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DigitalData.ActiveDirectory\DigitalData.ActiveDirectory.csproj" />
</ItemGroup>
</Project>

View File

@ -1,6 +0,0 @@
@DigitalData.ActiveDirectory.API_HostAddress = http://localhost:5092
GET {{DigitalData.ActiveDirectory.API_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -0,0 +1,84 @@
using DigitalData.Core.Exceptions;
using System.Net;
using System.Text.Json;
namespace DigitalData.ActiveDirectory.API.Middleware;
//TODO: Fix and use DigitalData.Core.Exceptions.Middleware
/// <summary>
/// Middleware for handling exceptions globally in the application.
/// Captures exceptions thrown during the request pipeline execution,
/// logs them, and returns an appropriate HTTP response with a JSON error message.
/// </summary>
[Obsolete("Use DigitalData.Core.Exceptions.Middleware")]
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
/// <param name="next">The next middleware in the request pipeline.</param>
/// <param name="logger">The logger instance for logging exceptions.</param>
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
/// <summary>
/// Invokes the middleware to handle the HTTP request.
/// </summary>
/// <param name="context">The HTTP context of the current request.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context); // Continue down the pipeline
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex, _logger);
}
}
/// <summary>
/// Handles exceptions by logging them and writing an appropriate JSON response.
/// </summary>
/// <param name="context">The HTTP context of the current request.</param>
/// <param name="exception">The exception that occurred.</param>
/// <param name="logger">The logger instance for logging the exception.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger)
{
context.Response.ContentType = "application/json";
string message;
switch (exception)
{
case BadRequestException badRequestEx:
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
message = badRequestEx.Message;
break;
case NotFoundException notFoundEx:
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
message = notFoundEx.Message;
break;
default:
logger.LogError(exception, "Unhandled exception occurred.");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
message = "An unexpected error occurred.";
break;
}
await context.Response.WriteAsync(JsonSerializer.Serialize(new
{
message
}));
}
}

View File

@ -1,12 +1,18 @@
using DigitalData.ActiveDirectory.API.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseMiddleware<ExceptionHandlingMiddleware>();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
@ -16,29 +22,8 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.UseAuthorization();
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.MapControllers();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

View File

@ -4,8 +4,8 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:34411",
"sslPort": 44378
"applicationUrl": "http://localhost:40890",
"sslPort": 44353
}
},
"profiles": {
@ -14,7 +14,7 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5092",
"applicationUrl": "http://localhost:5215",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@ -24,7 +24,7 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7221;http://localhost:5092",
"applicationUrl": "https://localhost:7001;http://localhost:5215",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -0,0 +1,10 @@
namespace DigitalData.ActiveDirectory;
public class ActiveDirectoryOptions
{
public string Path { get; set; } = null!;
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
}

View File

@ -0,0 +1,35 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.ActiveDirectory;
public static class DependencyInjection
{
public static IServiceCollection AddActiveDirectory(this IServiceCollection services, Action<ADConfigurationOptions>? options = null)
{
var cOptions = new ADConfigurationOptions();
options?.Invoke(cOptions);
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblies(typeof(DependencyInjection).Assembly);
cfg.LicenseKey = cOptions.MediatRLicenseKey;
});
if (cOptions.Configuration is null)
services.Configure<ActiveDirectoryOptions>(o => o = cOptions);
else
services.Configure<ActiveDirectoryOptions>(cOptions.Configuration);
return services;
}
public class ADConfigurationOptions : ActiveDirectoryOptions
{
internal ADConfigurationOptions() { }
public string? MediatRLicenseKey { get; set; }
public IConfiguration? Configuration { get; set; }
}
}

View File

@ -1,9 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DigitalData.Core.Exceptions" Version="1.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="7.0.1" />
<PackageReference Include="MediatR" Version="13.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="7.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net9.0'">
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="9.0.5" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,48 @@
using DigitalData.Core.Exceptions;
using MediatR;
using Microsoft.Extensions.Options;
using System.DirectoryServices;
namespace DigitalData.ActiveDirectory;
public record DirectorySearchQuery(string? Filter = null, SearchScope Scope = SearchScope.Subtree, int SizeLimit = 5000, params string[] properties)
: IRequest<IEnumerable<ResultPropertyCollection>>
{
public Action<DirectorySearcher>? Options { get; set; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public class DirectorySearchQueryHandler(IOptions<ActiveDirectoryOptions> options) : IRequestHandler<DirectorySearchQuery, IEnumerable<ResultPropertyCollection>>
{
public DirectoryEntry DirectoryEntry => new ()
{
Path = options.Value.Path,
Username = options.Value.Username,
Password = options.Value.Password
};
public Task<IEnumerable<ResultPropertyCollection>> Handle(DirectorySearchQuery request, CancellationToken cancellationToken = default)
{
return Task.Run(() =>
{
using var _dirEntry = DirectoryEntry;
using var searcher = new DirectorySearcher()
{
Filter = request.Filter,
SearchScope = request.Scope,
SizeLimit = request.SizeLimit,
SearchRoot = _dirEntry
};
request.Options?.Invoke(searcher);
if (request.properties.Length > 0)
searcher.PropertiesToLoad.Clear();
searcher.PropertiesToLoad.AddRange(request.properties.Where(p => p is not null).ToArray());
var res = searcher.FindAll().Cast<SearchResult>().Select(r => r.Properties);
return res.Any() ? res : throw new NotFoundException();
});
}
}