This commit is contained in:
Janus Knudsen 2025-03-03 17:40:16 +01:00
parent 71576a4b1f
commit 73a1f11e99
21 changed files with 236 additions and 228 deletions

100
Core/Sql/SqlOperations.cs Normal file
View file

@ -0,0 +1,100 @@
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using PlanTempus.Core.Sql.ConnectionFactory;
using System.Data;
namespace PlanTempus.Core.Sql
{
public class DatabaseScope : IDisposable
{
private readonly IDbConnection _connection;
private readonly IOperationHolder<DependencyTelemetry> _operation;
public DatabaseScope(IDbConnection connection, IOperationHolder<DependencyTelemetry> operation)
{
_connection = connection;
_operation = operation;
}
public IDbConnection Connection => _connection;
public void Success()
{
_operation.Telemetry.Success = true;
}
public void Error(Exception ex)
{
_operation.Telemetry.Success = false;
_operation.Telemetry.Properties["Error"] = ex.Message;
}
public void Dispose()
{
_operation.Dispose();
_connection.Dispose();
}
}
public interface IDatabaseOperations
{
DatabaseScope CreateScope(string operationName);
Task<T> ExecuteAsync<T>(Func<IDbConnection, Task<T>> operation, string operationName);
Task ExecuteAsync(Func<IDbConnection, Task> operation, string operationName);
}
public class SqlOperations : IDatabaseOperations
{
private readonly IDbConnectionFactory _connectionFactory;
private readonly TelemetryClient _telemetryClient;
public SqlOperations(IDbConnectionFactory connectionFactory, TelemetryClient telemetryClient)
{
_connectionFactory = connectionFactory;
_telemetryClient = telemetryClient;
}
public DatabaseScope CreateScope(string operationName)
{
var connection = _connectionFactory.Create();
var operation = _telemetryClient.StartOperation<DependencyTelemetry>(operationName);
operation.Telemetry.Type = "SQL";
operation.Telemetry.Target = "PostgreSQL";
return new DatabaseScope(connection, operation);
}
public async Task<T> ExecuteAsync<T>(Func<IDbConnection, Task<T>> operation, string operationName)
{
using var scope = CreateScope(operationName);
try
{
var result = await operation(scope.Connection);
scope.Success();
return result;
}
catch (Exception ex)
{
scope.Error(ex);
throw;
}
}
public async Task ExecuteAsync(Func<IDbConnection, Task> operation, string operationName)
{
using var scope = CreateScope(operationName);
try
{
await operation(scope.Connection);
scope.Success();
}
catch (Exception ex)
{
scope.Error(ex);
throw;
}
}
}
}