This commit is contained in:
Janus C. H. Knudsen 2025-03-10 15:56:22 +01:00
parent f3ab94eff1
commit 31666b4ba0
34 changed files with 140 additions and 83 deletions

View file

@ -1,4 +1,4 @@
namespace PlanTempus.Core.Sql.ConnectionFactory
namespace PlanTempus.Core.Database.ConnectionFactory
{
public interface IDbConnectionFactory
{

View file

@ -1,6 +1,7 @@
using Npgsql;
using System.Data;
namespace PlanTempus.Core.Sql.ConnectionFactory
using System.Data;
using Npgsql;
namespace PlanTempus.Core.Database.ConnectionFactory
{
public record ConnectionStringParameters(string User, string Pwd);

View file

@ -2,7 +2,7 @@
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
namespace PlanTempus.Core.Sql;
namespace PlanTempus.Core.Database;
public class DatabaseScope : IDisposable
{
@ -12,6 +12,7 @@ public class DatabaseScope : IDisposable
{
Connection = connection;
_operation = operation;
_operation.Telemetry.Success = true;
}
public IDbConnection Connection { get; }
@ -22,11 +23,6 @@ public class DatabaseScope : IDisposable
Connection.Dispose();
}
public void Success()
{
_operation.Telemetry.Success = true;
}
public void Error(Exception ex)
{
_operation.Telemetry.Success = false;

View file

@ -1,6 +1,6 @@
using System.Data;
namespace PlanTempus.Core.Sql;
namespace PlanTempus.Core.Database;
public interface IDatabaseOperations
{

View file

@ -1,9 +1,9 @@
using System.Data;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
namespace PlanTempus.Core.Sql;
namespace PlanTempus.Core.Database;
public class SqlOperations : IDatabaseOperations
{
@ -32,7 +32,6 @@ public class SqlOperations : IDatabaseOperations
try
{
var result = await operation(scope.Connection);
scope.Success();
return result;
}
catch (Exception ex)
@ -48,7 +47,6 @@ public class SqlOperations : IDatabaseOperations
try
{
await operation(scope.Connection);
scope.Success();
}
catch (Exception ex)
{

View file

@ -1,5 +1,5 @@
using Autofac;
using PlanTempus.Core.Logging;
using PlanTempus.Core.SeqLogging;
namespace PlanTempus.Core.ModuleRegistry
{

View file

@ -10,13 +10,12 @@ namespace PlanTempus.Core.ModuleRegistry
protected override void Load(ContainerBuilder builder)
{
var configuration = TelemetryConfiguration.CreateDefault();
configuration.ConnectionString = TelemetryConfig.ConnectionString;
configuration.TelemetryChannel.DeveloperMode = true;
var client = new Microsoft.ApplicationInsights.TelemetryClient(configuration);
client.Context.GlobalProperties["Application"] = GetType().Namespace.Split('.')[0];
client.Context.GlobalProperties["Application"] = GetType().Namespace?.Split('.')[0];
client.Context.GlobalProperties["MachineName"] = Environment.MachineName;
client.Context.GlobalProperties["Version"] = Environment.Version.ToString();
client.Context.GlobalProperties["ProcessorCount"] = Environment.ProcessorCount.ToString();
@ -34,10 +33,11 @@ namespace PlanTempus.Core.ModuleRegistry
configuration.TelemetryChannel = new Telemetry.SeqTelemetryChannel(messageChannel, client);
}
var telemetryProcessorChain = new Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryProcessorChainBuilder(configuration);
var telemetryProcessorChain =
new Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryProcessorChainBuilder(
configuration);
telemetryProcessorChain.Use(next => new Telemetry.Enrichers.EnrichWithMetaTelemetry(next));
telemetryProcessorChain.Build();
}
}

View file

@ -4,7 +4,7 @@ using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.Hosting;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.Core.Logging
namespace PlanTempus.Core.SeqLogging
{
public class SeqBackgroundService : BackgroundService
{

View file

@ -1,4 +1,4 @@
namespace PlanTempus.Core.Logging
namespace PlanTempus.Core.SeqLogging
{
public record SeqConfiguration(string IngestionEndpoint, string ApiKey, string Environment);
}

View file

@ -1,4 +1,4 @@
namespace PlanTempus.Core.Logging
namespace PlanTempus.Core.SeqLogging
{
public class SeqHttpClient
{

View file

@ -1,13 +1,11 @@
using Microsoft.ApplicationInsights.DataContracts;
using System.Text;
using System.Text;
using Microsoft.ApplicationInsights.DataContracts;
namespace PlanTempus.Core.Logging
namespace PlanTempus.Core.SeqLogging
{
public class SeqLogger<T>
{
private readonly SeqHttpClient _httpClient;
private readonly string _environmentName;
private readonly string _machineName;
private readonly SeqConfiguration _configuration;
public SeqLogger(SeqHttpClient httpClient, SeqConfiguration configuration)
@ -23,8 +21,7 @@ namespace PlanTempus.Core.Logging
{ "@t", trace.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", trace.Message },
{ "@l", MapSeverityToLevel(trace.SeverityLevel) },
{ "Environment", _environmentName },
{ "MachineName", _machineName }
{ "Environment", _configuration.Environment },
};
foreach (var prop in trace.Properties)
@ -43,8 +40,7 @@ namespace PlanTempus.Core.Logging
{ "@t", evt.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", evt.Name },
{ "@l", "Information" },
{ "Environment", _environmentName },
{ "MachineName", _machineName }
{ "Environment", _configuration.Environment }
};
foreach (var prop in evt.Properties)
@ -67,9 +63,8 @@ namespace PlanTempus.Core.Logging
{ "@mt", ex.Exception.Message },
{ "@l", "Error" },
{ "@x", FormatExceptionForSeq(ex.Exception) },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "ExceptionType", ex.Exception.GetType().Name },
{ "Environment", _configuration.Environment },
{ "ExceptionType", ex.Exception.GetType().Name }
};
foreach (var prop in ex.Properties)
@ -88,8 +83,7 @@ namespace PlanTempus.Core.Logging
{ "@t", dep.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", $"Dependency: {dep.Name}" },
{ "@l", dep.Success ?? true ? "Information" : "Error" },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "Environment", _configuration.Environment },
{ "DependencyType", dep.Type },
{ "Target", dep.Target },
{ "Duration", dep.Duration.TotalMilliseconds }

View file

@ -1,7 +1,7 @@
using Insight.Database;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Database.Core;
using System.Data;
using PlanTempus.Core.Database.ConnectionFactory;
namespace PlanTempus.Database.ConfigurationManagementSystem;

View file

@ -1,6 +1,6 @@
using System.Data;
using Insight.Database;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
using PlanTempus.Database.Common;
namespace PlanTempus.Database.Core.DCL

View file

@ -1,6 +1,6 @@
using System.Data;
using Insight.Database;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
using PlanTempus.Database.Common;
namespace PlanTempus.Database.Core.DCL

View file

@ -1,6 +1,6 @@
using System.Data;
using Insight.Database;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
using PlanTempus.Database.Common;
using PlanTempus.Database.Core;

View file

@ -1,6 +1,6 @@
using Insight.Database;
using PlanTempus.Core.Sql.ConnectionFactory;
using System.Data;
using PlanTempus.Core.Database.ConnectionFactory;
namespace PlanTempus.Database.Core.DDL
{

View file

@ -1,4 +1,4 @@
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
namespace PlanTempus.Database.Core
{

View file

@ -1,6 +1,6 @@
using Autofac;
using PlanTempus.Core.Sql;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database;
using PlanTempus.Core.Database.ConnectionFactory;
namespace PlanTempus.Database.ModuleRegistry
{

View file

@ -0,0 +1,24 @@
using Autofac;
using PlanTempus.Core.SeqLogging;
namespace PlanTempus.Components.ModuleRegistry
{
public class CommandModule : Module
{
// public required SeqConfiguration SeqConfiguration { get; set; }
protected override void Load(ContainerBuilder builder)
{
// Registrer alle handlers
builder.RegisterAssemblyTypes()
.AsClosedTypesOf(typeof(ICommandHandler<>))
.InstancePerLifetimeScope();
// Registrer en decorator for alle ICommandHandler<TCommand>
builder.RegisterGenericDecorator(
typeof(LoggingCommandHandlerDecorator<>), // Din decorator-klasse
typeof(ICommandHandler<>)); // Interface, der skal dekoreres
}
}
}

View file

@ -1,6 +1,6 @@
using Insight.Database;
using Microsoft.ApplicationInsights;
using PlanTempus.Core.Sql;
using PlanTempus.Core.Database;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.Components.Organizations.Create
@ -32,8 +32,6 @@ namespace PlanTempus.Components.Organizations.Create
transaction.Commit();
db.Success();
telemetryClient.TrackTrace(GetType().Name, orgResult.Format());
return orgResult;
}

View file

@ -1,9 +1,15 @@
namespace PlanTempus.Components.Users.Create
{
public class CreateUserCommand
public interface ICommand
{
Guid CorrelationId { get; set; }
}
public class CreateUserCommand : ICommand
{
public string Email { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; } = true;
public required Guid CorrelationId { get; set; }
}
}

View file

@ -1,15 +1,22 @@
using Insight.Database;
using Microsoft.ApplicationInsights;
using Npgsql;
using PlanTempus.Components.Users.Exceptions;
using PlanTempus.Core;
using PlanTempus.Core.Sql;
using PlanTempus.Core.Database;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.Components.Users.Create
{
public interface ICommandHandler<T, TResult>
{
Task<TResult> Handle(T input);
}
public class CreateUserHandler(
TelemetryClient telemetryClient,
IDatabaseOperations databaseOperations,
ISecureTokenizer secureTokenizer)
ISecureTokenizer secureTokenizer) : ICommandHandler<CreateUserCommand, CreateUserResult>
{
public async Task<CreateUserResult> Handle(CreateUserCommand command)
{
@ -36,13 +43,17 @@ namespace PlanTempus.Components.Users.Create
});
db.Success();
var result = data.First();
telemetryClient.TrackTrace(GetType().Name, result.Format());
return result;
}
catch (PostgresException ex) when (ex.SqlState == "23505")
{
db.Error(ex);
throw new EmailAlreadyRegistreredException();
}
catch (Exception ex)
{
db.Error(ex);

View file

@ -0,0 +1,25 @@
using Microsoft.ApplicationInsights;
namespace PlanTempus.Components.Users.Create;
public class CreateUserHandlerDecorator : ICommandHandler<CreateUserCommand, CreateUserResult>
{
private readonly ICommandHandler<CreateUserCommand, CreateUserResult> _decoratedHandler;
private readonly TelemetryClient _telemetryClient;
public CreateUserHandlerDecorator(
ICommandHandler<CreateUserCommand, CreateUserResult> decoratedHandler,
TelemetryClient telemetryClient)
{
_decoratedHandler = decoratedHandler;
_telemetryClient = telemetryClient;
}
public async Task<CreateUserResult> Handle(CreateUserCommand command)
{
_telemetryClient.TrackTrace($"Before handling {nameof(CreateUserCommand)}");
var result = await _decoratedHandler.Handle(command);
_telemetryClient.TrackTrace($"After handling {nameof(CreateUserCommand)}");
return result;
}
}

View file

@ -0,0 +1,6 @@
namespace PlanTempus.Components.Users.Exceptions;
public class EmailAlreadyRegistreredException: Exception
{
}

View file

@ -3,12 +3,12 @@ using Insight.Database;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Npgsql;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Database.ConfigurationManagementSystem;
using PlanTempus.Database.Core.DCL;
using PlanTempus.Database.Core.DDL;
using System.Data;
using System.Diagnostics;
using PlanTempus.Core.Database.ConnectionFactory;
namespace PlanTempus.SetupInfrastructure
{

View file

@ -2,6 +2,7 @@
using PlanTempus.Core.Configurations;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.ModuleRegistry;
using PlanTempus.Core.SeqLogging;
using PlanTempus.Database.Core;
namespace PlanTempus.SetupInfrastructure
@ -34,7 +35,7 @@ namespace PlanTempus.SetupInfrastructure
builder.RegisterModule(new SeqLoggingModule
{
SeqConfiguration = configuration.GetSection("SeqConfiguration").ToObject<Core.Logging.SeqConfiguration>()
SeqConfiguration = configuration.GetSection("SeqConfiguration").ToObject<SeqConfiguration>()
});

View file

@ -2,7 +2,7 @@
using Autofac;
using Insight.Database;
using Newtonsoft.Json;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
using Shouldly;
namespace PlanTempus.X.TDD.ConfigurationSystem;

View file

@ -3,7 +3,7 @@ using Insight.Database;
using PlanTempus.Core.Configurations;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Configurations.SmartConfigProvider;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Core.Database.ConnectionFactory;
using Shouldly;
namespace PlanTempus.X.TDD.ConfigurationTests;

View file

@ -3,7 +3,7 @@ using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
using PlanTempus.Core.SeqLogging;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.X.TDD.Logging;

View file

@ -1,7 +1,7 @@
using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
using PlanTempus.Core.SeqLogging;
namespace PlanTempus.X.TDD.Logging;

View file

@ -2,7 +2,7 @@ using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
using PlanTempus.Core.SeqLogging;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.X.TDD.Logging;

View file

@ -20,6 +20,7 @@
<ItemGroup>
<ProjectReference Include="..\Application\PlanTempus.Application.csproj"/>
<ProjectReference Include="..\Database\PlanTempus.Database.csproj"/>
<ProjectReference Include="..\PlanTempus.Components\PlanTempus.Components.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -1,7 +1,8 @@
using Autofac;
using Insight.Database;
using PlanTempus.Core.Sql;
using PlanTempus.Core.Sql.ConnectionFactory;
using PlanTempus.Components.Users.Exceptions;
using PlanTempus.Core.Database;
using PlanTempus.Core.Database.ConnectionFactory;
using Shouldly;
namespace PlanTempus.X.TDD;
@ -38,8 +39,6 @@ public class PostgresTests : TestFixture
{
var user = await db.Connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tables limit 5");
db.Success();
}
catch (Exception ex)
{
@ -56,8 +55,6 @@ public class PostgresTests : TestFixture
{
var user = await db.Connection.QuerySqlAsync<string>(
"SELECT tablename FROM pg_tables limit 5");
db.Success();
}
catch (Exception ex)
{
@ -69,7 +66,7 @@ public class PostgresTests : TestFixture
public async Task TestForUniqueUserEmail()
{
using var db = _databaseOperations.CreateScope(nameof(TestForUniqueUserEmail));
try
// try
{
var sql = @"
INSERT INTO system.users(email, password_hash, security_stamp, email_confirmed,
@ -81,7 +78,7 @@ public class PostgresTests : TestFixture
var parameters = new
{
Email = "elon.musk@mars.com",
Email = "jarjarbinks22233@mars.com",
PasswordHash = "MartianRover2025",
SecurityStamp = "MarsOrBust",
EmailConfirmed = true,
@ -92,18 +89,17 @@ public class PostgresTests : TestFixture
var user = await db.Connection.QuerySqlAsync<dynamic>(sql, parameters);
user.ShouldNotBeNull();
// ((string)user.email).ShouldBe("elon.musk@mars.com");
// ((bool)user.is_active).ShouldBeTrue();
// user.ShouldNotBeNull();
db.Success();
//try insert, to test exception
var ex = await Should.ThrowAsync<EmailAlreadyRegistreredException>(async () =>
await db.Connection.ExecuteAsync(sql, parameters));
}
catch (Exception ex)
{
db.Error(ex);
// catch (Exception ex)
// {
// db.Error(ex);
// }
}
}
[TestMethod]
public async Task TestSimpleDatabaseOperation()

View file

@ -4,8 +4,8 @@ using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Logging;
using PlanTempus.Core.Configurations;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Logging;
using PlanTempus.Core.ModuleRegistry;
using PlanTempus.Core.SeqLogging;
using PlanTempus.Database.ModuleRegistry;
namespace PlanTempus.X.TDD;