Enhancing telemetry in Seq and fixes namespaces

This commit is contained in:
Janus C. H. Knudsen 2025-02-20 00:23:13 +01:00
parent 5568007237
commit 9f4996bc8f
65 changed files with 1122 additions and 1139 deletions

View file

@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="App.ts" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
<ProjectReference Include="..\Database\Database.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Views\Components\" />
</ItemGroup>
</Project>

View file

@ -1,6 +1,6 @@
using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Razor;
namespace Application.Common namespace PlanTempus.Application.Common
{ {
public class ComponentsViewLocationExpander : IViewLocationExpander public class ComponentsViewLocationExpander : IViewLocationExpander
{ {

View file

@ -1,7 +1,7 @@
using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Application.Components.Navigation namespace PlanTempus.Application.Components.Navigation
{ {
public class NavigationViewComponent : ViewComponent public class NavigationViewComponent : ViewComponent
{ {

View file

@ -1,5 +1,5 @@
@page @page
@model IndexModel @model PlanTempus.Application.Pages.IndexModel
@{ @{
ViewData["Title"] = "Home page"; ViewData["Title"] = "Home page";
} }

View file

@ -3,7 +3,7 @@ using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages;
namespace PlanTempus.Pages namespace PlanTempus.Application.Pages
{ {
public class IndexModel : PageModel public class IndexModel : PageModel
{ {

View file

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="App.ts" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\PlanTempus.Core.csproj" />
<ProjectReference Include="..\Database\PlanTempus.Database.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Views\Components\" />
</ItemGroup>
</Project>

View file

@ -1,5 +1,5 @@
using Application;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using PlanTempus.Application;
var host = Host.CreateDefaultBuilder(args) var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) .UseServiceProviderFactory(new AutofacServiceProviderFactory())

View file

@ -1,8 +1,9 @@
using Autofac; using Autofac;
using Core.Configurations.JsonConfigProvider; using PlanTempus.Core.Configurations.JsonConfigProvider;
using Core.Configurations; using PlanTempus.Core.Configurations;
using PlanTempus.Core.ModuleRegistry;
namespace Application namespace PlanTempus.Application
{ {
public class Startup public class Startup
{ {
@ -39,9 +40,9 @@ namespace Application
ConnectionString = ConfigurationRoot.GetConnectionString("ptdb") ConnectionString = ConfigurationRoot.GetConnectionString("ptdb")
}); });
builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule builder.RegisterModule(new TelemetryModule
{ {
TelemetryConfig = ConfigurationRoot.GetSection(nameof(Core.ModuleRegistry.TelemetryConfig)).ToObject<Core.ModuleRegistry.TelemetryConfig>() TelemetryConfig = ConfigurationRoot.GetSection(nameof(TelemetryConfig)).ToObject<TelemetryConfig>()
}); });

View file

@ -4,11 +4,7 @@
"ptdb": "Host=localhost;Port=5433;Database=ptdb01;User Id=sathumper;Password=3911;" "ptdb": "Host=localhost;Port=5433;Database=ptdb01;User Id=sathumper;Password=3911;"
}, },
"TelemetryConfig": { "TelemetryConfig": {
"ConnectionString": "InstrumentationKey=07d2a2b9-5e8e-4924-836e-264f8438f6c5;IngestionEndpoint=https://northeurope-2.in.applicationinsights.azure.com/;LiveEndpoint=https://northeurope.livediagnostics.monitor.azure.com/;ApplicationId=56748c39-2fa3-4880-a1e2-24068e791548" "ConnectionString": "InstrumentationKey=07d2a2b9-5e8e-4924-836e-264f8438f6c5;IngestionEndpoint=https://northeurope-2.in.applicationinsights.azure.com/;LiveEndpoint=https://northeurope.livediagnostics.monitor.azure.com/;ApplicationId=56748c39-2fa3-4880-a1e2-24068e791548",
}, "UseSeqLoggingTelemetryChannel": true
"Feature": {
"Enabled": true,
"RolloutPercentage": 25,
"AllowedUserGroups": [ "beta" ]
} }
} }

View file

@ -4,7 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Core.Configurations.Common namespace PlanTempus.Core.Configurations.Common
{ {
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;

View file

@ -1,5 +1,5 @@
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Core.Configurations namespace PlanTempus.Core.Configurations
{ {
public interface IConfigurationBuilder public interface IConfigurationBuilder
{ {
@ -133,7 +133,7 @@ namespace Core.Configurations
public interface IConfigurationProvider public interface IConfigurationProvider
{ {
void Build(); void Build();
Newtonsoft.Json.Linq.JObject Configuration(); JObject Configuration();
} }
public class ConfigurationSection : IConfigurationSection public class ConfigurationSection : IConfigurationSection
@ -148,6 +148,6 @@ namespace Core.Configurations
{ {
string Path { get; } string Path { get; }
string Key { get; } string Key { get; }
Newtonsoft.Json.Linq.JToken Value { get; set; } JToken Value { get; set; }
} }
} }

View file

@ -1,4 +1,4 @@
namespace Core.Configurations namespace PlanTempus.Core.Configurations
{ {
/// <summary> /// <summary>
/// Marker interface for application configurations that should be automatically registered in the DI container. /// Marker interface for application configurations that should be automatically registered in the DI container.

View file

@ -1,4 +1,4 @@
namespace Core.Configurations namespace PlanTempus.Core.Configurations
{ {
public interface IConfigurationRoot : IConfiguration { } public interface IConfigurationRoot : IConfiguration { }

View file

@ -1,8 +1,9 @@
using Core.Exceptions; using PlanTempus.Core.Exceptions;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using PlanTempus.Core.Configurations;
namespace Core.Configurations.JsonConfigProvider namespace PlanTempus.Core.Configurations.JsonConfigProvider
{ {
public static class JsonConfigExtension public static class JsonConfigExtension
{ {

View file

@ -1,4 +1,4 @@
namespace Core.Configurations.SmartConfigProvider; namespace PlanTempus.Core.Configurations.SmartConfigProvider;
public class AppConfiguration public class AppConfiguration
{ {
public long Id { get; set; } public long Id { get; set; }

View file

@ -1,4 +1,4 @@
namespace Core.Configurations.SmartConfigProvider; namespace PlanTempus.Core.Configurations.SmartConfigProvider;
public interface IConfigurationRepository public interface IConfigurationRepository
{ {
string ConnectionString { get; set; } string ConnectionString { get; set; }

View file

@ -1,7 +1,7 @@
using System.Data; using System.Data;
using Insight.Database; using Insight.Database;
namespace Core.Configurations.SmartConfigProvider.Repositories; namespace PlanTempus.Core.Configurations.SmartConfigProvider.Repositories;
public class PostgresConfigurationRepository : IConfigurationRepository public class PostgresConfigurationRepository : IConfigurationRepository
{ {
private IDbConnection _connection; private IDbConnection _connection;

View file

@ -1,4 +1,6 @@
namespace Core.Configurations.SmartConfigProvider using PlanTempus.Core.Configurations;
namespace PlanTempus.Core.Configurations.SmartConfigProvider
{ {
/// <summary> /// <summary>
/// Extension methods for adding smart configuration providers to IConfigurationBuilder. /// Extension methods for adding smart configuration providers to IConfigurationBuilder.

View file

@ -1,4 +1,4 @@
namespace Core.Configurations.SmartConfigProvider namespace PlanTempus.Core.Configurations.SmartConfigProvider
{ {
/// <summary> /// <summary>
/// Configuration options for setting up smart configuration providers. /// Configuration options for setting up smart configuration providers.

View file

@ -1,9 +1,9 @@
using Core.Configurations.JsonConfigProvider;
using Core.Exceptions;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Exceptions;
namespace Core.Configurations.SmartConfigProvider namespace PlanTempus.Core.Configurations.SmartConfigProvider
{ {
/// <summary> /// <summary>
/// Configuration provider that loads configuration from a smart configuration source (e.g. database). /// Configuration provider that loads configuration from a smart configuration source (e.g. database).

View file

@ -4,7 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Core.Entities.Users namespace PlanTempus.Core.Entities.Users
{ {
public class User public class User
{ {

View file

@ -1,4 +1,4 @@
namespace Core.Entities.Users namespace PlanTempus.Core.Entities.Users
{ {
public static class PasswordHasher public static class PasswordHasher
{ {

View file

@ -1,9 +1,9 @@
namespace Core.Exceptions namespace PlanTempus.Core.Exceptions
{ {
internal class ConfigurationException : Exception internal class ConfigurationException : Exception
{ {
public ConfigurationException(string message) : base(message) public ConfigurationException(string message) : base(message)
{ {
} }
} }
} }

View file

@ -1,20 +1,20 @@
using Core.Telemetry; using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using PlanTempus.Core.Telemetry;
namespace Core.Logging namespace PlanTempus.Core.Logging
{ {
public class SeqBackgroundService : BackgroundService public class SeqBackgroundService : BackgroundService
{ {
private readonly IMessageChannel<ITelemetry> _messageChannel; private readonly IMessageChannel<ITelemetry> _messageChannel;
private readonly TelemetryClient _telemetryClient; private readonly TelemetryClient _telemetryClient;
private readonly SeqLogger _seqLogger; private readonly SeqLogger<SeqBackgroundService> _seqLogger;
public SeqBackgroundService(TelemetryClient telemetryClient, public SeqBackgroundService(TelemetryClient telemetryClient,
IMessageChannel<ITelemetry> messageChannel, IMessageChannel<ITelemetry> messageChannel,
SeqLogger seqlogger) SeqLogger<SeqBackgroundService> seqlogger)
{ {
_telemetryClient = telemetryClient; _telemetryClient = telemetryClient;
_messageChannel = messageChannel; _messageChannel = messageChannel;
@ -49,12 +49,12 @@ namespace Core.Logging
await _seqLogger.LogAsync(et); await _seqLogger.LogAsync(et);
break; break;
case EventTelemetry et: case EventTelemetry et:
await _seqLogger.LogAsync(et); await _seqLogger.LogAsync(et);
break; break;
default: default:
throw new NotSupportedException(telemetry.GetType().Name); throw new NotSupportedException(telemetry.GetType().Name);
} }
} }

View file

@ -1,7 +1,7 @@
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.DataContracts;
using System.Text; using System.Text;
namespace Core.Logging namespace PlanTempus.Core.Logging
{ {
public record SeqConfiguration(string IngestionEndpoint, string ApiKey, string Environment); public record SeqConfiguration(string IngestionEndpoint, string ApiKey, string Environment);
} }

View file

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

View file

@ -1,248 +1,239 @@
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.DataContracts;
using System.Text; using System.Text;
namespace Core.Logging namespace PlanTempus.Core.Logging
{ {
public class SeqLogger public class SeqLogger<T>
{ {
private readonly SeqHttpClient _httpClient; private readonly SeqHttpClient _httpClient;
private readonly string _environmentName; private readonly string _environmentName;
private readonly string _machineName; private readonly string _machineName;
private readonly SeqConfiguration _configuration; private readonly SeqConfiguration _configuration;
public SeqLogger(SeqHttpClient httpClient, string environmentName, SeqConfiguration configuration) public SeqLogger(SeqHttpClient httpClient, string environmentName, SeqConfiguration configuration)
{ {
_httpClient = httpClient; _httpClient = httpClient;
_environmentName = configuration.Environment; }
_machineName = Environment.MachineName;
}
public async Task LogAsync(TraceTelemetry trace, CancellationToken cancellationToken = default) public async Task LogAsync(TraceTelemetry trace, CancellationToken cancellationToken = default)
{ {
var seqEvent = new Dictionary<string, object> var seqEvent = new Dictionary<string, object>
{ {
{ "@t", trace.Timestamp.UtcDateTime.ToString("o") }, { "@t", trace.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", trace.Message }, { "@mt", trace.Message },
{ "@l", MapSeverityToLevel(trace.SeverityLevel) }, { "@l", MapSeverityToLevel(trace.SeverityLevel) },
{ "Environment", _environmentName }, { "Environment", _environmentName },
{ "MachineName", _machineName } { "MachineName", _machineName }
}; };
foreach (var prop in trace.Properties) foreach (var prop in trace.Properties)
{ seqEvent.Add($"prop_{prop.Key}", prop.Value);
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken); foreach (var prop in trace.Context.GlobalProperties)
} seqEvent.Add($"global_{prop.Key}", prop.Value);
public async Task LogAsync(EventTelemetry evt, CancellationToken cancellationToken = default) await SendToSeqAsync(seqEvent, cancellationToken);
{ }
var seqEvent = new Dictionary<string, object>
{
{ "@t", evt.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", evt.Name },
{ "@l", "Information" },
{ "Environment", _environmentName },
{ "MachineName", _machineName }
};
foreach (var prop in evt.Properties) public async Task LogAsync(EventTelemetry evt, CancellationToken cancellationToken = default)
{ {
seqEvent.Add(prop.Key, prop.Value); var seqEvent = new Dictionary<string, object>
} {
{ "@t", evt.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", evt.Name },
{ "@l", "Information" },
{ "Environment", _environmentName },
{ "MachineName", _machineName }
};
foreach (var metric in evt.Metrics) foreach (var prop in evt.Properties)
{ seqEvent.Add($"prop_{prop.Key}", prop.Value);
seqEvent.Add($"metric_{metric.Key}", metric.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken); foreach (var prop in evt.Context.GlobalProperties)
} seqEvent.Add($"global_{prop.Key}", prop.Value);
public async Task LogAsync(ExceptionTelemetry ex, CancellationToken cancellationToken = default) foreach (var metric in evt.Metrics)
{ seqEvent.Add($"metric_{metric.Key}", metric.Value);
var seqEvent = new Dictionary<string, object>
{
{ "@t", ex.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", ex.Exception.Message },
{ "@l", "Error" },
{ "@x", FormatExceptionForSeq(ex.Exception) },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "ExceptionType", ex.Exception.GetType().Name },
};
foreach (var prop in ex.Properties) await SendToSeqAsync(seqEvent, cancellationToken);
{ }
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken); public async Task LogAsync(ExceptionTelemetry ex, CancellationToken cancellationToken = default)
} {
var seqEvent = new Dictionary<string, object>
{
{ "@t", ex.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", ex.Exception.Message },
{ "@l", "Error" },
{ "@x", FormatExceptionForSeq(ex.Exception) },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "ExceptionType", ex.Exception.GetType().Name },
};
public async Task LogAsync(DependencyTelemetry dep, CancellationToken cancellationToken = default) foreach (var prop in ex.Properties)
{ seqEvent.Add($"prop_{prop.Key}", prop.Value);
var seqEvent = new Dictionary<string, object>
{
{ "@t", dep.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", $"Dependency: {dep.Name}" },
{ "@l", dep.Success??true ? "Information" : "Error" },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "DependencyType", dep.Type },
{ "Target", dep.Target },
{ "Duration", dep.Duration.TotalMilliseconds }
};
foreach (var prop in dep.Properties) foreach (var prop in ex.Context.GlobalProperties)
{ seqEvent.Add($"global_{prop.Key}", prop.Value);
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken); await SendToSeqAsync(seqEvent, cancellationToken);
} }
public async Task LogAsync(RequestTelemetry req, CancellationToken cancellationToken = default) public async Task LogAsync(DependencyTelemetry dep, CancellationToken cancellationToken = default)
{ {
var seqEvent = new Dictionary<string, object> var seqEvent = new Dictionary<string, object>
{ {
{ "@t", req.Timestamp.UtcDateTime.ToString("o") }, { "@t", dep.Timestamp.UtcDateTime.ToString("o") },
{ "@mt",$"{req.Properties["httpMethod"]} {req.Name}" }, { "@mt", $"Dependency: {dep.Name}" },
{ "@l", req.Success??true ? "Information" : "Error" }, { "@l", dep.Success??true ? "Information" : "Error" },
{ "Environment", _environmentName }, { "Environment", _environmentName },
{ "MachineName", _machineName }, { "MachineName", _machineName },
{ "Url", req.Url }, { "DependencyType", dep.Type },
{ "ResponseCode", req.ResponseCode }, { "Target", dep.Target },
{ "Application", "sadasd" }, { "Duration", dep.Duration.TotalMilliseconds }
{ "RequestMethod", req.Properties["httpMethod"] }, };
{ "RequestId", req.Id },
{ "ItemTypeFlag", req.ItemTypeFlag.ToString() },
{ "@sp", "12"},
{ "@tr", "23344"},
{ "@sk","Server" },
{ "@st", req.Timestamp.UtcDateTime.Subtract(req.Duration).ToString("o") }
};
req.Properties.Remove("httpMethod");
//we should add a property with name { "Application", "<...>" } other the Seq Span is not looking ok foreach (var prop in dep.Properties)
foreach (var prop in req.Properties) seqEvent.Add($"prop_{prop.Key}", prop.Value);
{
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken); foreach (var prop in dep.Context.GlobalProperties)
} seqEvent.Add($"global_{prop.Key}", prop.Value);
public async Task LogAsync(Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> operationHolder, CancellationToken cancellationToken = default)
{
var req = operationHolder.Telemetry;
var seqEvent = new Dictionary<string, object> await SendToSeqAsync(seqEvent, cancellationToken);
{ }
{ "@t", req.Timestamp.UtcDateTime.ToString("o") }, public async Task LogAsync(RequestTelemetry req, CancellationToken cancellationToken = default)
{ "@mt",$"{req.Properties["httpMethod"]} {req.Name}" }, {
{ "@l", req.Success??true ? "Information" : "Error" }, throw new NotImplementedException();
{ "Environment", _environmentName }, }
{ "MachineName", _machineName }, public async Task LogAsync(Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> operationHolder, CancellationToken cancellationToken = default)
{ "Url", req.Url }, {
{ "ResponseCode", req.ResponseCode }, var req = operationHolder.Telemetry;
{ "Application", "sadasd" },
{ "RequestMethod", req.Properties["httpMethod"] },
{ "RequestId", req.Id },
{ "ItemTypeFlag", req.ItemTypeFlag.ToString() },
{ "@sp", "12"},
{ "@tr", "23344"},
{ "@sk","Server" },
{ "@st", req.Timestamp.UtcDateTime.Subtract(req.Duration).ToString("o") }
};
req.Properties.Remove("httpMethod");
//we should add a property with name { "Application", "<...>" } other the Seq Span is not looking ok //https://docs.datalust.co/v2025.1/docs/posting-raw-events
foreach (var prop in req.Properties) var seqEvent = new Dictionary<string, object>
{ {
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken); { "@t", req.Timestamp.UtcDateTime.ToString("o") },
} { "@mt",req.Name },
private async Task SendToSeqAsync(Dictionary<string, object> seqEvent, CancellationToken cancellationToken) { "@l", req.Success??true ? "Information" : "Error" },
{ { "@sp", req.Id }, //Span id Unique identifier of a span Yes, if the event is a span
var content = new StringContent( { "@tr", req.Context.Operation.Id}, //Trace id An identifier that groups all spans and logs that are in the same trace Yes, if the event is a span
Newtonsoft.Json.JsonConvert.SerializeObject(seqEvent), { "@sk","Server" }, //Span kind Describes the relationship of the span to others in the trace: Client, Server, Internal, Producer, or Consumer
Encoding.UTF8, { "@st", req.Timestamp.UtcDateTime.Subtract(req.Duration).ToString("o") }, //Start The start ISO 8601 timestamp of this span Yes, if the event is a span
"application/vnd.serilog.clef"); { "SourceContext", typeof(T).FullName },
{ "Url", req.Url },
{ "RequestId", req.Id },
{ "ItemTypeFlag", req.ItemTypeFlag.ToString() }
};
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/ingest/clef")
{
Content = content
};
var result = await _httpClient.SendAsync(requestMessage, cancellationToken); if (!string.IsNullOrEmpty(req.ResponseCode))
{
if (int.TryParse(req.ResponseCode, out int statusCode))
{
if (Enum.IsDefined(typeof(System.Net.HttpStatusCode), statusCode))
seqEvent["StatusCode"] = $"{statusCode} {(System.Net.HttpStatusCode)statusCode}";
else
seqEvent["StatusCode"] = $"{statusCode} Unknown";
}
}
if (!string.IsNullOrEmpty(req.Context.Operation.ParentId))
seqEvent["@ps"] = req.Context.Operation.ParentId;
result.EnsureSuccessStatusCode(); if (req.Properties.TryGetValue("httpMethod", out string method))
} {
seqEvent["RequestMethod"] = method;
seqEvent["@mt"] = $"{req.Properties["httpMethod"]} {req.Name}";
req.Properties.Remove("httpMethod");
}
private string MapSeverityToLevel(SeverityLevel? severity) foreach (var prop in req.Properties)
{ seqEvent.Add($"prop_{prop.Key}", prop.Value);
return severity switch
{
SeverityLevel.Verbose => "Verbose",
SeverityLevel.Information => "Information",
SeverityLevel.Warning => "Warning",
SeverityLevel.Error => "Error",
SeverityLevel.Critical => "Fatal",
_ => "Information"
};
}
private string FormatExceptionForSeq(Exception ex)
{
var sb = new StringBuilder();
var exceptionCount = 0;
void FormatSingleException(Exception currentEx, int depth) foreach (var prop in req.Context.GlobalProperties)
{ seqEvent.Add($"global_{prop.Key}", prop.Value);
if (depth > 0) sb.AppendLine("\n--- Inner Exception ---");
sb.AppendLine($"Exception Type: {currentEx.GetType().FullName}"); await SendToSeqAsync(seqEvent, cancellationToken);
sb.AppendLine($"Message: {currentEx.Message}"); }
sb.AppendLine($"Source: {currentEx.Source}"); private async Task SendToSeqAsync(Dictionary<string, object> seqEvent, CancellationToken cancellationToken)
sb.AppendLine($"HResult: 0x{currentEx.HResult:X8}"); {
sb.AppendLine("Stack Trace:"); var content = new StringContent(
sb.AppendLine(currentEx.StackTrace?.Trim()); Newtonsoft.Json.JsonConvert.SerializeObject(seqEvent),
Encoding.UTF8,
"application/vnd.serilog.clef");
if (currentEx.Data.Count > 0) var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/ingest/clef")
{ {
sb.AppendLine("Additional Data:"); Content = content
foreach (var key in currentEx.Data.Keys) };
{
sb.AppendLine($" {key}: {currentEx.Data[key]}");
}
}
}
void RecurseExceptions(Exception currentEx, int depth = 0) var result = await _httpClient.SendAsync(requestMessage, cancellationToken);
{
if (currentEx is AggregateException aggEx)
{
foreach (var inner in aggEx.InnerExceptions)
{
RecurseExceptions(inner, depth);
depth++;
}
}
else if (currentEx.InnerException != null)
{
RecurseExceptions(currentEx.InnerException, depth + 1);
}
FormatSingleException(currentEx, depth); result.EnsureSuccessStatusCode();
exceptionCount++; }
}
RecurseExceptions(ex); private string MapSeverityToLevel(SeverityLevel? severity)
sb.Insert(0, $"EXCEPTION CHAIN ({exceptionCount} exceptions):\n"); {
return sb.ToString(); return severity switch
} {
} SeverityLevel.Verbose => "Verbose",
SeverityLevel.Information => "Information",
SeverityLevel.Warning => "Warning",
SeverityLevel.Error => "Error",
SeverityLevel.Critical => "Fatal",
_ => "Information"
};
}
private string FormatExceptionForSeq(Exception ex)
{
var sb = new StringBuilder();
var exceptionCount = 0;
void FormatSingleException(Exception currentEx, int depth)
{
if (depth > 0) sb.AppendLine("\n--- Inner Exception ---");
sb.AppendLine($"Exception Type: {currentEx.GetType().FullName}");
sb.AppendLine($"Message: {currentEx.Message}");
sb.AppendLine($"Source: {currentEx.Source}");
sb.AppendLine($"HResult: 0x{currentEx.HResult:X8}");
sb.AppendLine("Stack Trace:");
sb.AppendLine(currentEx.StackTrace?.Trim());
if (currentEx.Data.Count > 0)
{
sb.AppendLine("Additional Data:");
foreach (var key in currentEx.Data.Keys)
{
sb.AppendLine($" {key}: {currentEx.Data[key]}");
}
}
}
void RecurseExceptions(Exception currentEx, int depth = 0)
{
if (currentEx is AggregateException aggEx)
{
foreach (var inner in aggEx.InnerExceptions)
{
RecurseExceptions(inner, depth);
depth++;
}
}
else if (currentEx.InnerException != null)
{
RecurseExceptions(currentEx.InnerException, depth + 1);
}
FormatSingleException(currentEx, depth);
exceptionCount++;
}
RecurseExceptions(ex);
sb.Insert(0, $"EXCEPTION CHAIN ({exceptionCount} exceptions):\n");
return sb.ToString();
}
}
} }

View file

@ -1,8 +1,8 @@
using Autofac; using Autofac;
using Core.Logging; using PlanTempus.Core.Logging;
using Core.Telemetry; using PlanTempus.Core.Telemetry;
namespace Core.ModuleRegistry namespace PlanTempus.Core.ModuleRegistry
{ {
public class SeqLoggingModule : Module public class SeqLoggingModule : Module
{ {

View file

@ -1,71 +1,48 @@
using Autofac; using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
namespace Core.ModuleRegistry namespace PlanTempus.Core.ModuleRegistry
{ {
public class TelemetryModule : Module public class TelemetryModule : Module
{ {
public TelemetryConfig TelemetryConfig { get; set; } public TelemetryConfig TelemetryConfig { get; set; }
protected override void Load(ContainerBuilder builder)
{
if (TelemetryConfig == null)
throw new Exceptions.ConfigurationException("TelemetryConfig is missing");
//builder.Register(c => protected override void Load(ContainerBuilder builder)
//{ {
// var channel = new Telemetry.DualTelemetryChannel("C:\\logs\\telemetry.log"); if (TelemetryConfig == null)
// channel.DeveloperMode = true; throw new Exceptions.ConfigurationException("TelemetryConfig is missing");
// var config = new TelemetryConfiguration
// {
// ConnectionString = TelemetryConfig.ConnectionString,
// TelemetryChannel = channel
// };
// return new TelemetryClient(config);
//}).InstancePerLifetimeScope();
var telemetryChannel = new InMemoryChannel
{
DeveloperMode = true
};
//var configuration = new TelemetryConfiguration
//{
// ConnectionString = TelemetryConfig.ConnectionString,
// TelemetryChannel = telemetryChannel
//};
//telemetryChannel.Initialize(configuration);
var tmc = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault(); var configuration = TelemetryConfiguration.CreateDefault();
tmc.ConnectionString = TelemetryConfig.ConnectionString; configuration.ConnectionString = TelemetryConfig.ConnectionString;
tmc.TelemetryChannel.DeveloperMode = true; configuration.TelemetryChannel.DeveloperMode = true;
var channel = new Telemetry.SeqLoggingTelemetryChannel("C:\\logs\\telemetry.log");
tmc.TelemetryChannel = channel; if (TelemetryConfig.UseSeqLoggingTelemetryChannel)
configuration.TelemetryChannel = new Telemetry.SeqLoggingTelemetryChannel(); ;
////var r = new Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryProcessorChainBuilder(tmc); var r = new Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryProcessorChainBuilder(configuration);
////r.Use(next => new Domain.EventTelemetryEnrichers.EnrichWithMetaTelemetry(next)); r.Use(next => new Telemetry.Enrichers.EnrichWithMetaTelemetry(next));
////r.Build(); r.Build();
//builder.RegisterInstance(configuration); //builder.RegisterInstance(configuration);
builder.Register(c => new TelemetryClient(tmc)).InstancePerLifetimeScope();
//builder.RegisterType<Microsoft.ApplicationInsights.TelemetryClient>() //builder.RegisterType<Microsoft.ApplicationInsights.TelemetryClient>()
// .InstancePerLifetimeScope(); // .InstancePerLifetimeScope();
//builder.RegisterType<Microsoft.ApplicationInsights.TelemetryClient>() var client = new Microsoft.ApplicationInsights.TelemetryClient(configuration);
// .As<Telemetry.ITelemetryClient>() client.Context.GlobalProperties["Application"] = GetType().Namespace.Split('.')[0];
// .InstancePerLifetimeScope(); client.Context.GlobalProperties["MachineName"] = Environment.MachineName;
} client.Context.GlobalProperties["Version"] = Environment.Version.ToString();
} client.Context.GlobalProperties["ProcessorCount"] = Environment.ProcessorCount.ToString();
public class TelemetryConfig builder.Register(c => client).InstancePerLifetimeScope();
{ }
public string ConnectionString { get; set; } }
}
public class TelemetryConfig
{
public string ConnectionString { get; set; }
public bool UseSeqLoggingTelemetryChannel { get; set; }
}
} }

View file

@ -1,4 +1,4 @@
namespace Core.MultiKeyEncryption namespace PlanTempus.Core.MultiKeyEncryption
{ {
internal class MasterKey internal class MasterKey
{ {

View file

@ -5,7 +5,7 @@ using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Core.MultiKeyEncryption namespace PlanTempus.Core.MultiKeyEncryption
{ {
public class SecureConnectionString public class SecureConnectionString
{ {

View file

@ -1,4 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk"> 
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>

View file

@ -0,0 +1,22 @@
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
namespace PlanTempus.Core.Telemetry.Enrichers
{
public class EnrichWithMetaTelemetry : ITelemetryProcessor
{
private readonly ITelemetryProcessor _next;
public EnrichWithMetaTelemetry(ITelemetryProcessor next)
{
_next = next;
}
public void Process(ITelemetry item)
{
//nothing going on here yet :)
_next.Process(item);
}
}
}

View file

@ -1,5 +1,5 @@
using System.Threading.Channels; using System.Threading.Channels;
namespace Core.Telemetry namespace PlanTempus.Core.Telemetry
{ {
public interface IMessageChannel<T> : IDisposable public interface IMessageChannel<T> : IDisposable
{ {

View file

@ -1,23 +1,23 @@
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Channel;
using System.Threading.Channels; using System.Threading.Channels;
namespace Core.Telemetry namespace PlanTempus.Core.Telemetry
{ {
public class MessageChannel : IMessageChannel<ITelemetry> public class MessageChannel : IMessageChannel<ITelemetry>
{ {
private readonly Channel<ITelemetry> _channel; private readonly Channel<ITelemetry> _channel;
public MessageChannel() public MessageChannel()
{ {
_channel = Channel.CreateUnbounded<ITelemetry>(); _channel = Channel.CreateUnbounded<ITelemetry>();
} }
public ChannelWriter<ITelemetry> Writer => _channel.Writer; public ChannelWriter<ITelemetry> Writer => _channel.Writer;
public ChannelReader<ITelemetry> Reader => _channel.Reader; public ChannelReader<ITelemetry> Reader => _channel.Reader;
public void Dispose() public void Dispose()
{ {
_channel.Writer.Complete(); _channel.Writer.Complete();
} }
} }
} }

View file

@ -1,11 +1,10 @@
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Channel;
using System.Net.Http.Headers; using System.Net.Http.Headers;
namespace Core.Telemetry namespace PlanTempus.Core.Telemetry
{ {
public class SeqLoggingTelemetryChannel : InMemoryChannel, ITelemetryChannel public class SeqLoggingTelemetryChannel : InMemoryChannel, ITelemetryChannel
{ {
private readonly string _filePath;
public ITelemetryChannel _defaultChannel; public ITelemetryChannel _defaultChannel;
static HttpClient _client = new HttpClient(); static HttpClient _client = new HttpClient();
@ -22,9 +21,8 @@ namespace Core.Telemetry
} }
public SeqLoggingTelemetryChannel(string filePath) public SeqLoggingTelemetryChannel()
{ {
_filePath = filePath;
} }
public new void Send(ITelemetry telemetry) public new void Send(ITelemetry telemetry)
{ {

View file

@ -1,6 +1,6 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Database.Common namespace PlanTempus.Database.Common
{ {
internal class Validations internal class Validations
{ {

View file

@ -1,53 +1,54 @@
using Insight.Database; using Insight.Database;
using PlanTempus.Database.Core;
using System.Data; using System.Data;
namespace Database.ConfigurationManagementSystem; namespace PlanTempus.Database.ConfigurationManagementSystem;
public class SetupConfiguration : Core.IDbConfigure<SetupConfiguration.Command> public class SetupConfiguration : IDbConfigure<SetupConfiguration.Command>
{ {
public class Command public class Command
{ {
} }
private readonly IDbConnection _db; private readonly IDbConnection _db;
public SetupConfiguration(IDbConnection connection) public SetupConfiguration(IDbConnection connection)
{ {
_db = connection; _db = connection;
} }
public void With(Command notInUse) public void With(Command notInUse)
{ {
using (var transaction = _db.OpenWithTransaction()) using (var transaction = _db.OpenWithTransaction())
{ {
try try
{ {
CreateConfigurationTable(); CreateConfigurationTable();
CreateHistoryTable(); CreateHistoryTable();
CreateConfigurationIndexes(); CreateConfigurationIndexes();
CreateModifiedAtTrigger(); CreateModifiedAtTrigger();
CreateNotifyTrigger(); CreateNotifyTrigger();
CreateHistoryTrigger(); CreateHistoryTrigger();
transaction.Commit(); transaction.Commit();
} }
catch (Exception ex) catch (Exception ex)
{ {
transaction.Rollback(); transaction.Rollback();
throw new InvalidOperationException("Failed to SetupConfiguration in Database", ex); throw new InvalidOperationException("Failed to SetupConfiguration in Database", ex);
} }
} }
} }
private void ExecuteSql(string sql) private void ExecuteSql(string sql)
{ {
_db.ExecuteSql(sql); _db.ExecuteSql(sql);
} }
void CreateConfigurationTable() void CreateConfigurationTable()
{ {
const string sql = @" const string sql = @"
CREATE TABLE IF NOT EXISTS app_configuration ( CREATE TABLE IF NOT EXISTS app_configuration (
id bigserial NOT NULL, id bigserial NOT NULL,
""key"" varchar(255) NOT NULL, ""key"" varchar(255) NOT NULL,
@ -61,12 +62,12 @@ public class SetupConfiguration : Core.IDbConfigure<SetupConfiguration.Command>
etag uuid DEFAULT gen_random_uuid() NULL, etag uuid DEFAULT gen_random_uuid() NULL,
CONSTRAINT app_configuration_pkey PRIMARY KEY (id) CONSTRAINT app_configuration_pkey PRIMARY KEY (id)
);"; );";
ExecuteSql(sql); ExecuteSql(sql);
} }
void CreateHistoryTable() void CreateHistoryTable()
{ {
const string sql = @" const string sql = @"
CREATE TABLE IF NOT EXISTS app_configuration_history ( CREATE TABLE IF NOT EXISTS app_configuration_history (
history_id bigserial NOT NULL, history_id bigserial NOT NULL,
action_type char(1) NOT NULL, action_type char(1) NOT NULL,
@ -84,20 +85,20 @@ public class SetupConfiguration : Core.IDbConfigure<SetupConfiguration.Command>
etag uuid NULL, etag uuid NULL,
CONSTRAINT app_configuration_history_pkey PRIMARY KEY (history_id) CONSTRAINT app_configuration_history_pkey PRIMARY KEY (history_id)
);"; );";
ExecuteSql(sql); ExecuteSql(sql);
} }
void CreateConfigurationIndexes() void CreateConfigurationIndexes()
{ {
const string sql = @" const string sql = @"
CREATE INDEX IF NOT EXISTS idx_app_configuration_key ON app_configuration(""key""); CREATE INDEX IF NOT EXISTS idx_app_configuration_key ON app_configuration(""key"");
CREATE INDEX IF NOT EXISTS idx_app_configuration_validity ON app_configuration(valid_from, expires_at);"; CREATE INDEX IF NOT EXISTS idx_app_configuration_validity ON app_configuration(valid_from, expires_at);";
ExecuteSql(sql); ExecuteSql(sql);
} }
void CreateModifiedAtTrigger() void CreateModifiedAtTrigger()
{ {
const string sql = @" const string sql = @"
CREATE OR REPLACE FUNCTION update_app_configuration_modified_at() CREATE OR REPLACE FUNCTION update_app_configuration_modified_at()
RETURNS TRIGGER AS $$ RETURNS TRIGGER AS $$
BEGIN BEGIN
@ -110,12 +111,12 @@ public class SetupConfiguration : Core.IDbConfigure<SetupConfiguration.Command>
BEFORE UPDATE ON app_configuration BEFORE UPDATE ON app_configuration
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION update_app_configuration_modified_at();"; EXECUTE FUNCTION update_app_configuration_modified_at();";
ExecuteSql(sql); ExecuteSql(sql);
} }
void CreateNotifyTrigger() void CreateNotifyTrigger()
{ {
const string sql = @" const string sql = @"
CREATE OR REPLACE FUNCTION notify_app_configuration_change() CREATE OR REPLACE FUNCTION notify_app_configuration_change()
RETURNS TRIGGER AS $$ RETURNS TRIGGER AS $$
BEGIN BEGIN
@ -128,12 +129,12 @@ public class SetupConfiguration : Core.IDbConfigure<SetupConfiguration.Command>
AFTER INSERT OR UPDATE ON app_configuration AFTER INSERT OR UPDATE ON app_configuration
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION notify_app_configuration_change();"; EXECUTE FUNCTION notify_app_configuration_change();";
ExecuteSql(sql); ExecuteSql(sql);
} }
void CreateHistoryTrigger() void CreateHistoryTrigger()
{ {
const string sql = @" const string sql = @"
CREATE OR REPLACE FUNCTION log_app_configuration_changes() CREATE OR REPLACE FUNCTION log_app_configuration_changes()
RETURNS TRIGGER AS $$ RETURNS TRIGGER AS $$
BEGIN BEGIN
@ -172,8 +173,8 @@ public class SetupConfiguration : Core.IDbConfigure<SetupConfiguration.Command>
CREATE OR REPLACE TRIGGER trg_app_configuration_history CREATE OR REPLACE TRIGGER trg_app_configuration_history
AFTER INSERT OR UPDATE OR DELETE ON app_configuration AFTER INSERT OR UPDATE OR DELETE ON app_configuration
FOR EACH ROW EXECUTE FUNCTION log_app_configuration_changes();"; FOR EACH ROW EXECUTE FUNCTION log_app_configuration_changes();";
ExecuteSql(sql); ExecuteSql(sql);
} }
} }

View file

@ -1,113 +1,114 @@
using System.Data; using System.Data;
using Database.Common;
using Insight.Database; using Insight.Database;
using PlanTempus.Database.Common;
using PlanTempus.Database.Core;
namespace Database.Core.DCL namespace PlanTempus.Database.Core.DCL
{ {
/// <summary> /// <summary>
/// Only a superadmin or similar can create Application Users /// Only a superadmin or similar can create Application Users
/// </summary> /// </summary>
public class SetupApplicationUser : IDbConfigure<SetupApplicationUser.Command> public class SetupApplicationUser : IDbConfigure<SetupApplicationUser.Command>
{ {
public class Command public class Command
{ {
public required string Schema { get; init; } public required string Schema { get; init; }
public required string User { get; init; } public required string User { get; init; }
public required string Password { get; init; } public required string Password { get; init; }
} }
IDbConnection _db; IDbConnection _db;
Command _command; Command _command;
public SetupApplicationUser(IDbConnection db) public SetupApplicationUser(IDbConnection db)
{ {
_db = db; _db = db;
} }
public void With(Command command) public void With(Command command)
{ {
_command = command; _command = command;
if (!Validations.IsValidSchemaName(_command.Schema)) if (!Validations.IsValidSchemaName(_command.Schema))
throw new ArgumentException("Invalid schema name", _command.Schema); throw new ArgumentException("Invalid schema name", _command.Schema);
using (var transaction = _db.OpenWithTransaction()) using (var transaction = _db.OpenWithTransaction())
{ {
try try
{ {
CreateSchema(); CreateSchema();
CreateRole(); CreateRole();
GrantSchemaRights(); GrantSchemaRights();
transaction.Commit(); transaction.Commit();
} }
catch (Exception ex) catch (Exception ex)
{ {
transaction.Rollback(); transaction.Rollback();
throw new InvalidOperationException("Failed to SetupApplicationUser in Database", ex); throw new InvalidOperationException("Failed to SetupApplicationUser in Database", ex);
} }
} }
} }
private void ExecuteSql(string sql) private void ExecuteSql(string sql)
{ {
_db.ExecuteSql(sql); _db.ExecuteSql(sql);
} }
private void CreateSchema() private void CreateSchema()
{ {
var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}"; var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}";
ExecuteSql(sql); ExecuteSql(sql);
} }
private void CreateRole() private void CreateRole()
{ {
var sql = $@" var sql = $@"
DO $$ DO $$
BEGIN BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{_command.User}') THEN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{_command.User}') THEN
CREATE ROLE {_command.User} WITH CREATEDB CREATEROLE LOGIN PASSWORD '{_command.Password}'; CREATE ROLE {_command.User} WITH CREATEDB CREATEROLE LOGIN PASSWORD '{_command.Password}';
END IF; END IF;
END $$;"; END $$;";
ExecuteSql(sql); ExecuteSql(sql);
var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';"; var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';";
ExecuteSql(sql1); ExecuteSql(sql1);
} }
private void GrantSchemaRights() private void GrantSchemaRights()
{ {
// Grant USAGE og alle CREATE rettigheder på schema niveau // Grant USAGE og alle CREATE rettigheder på schema niveau
var sql = $@" var sql = $@"
GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User}; GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User};
GRANT ALL ON SCHEMA {_command.Schema} TO {_command.User};"; GRANT ALL ON SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql); ExecuteSql(sql);
// Grant rettigheder på eksisterende og fremtidige tabeller // Grant rettigheder på eksisterende og fremtidige tabeller
var sql1 = $"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA {_command.Schema} TO {_command.User};"; var sql1 = $"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql1); ExecuteSql(sql1);
var sql2 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT ALL PRIVILEGES ON TABLES TO {_command.User};"; var sql2 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT ALL PRIVILEGES ON TABLES TO {_command.User};";
ExecuteSql(sql2); ExecuteSql(sql2);
// Grant sequence rettigheder // Grant sequence rettigheder
var sql3 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};"; var sql3 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql3); ExecuteSql(sql3);
// Grant execute på functions // Grant execute på functions
var sql4 = $"GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA {_command.Schema} TO {_command.User};"; var sql4 = $"GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql4); ExecuteSql(sql4);
// Grant for fremtidige functions // Grant for fremtidige functions
var sql5 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT EXECUTE ON FUNCTIONS TO {_command.User};"; var sql5 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT EXECUTE ON FUNCTIONS TO {_command.User};";
ExecuteSql(sql5); ExecuteSql(sql5);
// Grant for fremtidige sequences // Grant for fremtidige sequences
var sql6 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT USAGE ON SEQUENCES TO {_command.User};"; var sql6 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT USAGE ON SEQUENCES TO {_command.User};";
ExecuteSql(sql6); ExecuteSql(sql6);
} }
} }
} }

View file

@ -1,8 +1,9 @@
using System.Data; using System.Data;
using Database.Common;
using Insight.Database; using Insight.Database;
using PlanTempus.Database.Common;
using PlanTempus.Database.Core;
namespace Database.Core.DCL namespace PlanTempus.Database.Core.DCL
{ {
/// <summary> /// <summary>

View file

@ -1,93 +1,94 @@
using System.Data; using System.Data;
using Database.Common;
using Insight.Database; using Insight.Database;
using PlanTempus.Database.Common;
using PlanTempus.Database.Core;
namespace Database.Core.DCL namespace PlanTempus.Database.Core.DCL
{ {
public class SetupOrganization : IDbConfigure<SetupOrganization.Command> public class SetupOrganization : IDbConfigure<SetupOrganization.Command>
{ {
public class Command public class Command
{ {
public required string Schema { get; init; } public required string Schema { get; init; }
public required string User { get; init; } public required string User { get; init; }
public required string Password { get; init; } public required string Password { get; init; }
} }
IDbConnection _db; IDbConnection _db;
Command _command; Command _command;
public SetupOrganization(IDbConnection db) public SetupOrganization(IDbConnection db)
{ {
_db = db; _db = db;
} }
public void With(Command command) public void With(Command command)
{ {
_command = command; _command = command;
if (!Validations.IsValidSchemaName(_command.Schema)) if (!Validations.IsValidSchemaName(_command.Schema))
throw new ArgumentException("Invalid schema name", _command.Schema); throw new ArgumentException("Invalid schema name", _command.Schema);
using (var transaction = _db.BeginTransaction()) using (var transaction = _db.BeginTransaction())
{ {
try try
{ {
CreateSchema(); CreateSchema();
CreateRole(); CreateRole();
GrantSchemaRights(); GrantSchemaRights();
transaction.Commit(); transaction.Commit();
} }
catch (Exception ex) catch (Exception ex)
{ {
transaction.Rollback(); transaction.Rollback();
throw new InvalidOperationException("Failed to SetupOrganization in Database", ex); throw new InvalidOperationException("Failed to SetupOrganization in Database", ex);
} }
} }
} }
private void ExecuteSql(string sql) private void ExecuteSql(string sql)
{ {
_db.ExecuteSql(sql); _db.ExecuteSql(sql);
} }
private void CreateSchema() private void CreateSchema()
{ {
var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}"; var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}";
ExecuteSql(sql); ExecuteSql(sql);
} }
private void CreateRole() private void CreateRole()
{ {
var sql = $"CREATE ROLE {_command.User} LOGIN PASSWORD '{_command.Password}';"; var sql = $"CREATE ROLE {_command.User} LOGIN PASSWORD '{_command.Password}';";
ExecuteSql(sql); ExecuteSql(sql);
var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';"; var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';";
ExecuteSql(sql1); ExecuteSql(sql1);
} }
private void GrantSchemaRights() private void GrantSchemaRights()
{ {
var sql = $"GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User};"; var sql = $"GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql); ExecuteSql(sql);
var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} " + var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} " +
$"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_command.User};"; $"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_command.User};";
ExecuteSql(sql1); ExecuteSql(sql1);
var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};"; var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql2); ExecuteSql(sql2);
var sql3 = $"GRANT CREATE TABLE ON SCHEMA {_command.Schema} TO {_command.User};"; var sql3 = $"GRANT CREATE TABLE ON SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql3); ExecuteSql(sql3);
} }
public void RevokeCreateTable() public void RevokeCreateTable()
{ {
var sql = $"REVOKE CREATE TABLE ON SCHEMA {_command.Schema} FROM {_command.User};"; var sql = $"REVOKE CREATE TABLE ON SCHEMA {_command.Schema} FROM {_command.User};";
ExecuteSql(sql); ExecuteSql(sql);
} }
} }
} }

View file

@ -1,7 +1,8 @@
using Insight.Database; using Insight.Database;
using PlanTempus.Database.Core;
using System.Data; using System.Data;
namespace Database.Core.DDL namespace PlanTempus.Database.Core.DDL
{ {
/// <summary> /// <summary>
/// This is by purpose not async await /// This is by purpose not async await

View file

@ -1,7 +1,7 @@
namespace Database.Core namespace PlanTempus.Database.Core
{ {
public interface IDbConfigure<T> public interface IDbConfigure<T>
{ {
void With(T command); void With(T command);
} }
} }

View file

@ -1,8 +1,8 @@
using Core.Entities.Users; using Insight.Database;
using Insight.Database; using PlanTempus.Core.Entities.Users;
using System.Data; using System.Data;
namespace Database.Core namespace PlanTempus.Database.Core
{ {
public class UserService public class UserService
{ {

View file

@ -1,22 +1,22 @@
using Autofac; using Autofac;
using Npgsql; using Npgsql;
using System.Data; using System.Data;
namespace Database.ModuleRegistry namespace PlanTempus.Database.ModuleRegistry
{ {
public class DbPostgreSqlModule : Module public class DbPostgreSqlModule : Module
{ {
public required string ConnectionString { get; set; } public required string ConnectionString { get; set; }
protected override void Load(ContainerBuilder builder) protected override void Load(ContainerBuilder builder)
{ {
Insight.Database.Providers.PostgreSQL.PostgreSQLInsightDbProvider.RegisterProvider(); Insight.Database.Providers.PostgreSQL.PostgreSQLInsightDbProvider.RegisterProvider();
builder.Register(c => builder.Register(c =>
{ {
IDbConnection connection = new NpgsqlConnection(ConnectionString); IDbConnection connection = new NpgsqlConnection(ConnectionString);
return connection; return connection;
}) })
.InstancePerLifetimeScope(); .InstancePerLifetimeScope();
} }
} }
} }

View file

@ -1,26 +1,26 @@
using Insight.Database; using Insight.Database;
using System.Data; using System.Data;
namespace Database.NavigationSystem namespace PlanTempus.Database.NavigationSystem
{ {
internal class Setup internal class Setup
{ {
private readonly IDbConnection _db; private readonly IDbConnection _db;
public Setup(IDbConnection db) public Setup(IDbConnection db)
{ {
_db = db; _db = db;
} }
public void CreateSystem() public void CreateSystem()
{ {
//await CreateNavigationLinkTemplatesTable(schema); //await CreateNavigationLinkTemplatesTable(schema);
//await CreateNavigationLinkTemplateTranslationsTable(schema); //await CreateNavigationLinkTemplateTranslationsTable(schema);
} }
private async Task CreateNavigationLinkTemplatesTable() private async Task CreateNavigationLinkTemplatesTable()
{ {
var sql = $@" var sql = $@"
CREATE TABLE IF NOT EXISTS navigation_link_templates ( CREATE TABLE IF NOT EXISTS navigation_link_templates (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
parent_id INTEGER NULL, parent_id INTEGER NULL,
@ -31,12 +31,12 @@ namespace Database.NavigationSystem
FOREIGN KEY (permission_id) REFERENCES permissions(id), FOREIGN KEY (permission_id) REFERENCES permissions(id),
FOREIGN KEY (parent_id) REFERENCES navigation_link_templates(id) FOREIGN KEY (parent_id) REFERENCES navigation_link_templates(id)
)"; )";
await _db.ExecuteAsync(sql); await _db.ExecuteAsync(sql);
} }
private async Task CreateNavigationLinkTemplateTranslationsTable(string schema) private async Task CreateNavigationLinkTemplateTranslationsTable(string schema)
{ {
var sql = $@" var sql = $@"
CREATE TABLE IF NOT EXISTS navigation_link_template_translations ( CREATE TABLE IF NOT EXISTS navigation_link_template_translations (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
template_id INTEGER NOT NULL, template_id INTEGER NOT NULL,
@ -44,7 +44,7 @@ namespace Database.NavigationSystem
display_name VARCHAR(100) NOT NULL, display_name VARCHAR(100) NOT NULL,
FOREIGN KEY (template_id) REFERENCES navigation_link_templates(id) FOREIGN KEY (template_id) REFERENCES navigation_link_templates(id)
)"; )";
await _db.ExecuteAsync(sql); await _db.ExecuteAsync(sql);
} }
} }
} }

View file

@ -6,7 +6,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" /> <ProjectReference Include="..\Core\PlanTempus.Core.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -1,92 +1,91 @@
using System.Data; using System.Data;
using Database.Common;
using Insight.Database; using Insight.Database;
namespace Database.RolesPermissionSystem namespace PlanTempus.Database.RolesPermissionSystem
{ {
/// <summary> /// <summary>
/// This is by purpose not async await /// This is by purpose not async await
/// It is intended that this is created with the correct Application User, which is why the schema name is omitted. /// It is intended that this is created with the correct Application User, which is why the schema name is omitted.
/// </summary> /// </summary>
public class Setup public class Setup
{ {
IDbConnection _db; IDbConnection _db;
public Setup(IDbConnection db) public Setup(IDbConnection db)
{ {
_db = db; _db = db;
} }
/// <summary> /// <summary>
/// Creates the system tables in the specified schema within a transaction. /// Creates the system tables in the specified schema within a transaction.
/// </summary> /// </summary>
/// <param name="schema">The schema name where the tables will be created.</param> /// <param name="schema">The schema name where the tables will be created.</param>
public void CreateSystem() public void CreateSystem()
{ {
//if (!Validations.IsValidSchemaName(_schema)) //if (!Validations.IsValidSchemaName(_schema))
// throw new ArgumentException("Invalid schema name", _schema); // throw new ArgumentException("Invalid schema name", _schema);
using (var transaction = _db.BeginTransaction()) using (var transaction = _db.BeginTransaction())
{ {
try try
{ {
CreateRolesTable(); CreateRolesTable();
CreatePermissionsTable(); CreatePermissionsTable();
CreatePermissionTypesTable(); CreatePermissionTypesTable();
CreateRolePermissionsTable(); CreateRolePermissionsTable();
transaction.Commit(); transaction.Commit();
} }
catch (Exception ex) catch (Exception ex)
{ {
transaction.Rollback(); transaction.Rollback();
throw new InvalidOperationException("Failed to create system tables.", ex); throw new InvalidOperationException("Failed to create system tables.", ex);
} }
} }
} }
private void ExecuteSql(string sql) private void ExecuteSql(string sql)
{ {
_db.ExecuteSql(sql); _db.ExecuteSql(sql);
} }
private void CreatePermissionTypesTable() private void CreatePermissionTypesTable()
{ {
var sql = $@" var sql = $@"
CREATE TABLE IF NOT EXISTS permission_types ( CREATE TABLE IF NOT EXISTS permission_types (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE name VARCHAR(100) NOT NULL UNIQUE
)"; )";
ExecuteSql(sql); ExecuteSql(sql);
} }
private void CreatePermissionsTable() private void CreatePermissionsTable()
{ {
var sql = $@" var sql = $@"
CREATE TABLE IF NOT EXISTS permissions ( CREATE TABLE IF NOT EXISTS permissions (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE, name VARCHAR(100) NOT NULL UNIQUE,
type_id INTEGER NOT NULL, type_id INTEGER NOT NULL,
FOREIGN KEY (type_id) REFERENCES permission_types(id) FOREIGN KEY (type_id) REFERENCES permission_types(id)
)"; )";
ExecuteSql(sql); ExecuteSql(sql);
} }
private void CreateRolesTable() private void CreateRolesTable()
{ {
var sql = $@" var sql = $@"
CREATE TABLE IF NOT EXISTS roles ( CREATE TABLE IF NOT EXISTS roles (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE name VARCHAR(100) NOT NULL UNIQUE
)"; )";
ExecuteSql(sql); ExecuteSql(sql);
} }
private void CreateRolePermissionsTable() private void CreateRolePermissionsTable()
{ {
var sql = $@" var sql = $@"
CREATE TABLE IF NOT EXISTS role_permissions ( CREATE TABLE IF NOT EXISTS role_permissions (
role_id INTEGER NOT NULL, role_id INTEGER NOT NULL,
permission_id INTEGER NOT NULL, permission_id INTEGER NOT NULL,
@ -94,7 +93,7 @@ namespace Database.RolesPermissionSystem
FOREIGN KEY (role_id) REFERENCES roles(id), FOREIGN KEY (role_id) REFERENCES roles(id),
FOREIGN KEY (permission_id) REFERENCES permissions(id) FOREIGN KEY (permission_id) REFERENCES permissions(id)
)"; )";
ExecuteSql(sql); ExecuteSql(sql);
} }
} }
} }

View file

@ -1,7 +1,7 @@
using Insight.Database; using Insight.Database;
using System.Data; using System.Data;
namespace Database.Tenants namespace PlanTempus.Database.Tenants
{ {
internal class InitializeOrganizationData internal class InitializeOrganizationData
{ {

View file

@ -2,15 +2,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.10.35013.160 VisualStudioVersion = 17.10.35013.160
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "Core\Core.csproj", "{7B554252-1CE4-44BD-B108-B0BDCCB24742}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlanTempus.Core", "Core\PlanTempus.Core.csproj", "{7B554252-1CE4-44BD-B108-B0BDCCB24742}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "Tests\Tests.csproj", "{85614050-CFB0-4E39-81D3-7D99946449D9}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlanTempus.Tests", "Tests\PlanTempus.Tests.csproj", "{85614050-CFB0-4E39-81D3-7D99946449D9}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Application", "Application\Application.csproj", "{111CE8AE-E637-4376-A5A3-88D33E77EA88}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlanTempus.Application", "Application\PlanTempus.Application.csproj", "{111CE8AE-E637-4376-A5A3-88D33E77EA88}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Database", "Database\Database.csproj", "{D5096A7F-E6D4-4C87-874E-2D9A6BEAD57F}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlanTempus.Database", "Database\PlanTempus.Database.csproj", "{D5096A7F-E6D4-4C87-874E-2D9A6BEAD57F}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SetupInfrastructure", "SetupInfrastructure\SetupInfrastructure.csproj", "{48300227-BCBB-45A3-8359-9064DA85B1F9}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlanTempus.SetupInfrastructure", "SetupInfrastructure\PlanTempus.SetupInfrastructure.csproj", "{48300227-BCBB-45A3-8359-9064DA85B1F9}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

View file

@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Database\Database.csproj" /> <ProjectReference Include="..\Database\PlanTempus.Database.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -1,88 +1,91 @@
using Autofac; using Autofac;
using Insight.Database; using Insight.Database;
using PlanTempus.Database.ConfigurationManagementSystem;
using PlanTempus.Database.Core.DCL;
using PlanTempus.Database.Core.DDL;
using System.Data; using System.Data;
using System.Diagnostics; using System.Diagnostics;
namespace SetupInfrastructure namespace PlanTempus.SetupInfrastructure
{ {
/// <summary> /// <summary>
/// SETUP APPLICATION USER NAMED sathumper /// SETUP APPLICATION USER NAMED sathumper
/// ///
/// This should be handled on the Postgresql db server with a superadmin or similar. /// This should be handled on the Postgresql db server with a superadmin or similar.
/// ///
/// Execute SQL CreateRole.txt /// Execute SQL CreateRole.txt
/// ///
/// After that is executed it is time for running this main program /// After that is executed it is time for running this main program
/// Remember to use the newly created sathumper /// Remember to use the newly created sathumper
/// "ConnectionStrings": { /// "ConnectionStrings": {
/// "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptdb01;User Id=<uid>;Password=<secret>;" /// "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptdb01;User Id=<uid>;Password=<secret>;"
/// </summary> /// </summary>
internal class Program internal class Program
{ {
static IContainer _container; static IContainer _container;
static ConsoleColor _backgroundColor = Console.BackgroundColor; static ConsoleColor _backgroundColor = Console.BackgroundColor;
static ConsoleColor _foregroundColor = Console.ForegroundColor; static ConsoleColor _foregroundColor = Console.ForegroundColor;
static async Task Main(string[] args) static async Task Main(string[] args)
{ {
Welcome(); Welcome();
string userPass; string userPass;
try try
{ {
do do
{ {
Console.WriteLine("Input username:password for a superadmin role"); Console.WriteLine("Input username:password for a superadmin role");
userPass = Console.ReadLine() ?? string.Empty; userPass = Console.ReadLine() ?? string.Empty;
} while (!userPass.Contains(":") || userPass.Split(":").Length != 2 || } while (!userPass.Contains(":") || userPass.Split(":").Length != 2 ||
string.IsNullOrEmpty(userPass.Split(":")[0]) || string.IsNullOrEmpty(userPass.Split(":")[0]) ||
string.IsNullOrEmpty(userPass.Split(":")[1])); string.IsNullOrEmpty(userPass.Split(":")[1]));
var ctp = new Startup.ConnectionStringTemplateParameters( var ctp = new Startup.ConnectionStringTemplateParameters(
user: userPass.Split(":")[0], user: userPass.Split(":")[0],
pwd: userPass.Split(":")[1] pwd: userPass.Split(":")[1]
); );
_container = new Startup().ConfigureContainer(ctp); _container = new Startup().ConfigureContainer(ctp);
if (IsSuperAdmin()) if (IsSuperAdmin())
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
var sw = new Stopwatch(); var sw = new Stopwatch();
Console.Write("Database.Core.DCL.SetupDbAdmin..."); Console.Write("Database.Core.DCL.SetupDbAdmin...");
sw.Start(); sw.Start();
var setupDbAdmin = _container.Resolve<Database.Core.DCL.SetupDbAdmin>(); var setupDbAdmin = _container.Resolve<SetupDbAdmin>();
setupDbAdmin.With(new Database.Core.DCL.SetupDbAdmin.Command { Password = "3911", Schema = "system", User = "heimdall" }); setupDbAdmin.With(new SetupDbAdmin.Command { Password = "3911", Schema = "system", User = "heimdall" });
Console.WriteLine($"DONE, took: {sw.ElapsedMilliseconds} ms"); Console.WriteLine($"DONE, took: {sw.ElapsedMilliseconds} ms");
Console.WriteLine("::"); Console.WriteLine("::");
Console.WriteLine("::"); Console.WriteLine("::");
Console.Write("Database.Core.DDL.SetupIdentitySystem..."); Console.Write("Database.Core.DDL.SetupIdentitySystem...");
sw.Restart(); sw.Restart();
//create new container with application user, we use that role from now. //create new container with application user, we use that role from now.
_container = new Startup().ConfigureContainer(new Startup.ConnectionStringTemplateParameters("heimdall", "3911")); _container = new Startup().ConfigureContainer(new Startup.ConnectionStringTemplateParameters("heimdall", "3911"));
var setupIdentitySystem = _container.Resolve<Database.Core.DDL.SetupIdentitySystem>(); var setupIdentitySystem = _container.Resolve<SetupIdentitySystem>();
setupIdentitySystem.With(new Database.Core.DDL.SetupIdentitySystem.Command { Schema = "system"}); setupIdentitySystem.With(new SetupIdentitySystem.Command { Schema = "system" });
Console.WriteLine($"DONE, took: {sw.ElapsedMilliseconds} ms"); Console.WriteLine($"DONE, took: {sw.ElapsedMilliseconds} ms");
Console.WriteLine("::"); Console.WriteLine("::");
Console.WriteLine("::"); Console.WriteLine("::");
Console.Write("Database.ConfigurationManagementSystem.SetupConfiguration..."); Console.Write("Database.ConfigurationManagementSystem.SetupConfiguration...");
sw.Restart(); sw.Restart();
var setupConfigurationSystem = _container.Resolve<Database.ConfigurationManagementSystem.SetupConfiguration>(); var setupConfigurationSystem = _container.Resolve<SetupConfiguration>();
setupConfigurationSystem.With(new Database.ConfigurationManagementSystem.SetupConfiguration.Command()); setupConfigurationSystem.With(new SetupConfiguration.Command());
Console.Write($"DONE, took: {sw.ElapsedMilliseconds} ms"); Console.Write($"DONE, took: {sw.ElapsedMilliseconds} ms");
Console.WriteLine("::"); Console.WriteLine("::");
Console.WriteLine("::"); Console.WriteLine("::");
Console.Write("Database.Core.DCL.SetupApplicationUser..."); Console.Write("Database.Core.DCL.SetupApplicationUser...");
sw.Start(); sw.Start();
var setupApplicationUser = _container.Resolve<Database.Core.DCL.SetupApplicationUser>(); var setupApplicationUser = _container.Resolve<SetupApplicationUser>();
setupApplicationUser.With(new Database.Core.DCL.SetupApplicationUser.Command { Password = "3911", Schema = "system", User = "sathumper" }); setupApplicationUser.With(new SetupApplicationUser.Command { Password = "3911", Schema = "system", User = "sathumper" });
Console.WriteLine($"DONE, took: {sw.ElapsedMilliseconds} ms"); Console.WriteLine($"DONE, took: {sw.ElapsedMilliseconds} ms");
@ -91,86 +94,86 @@ namespace SetupInfrastructure
// input configurations!!! TODO:Missing // input configurations!!! TODO:Missing
Console.ForegroundColor = _foregroundColor; Console.ForegroundColor = _foregroundColor;
} }
} }
catch (Exception e) catch (Exception e)
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e); Console.WriteLine(e);
} }
} }
static bool IsSuperAdmin() static bool IsSuperAdmin()
{ {
//test db access //test db access
Console.WriteLine("Testing db access..."); Console.WriteLine("Testing db access...");
string query = @"SELECT usename, usesuper FROM pg_user WHERE usename = CURRENT_USER;"; string query = @"SELECT usename, usesuper FROM pg_user WHERE usename = CURRENT_USER;";
var conn = _container.Resolve<IDbConnection>(); var conn = _container.Resolve<IDbConnection>();
var result = (dynamic)conn.QuerySql(query).Single(); var result = (dynamic)conn.QuerySql(query).Single();
string username = result.usename; string username = result.usename;
bool isSuperuser = (bool)result.usesuper; bool isSuperuser = (bool)result.usesuper;
if ((bool)result.usesuper) if ((bool)result.usesuper)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.BackgroundColor = ConsoleColor.Yellow; Console.BackgroundColor = ConsoleColor.Yellow;
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("TEST SUCCESSFULLY"); Console.WriteLine("TEST SUCCESSFULLY");
Console.WriteLine(); Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = _backgroundColor; Console.BackgroundColor = _backgroundColor;
Console.WriteLine("-------------------------------"); Console.WriteLine("-------------------------------");
Console.WriteLine(); Console.WriteLine();
Console.WriteLine($"Username: {username}"); Console.WriteLine($"Username: {username}");
Console.WriteLine($"Super admin: true"); Console.WriteLine($"Super admin: true");
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("-------------------------------"); Console.WriteLine("-------------------------------");
Console.WriteLine("Press any key to start database setup"); Console.WriteLine("Press any key to start database setup");
Console.Read(); Console.Read();
return true; return true;
} }
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.BackgroundColor = ConsoleColor.Red; Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("TEST WAS NOT SUCCESSFULLY"); Console.WriteLine("TEST WAS NOT SUCCESSFULLY");
Console.WriteLine(); Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = _backgroundColor; Console.BackgroundColor = _backgroundColor;
Console.WriteLine("-------------------------------"); Console.WriteLine("-------------------------------");
Console.WriteLine(); Console.WriteLine();
Console.WriteLine($"Username: {username}"); Console.WriteLine($"Username: {username}");
Console.WriteLine($"Super admin: false"); Console.WriteLine($"Super admin: false");
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("-------------------------------"); Console.WriteLine("-------------------------------");
Console.WriteLine("User is required to be super admin"); Console.WriteLine("User is required to be super admin");
Console.Read(); Console.Read();
return false; return false;
} }
static void Welcome() static void Welcome()
{ {
Console.ForegroundColor = ConsoleColor.Blue; Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(@"__________.__ ___________ Console.WriteLine(@"__________.__ ___________
\______ \ | _____ ___\__ ___/___ _____ ______ __ __ ______ \______ \ | _____ ___\__ ___/___ _____ ______ __ __ ______
| ___/ | \__ \ / \| |_/ __ \ / \\____ \| | \/ ___/ | ___/ | \__ \ / \| |_/ __ \ / \\____ \| | \/ ___/
| | | |__/ __ \| | \ |\ ___/| Y Y \ |_> > | /\___ \ | | | |__/ __ \| | \ |\ ___/| Y Y \ |_> > | /\___ \
@ -182,9 +185,9 @@ namespace SetupInfrastructure
/ \ ___/| | | | / |_> > / \ ___/| | | | / |_> >
/_______ /\___ >__| |____/| __/ /_______ /\___ >__| |____/| __/
\/ \/ |__|"); \/ \/ |__|");
Console.WriteLine(); Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
} }
} }
} }

View file

@ -1,45 +1,46 @@
using Autofac; using Autofac;
using Core.Configurations; using PlanTempus.Core.Configurations;
using Core.Configurations.JsonConfigProvider; using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.ModuleRegistry;
using PlanTempus.Database.Core;
namespace PlanTempus.SetupInfrastructure
namespace SetupInfrastructure
{ {
public class Startup public class Startup
{ {
public virtual IConfigurationRoot Configuration() public virtual IConfigurationRoot Configuration()
{ {
var configuration = new ConfigurationBuilder() var configuration = new ConfigurationBuilder()
.AddJsonFile("appconfiguration.json") .AddJsonFile("appconfiguration.json")
.Build(); .Build();
return configuration; return configuration;
} }
public IContainer ConfigureContainer(ConnectionStringTemplateParameters ctp) public IContainer ConfigureContainer(ConnectionStringTemplateParameters ctp)
{ {
var builder = new ContainerBuilder(); var builder = new ContainerBuilder();
var configuration = Configuration(); var configuration = Configuration();
builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
{ {
ConnectionString = configuration.GetConnectionString("DefaultConnection").Replace("{usr}", ctp.user).Replace("{pwd}", ctp.pwd) ConnectionString = configuration.GetConnectionString("DefaultConnection").Replace("{usr}", ctp.user).Replace("{pwd}", ctp.pwd)
}); });
builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule builder.RegisterModule(new TelemetryModule
{ {
TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<Core.ModuleRegistry.TelemetryConfig>() TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<TelemetryConfig>()
}); });
builder.RegisterAssemblyTypes(typeof(Database.Core.IDbConfigure<>).Assembly) builder.RegisterAssemblyTypes(typeof(IDbConfigure<>).Assembly)
.AsClosedTypesOf(typeof(Database.Core.IDbConfigure<>)) .AsClosedTypesOf(typeof(IDbConfigure<>))
.AsSelf(); .AsSelf();
return builder.Build(); return builder.Build();
} }
public record ConnectionStringTemplateParameters(string user, string pwd); public record ConnectionStringTemplateParameters(string user, string pwd);
} }
} }

View file

@ -1,141 +1,142 @@
using Core.Configurations;
using FluentAssertions; using FluentAssertions;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Core.Configurations.JsonConfigProvider; using PlanTempus.Tests;
using Core.Configurations.SmartConfigProvider; using PlanTempus.Core.Configurations;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Configurations.SmartConfigProvider;
namespace Tests.ConfigurationTests namespace PlanTempus.Tests.ConfigurationTests
{ {
[TestClass] [TestClass]
public class JsonConfigurationProviderTests : TestFixture public class JsonConfigurationProviderTests : TestFixture
{ {
const string _testFolder = "ConfigurationTests/"; const string _testFolder = "ConfigurationTests/";
public JsonConfigurationProviderTests() : base(_testFolder) { } public JsonConfigurationProviderTests() : base(_testFolder) { }
[TestMethod] [TestMethod]
public void GetSection_ShouldReturnCorrectFeatureSection() public void GetSection_ShouldReturnCorrectFeatureSection()
{ {
// Arrange // Arrange
var expectedJObject = JObject.Parse(@"{ var expectedJObject = JObject.Parse(@"{
'Enabled': true, 'Enabled': true,
'RolloutPercentage': 25, 'RolloutPercentage': 25,
'AllowedUserGroups': ['beta'] 'AllowedUserGroups': ['beta']
}") as JToken; }") as JToken;
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.Build();
// Act
var section = builder.GetSection("Feature");
// Assert
section.Should().NotBeNull();
section.Value.Should().BeEquivalentTo(expectedJObject);
}
[TestMethod]
public void Get_ShouldReturnCorrectFeatureObject()
{
// Arrange
var expectedFeature = new Feature
{
Enabled = true,
RolloutPercentage = 25,
AllowedUserGroups = new() { "beta" }
};
var builder = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json") .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actualFeature = builder.GetSection("Feature").ToObject<Feature>(); var section = builder.GetSection("Feature");
// Assert
section.Should().NotBeNull();
section.Value.Should().BeEquivalentTo(expectedJObject);
}
[TestMethod]
public void Get_ShouldReturnCorrectFeatureObject()
{
// Arrange
var expectedFeature = new Feature
{
Enabled = true,
RolloutPercentage = 25,
AllowedUserGroups = new() { "beta" }
};
var builder = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.Build();
// Act
var actualFeature = builder.GetSection("Feature").ToObject<Feature>();
#pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete
var actualFeatureObsoleted = builder.GetSection("Feature").Get<Feature>(); var actualFeatureObsoleted = builder.GetSection("Feature").Get<Feature>();
#pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CS0618 // Type or member is obsolete
// Assert // Assert
actualFeature.Should().BeEquivalentTo(expectedFeature); actualFeature.Should().BeEquivalentTo(expectedFeature);
actualFeatureObsoleted.Should().BeEquivalentTo(expectedFeature); actualFeatureObsoleted.Should().BeEquivalentTo(expectedFeature);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectValueAsString() public void Get_ShouldReturnCorrectValueAsString()
{ {
// Arrange // Arrange
var expectedFeature = "123"; var expectedFeature = "123";
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json") .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actualFeature = builder.GetSection("AnotherSetting").Get<string>("Thresholds:High"); var actualFeature = builder.GetSection("AnotherSetting").Get<string>("Thresholds:High");
// Assert // Assert
actualFeature.Should().BeEquivalentTo(expectedFeature); actualFeature.Should().BeEquivalentTo(expectedFeature);
} }
/// <summary> /// <summary>
/// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder /// Testing a stupid indexer for compability with Microsoft ConfigurationBuilder
/// </summary> /// </summary>
[TestMethod] [TestMethod]
public void Indexer_ShouldReturnValueAsString() public void Indexer_ShouldReturnValueAsString()
{ {
// Arrange // Arrange
var expected = "SHA256"; var expected = "SHA256";
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json") .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actual = builder["Authentication"]; var actual = builder["Authentication"];
// Assert // Assert
actual.Should().BeEquivalentTo(expected); actual.Should().BeEquivalentTo(expected);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectValueAsInt() public void Get_ShouldReturnCorrectValueAsInt()
{ {
// Arrange // Arrange
var expectedFeature = 22; var expectedFeature = 22;
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json") .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.Build(); .Build();
// Act // Act
var actualFeature = builder.GetSection("AnotherSetting:Temperature").Get<int>("Indoor:Max:Limit"); var actualFeature = builder.GetSection("AnotherSetting:Temperature").Get<int>("Indoor:Max:Limit");
// Assert // Assert
actualFeature.Should().Be(expectedFeature); actualFeature.Should().Be(expectedFeature);
} }
[TestMethod] [TestMethod]
public void Get_ShouldReturnCorrectValueAsBool() public void Get_ShouldReturnCorrectValueAsBool()
{ {
// Arrange // Arrange
var expectedFeature = true; var expectedFeature = true;
var configRoot = new ConfigurationBuilder() var configRoot = new ConfigurationBuilder()
.AddJsonFile($"{_testFolder}appconfiguration.dev.json") .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
.AddSmartConfig() .AddSmartConfig()
.Build(); .Build();
// Act // Act
var actualFeature = configRoot.Get<bool>("Database:UseSSL"); var actualFeature = configRoot.Get<bool>("Database:UseSSL");
// Assert // Assert
actualFeature.Should().Be(expectedFeature); actualFeature.Should().Be(expectedFeature);
} }
} }
public class Feature public class Feature
{ {
public bool Enabled { get; set; } public bool Enabled { get; set; }
public int RolloutPercentage { get; set; } public int RolloutPercentage { get; set; }
public List<string> AllowedUserGroups { get; set; } public List<string> AllowedUserGroups { get; set; }
} }
} }

View file

@ -1,7 +1,8 @@
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Core.Configurations.Common; using PlanTempus.Core.Configurations.Common;
using PlanTempus.Tests;
namespace Tests.ConfigurationTests; namespace PlanTempus.Tests.ConfigurationTests;
[TestClass] [TestClass]
public class ConfigurationTests : TestFixture public class ConfigurationTests : TestFixture

View file

@ -1,13 +1,14 @@
using Core.Configurations; using FluentAssertions;
using FluentAssertions;
using Core.Configurations.JsonConfigProvider;
using Autofac; using Autofac;
using System.Data; using System.Data;
using Insight.Database; using Insight.Database;
using Npgsql; using Npgsql;
using Core.Configurations.SmartConfigProvider; using PlanTempus.Tests;
using PlanTempus.Core.Configurations;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Configurations.SmartConfigProvider;
namespace Tests.ConfigurationTests namespace PlanTempus.Tests.ConfigurationTests
{ {
[TestClass] [TestClass]
public class SmartConfigProviderTests : TestFixture public class SmartConfigProviderTests : TestFixture

View file

@ -4,7 +4,8 @@
"DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptmain;User Id=sathumper;Password=3911;" "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptmain;User Id=sathumper;Password=3911;"
}, },
"ApplicationInsights": { "ApplicationInsights": {
"ConnectionString": "InstrumentationKey=6d2e76ee-5343-4691-a5e3-81add43cb584;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/" "ConnectionString": "InstrumentationKey=6d2e76ee-5343-4691-a5e3-81add43cb584;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/",
"UseSeqLoggingTelemetryChannel": true
}, },
"Authentication": "SHA256", "Authentication": "SHA256",
"Feature": { "Feature": {

View file

@ -1,11 +1,11 @@
using Autofac; using Autofac;
using Core.Telemetry;
using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.DataContracts;
using Core.Logging; using PlanTempus.Core.Logging;
using PlanTempus.Core.Telemetry;
namespace Tests.Logging namespace PlanTempus.Tests.Logging
{ {
[TestClass] [TestClass]
public class SeqBackgroundServiceTest : TestFixture public class SeqBackgroundServiceTest : TestFixture
@ -23,9 +23,7 @@ namespace Tests.Logging
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
var httpClient = new SeqHttpClient(config); var httpClient = new SeqHttpClient(config);
var logger = new SeqLogger(httpClient, Environment.MachineName, config); var logger = new SeqLogger<SeqBackgroundService>(httpClient, Environment.MachineName, config);
_service = new SeqBackgroundService(telemetryClient, _messageChannel, logger); _service = new SeqBackgroundService(telemetryClient, _messageChannel, logger);
_cts = new CancellationTokenSource(); _cts = new CancellationTokenSource();
@ -40,15 +38,15 @@ namespace Tests.Logging
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
{ {
var eventTelemetry = new EventTelemetry var eventTelemetry = new EventTelemetry
{ {
Name = "Test Event", Name = "Test Event",
Timestamp = DateTimeOffset.UtcNow Timestamp = DateTimeOffset.UtcNow
}; };
eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString()); eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString());
eventTelemetry.Metrics.Add("TestMetric", 42.0); eventTelemetry.Metrics.Add("TestMetric", 42.0);
await _messageChannel.Writer.WriteAsync(eventTelemetry); await _messageChannel.Writer.WriteAsync(eventTelemetry);
} }
// wait for processing // wait for processing

View file

@ -1,146 +1,144 @@
using Autofac; using Autofac;
using Core.Logging;
using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
namespace Tests.Logging namespace PlanTempus.Tests.Logging
{ {
[TestClass] [TestClass]
public class SeqLoggerTests : TestFixture public class SeqLoggerTests : TestFixture
{ {
private SeqLogger _logger; private SeqLogger<SeqLoggerTests> _logger;
private SeqHttpClient _httpClient; private SeqHttpClient _httpClient;
private readonly string _testId; private readonly string _testId;
public SeqLoggerTests() public SeqLoggerTests()
{ {
_testId = Guid.NewGuid().ToString(); _testId = Guid.NewGuid().ToString();
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
_httpClient = new SeqHttpClient(config); _httpClient = new SeqHttpClient(config);
_logger = new SeqLogger(_httpClient, Environment.MachineName, config); _logger = new SeqLogger<SeqLoggerTests>(_httpClient, Environment.MachineName, config);
} }
[TestMethod] [TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithErrorLevel() public async Task LogTraceTelemetry_SendsCorrectDataWithErrorLevel()
{ {
// Arrange // Arrange
var traceTelemetry = new TraceTelemetry var traceTelemetry = new TraceTelemetry
{ {
Message = "Test trace error message", Message = "Test trace error message",
SeverityLevel = SeverityLevel.Error, SeverityLevel = SeverityLevel.Error,
Timestamp = DateTimeOffset.UtcNow Timestamp = DateTimeOffset.UtcNow
}; };
traceTelemetry.Properties.Add("TestId", _testId); traceTelemetry.Properties.Add("TestId", _testId);
// Act // Act
await _logger.LogAsync(traceTelemetry); await _logger.LogAsync(traceTelemetry);
} }
[TestMethod] [TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel() public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel()
{ {
// Arrange // Arrange
var traceTelemetry = new TraceTelemetry var traceTelemetry = new TraceTelemetry
{ {
Message = "Test trace warning message", Message = "Test trace warning message",
SeverityLevel = SeverityLevel.Warning, SeverityLevel = SeverityLevel.Warning,
Timestamp = DateTimeOffset.UtcNow Timestamp = DateTimeOffset.UtcNow
}; };
traceTelemetry.Properties.Add("TestId", _testId); traceTelemetry.Properties.Add("TestId", _testId);
// Act // Act
await _logger.LogAsync(traceTelemetry); await _logger.LogAsync(traceTelemetry);
} }
[TestMethod] [TestMethod]
public async Task LogEventTelemetry_SendsCorrectData() public async Task LogEventTelemetry_SendsCorrectData()
{ {
// Arrange // Arrange
var eventTelemetry = new EventTelemetry var eventTelemetry = new EventTelemetry
{ {
Name = "Test Event", Name = "Test Event",
Timestamp = DateTimeOffset.UtcNow Timestamp = DateTimeOffset.UtcNow
}; };
eventTelemetry.Properties.Add("TestId", _testId); eventTelemetry.Properties.Add("TestId", _testId);
eventTelemetry.Metrics.Add("TestMetric", 42.0); eventTelemetry.Metrics.Add("TestMetric", 42.0);
// Act // Act
await _logger.LogAsync(eventTelemetry); await _logger.LogAsync(eventTelemetry);
} }
[TestMethod] [TestMethod]
public async Task LogExceptionTelemetry_SendsCorrectData() public async Task LogExceptionTelemetry_SendsCorrectData()
{ {
try try
{ {
int t = 0; int t = 0;
var result = 10 / t; var result = 10 / t;
} }
catch (Exception e) catch (Exception e)
{ {
// Arrange // Arrange
var exceptionTelemetry = new ExceptionTelemetry(e) var exceptionTelemetry = new ExceptionTelemetry(e)
{ {
Timestamp = DateTimeOffset.UtcNow Timestamp = DateTimeOffset.UtcNow
}; };
exceptionTelemetry.Properties.Add("TestId", _testId); exceptionTelemetry.Properties.Add("TestId", _testId);
// Act // Act
await _logger.LogAsync(exceptionTelemetry); await _logger.LogAsync(exceptionTelemetry);
} }
} }
[TestMethod] [TestMethod]
public async Task LogDependencyTelemetry_SendsCorrectData() public async Task LogDependencyTelemetry_SendsCorrectData()
{ {
// Arrange // Arrange
var dependencyTelemetry = new DependencyTelemetry var dependencyTelemetry = new DependencyTelemetry
{ {
Name = "SQL Query", Name = "SQL Query",
Type = "SQL", Type = "SQL",
Target = "TestDB", Target = "TestDB",
Success = true, Success = true,
Duration = TimeSpan.FromMilliseconds(100), Duration = TimeSpan.FromMilliseconds(100),
Timestamp = DateTimeOffset.UtcNow Timestamp = DateTimeOffset.UtcNow
}; };
dependencyTelemetry.Properties.Add("TestId", _testId); dependencyTelemetry.Properties.Add("TestId", _testId);
// Act // Act
await _logger.LogAsync(dependencyTelemetry); await _logger.LogAsync(dependencyTelemetry);
} }
[TestMethod] [TestMethod]
public async Task LogRequestTelemetry_SendsCorrectData() public async Task LogRequestTelemetryInOperationHolderWithParentChild_SendsCorrectData()
{ {
var telemetryClient = Container.Resolve<TelemetryClient>(); var telemetryClient = Container.Resolve<TelemetryClient>();
var operationId = "op123"; using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> parent = telemetryClient.StartOperation<RequestTelemetry>("Parent First"))
{
using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> operation = telemetryClient.StartOperation<RequestTelemetry>("GET /api/parent")) parent.Telemetry.Duration = TimeSpan.FromMilliseconds(250);
{ parent.Telemetry.Url = new Uri("http://parent.test.com/api/test");
using (var child = telemetryClient.StartOperation<RequestTelemetry>("api/test")) using (var child = telemetryClient.StartOperation<RequestTelemetry>("Child 1"))
// Arrange {
{ child.Telemetry.Success = true;
child.Telemetry.ResponseCode = "200";
child.Telemetry.Duration = TimeSpan.FromMilliseconds(50);
child.Telemetry.Url = new Uri("http://child.test.com/api/test");
child.Telemetry.Timestamp = DateTimeOffset.UtcNow;
//child.Telemetry.Name = "/api/test"; child.Telemetry.Properties.Add("httpMethod", HttpMethod.Get.ToString());
child.Telemetry.Success = true; child.Telemetry.Properties.Add("TestId", _testId);
child.Telemetry.ResponseCode = "200";
child.Telemetry.Duration = TimeSpan.FromMilliseconds(50);
child.Telemetry.Url = new Uri("http://test.com/api/test");
child.Telemetry.Timestamp = DateTimeOffset.UtcNow;
child.Telemetry.Properties.Add("httpMethod", HttpMethod.Get.ToString()); await _logger.LogAsync(child);
child.Telemetry.Properties.Add("TestId", _testId); };
await _logger.LogAsync(child); await _logger.LogAsync(parent);
}; }
}
} }
// Act
}
}
} }

View file

@ -1,14 +1,8 @@
using Autofac;
using System.Data;
using Insight.Database;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Extensions.Logging;
using Core.Telemetry;
using Core.Entities.Users;
using System.Diagnostics; using System.Diagnostics;
using Sodium; using Sodium;
using PlanTempus.Core.Entities.Users;
namespace Tests namespace PlanTempus.Tests
{ {
[TestClass] [TestClass]
public class PasswordHasherTests : TestFixture public class PasswordHasherTests : TestFixture

View file

@ -18,8 +18,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Application\Application.csproj" /> <ProjectReference Include="..\Application\PlanTempus.Application.csproj" />
<ProjectReference Include="..\Database\Database.csproj" /> <ProjectReference Include="..\Database\PlanTempus.Database.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -1,11 +1,8 @@
using Autofac; using Autofac;
using System.Data; using System.Data;
using Insight.Database; using Insight.Database;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Extensions.Logging;
using Core.Telemetry;
namespace Tests namespace PlanTempus.Tests
{ {
[TestClass] [TestClass]
public class PostgresTests : TestFixture public class PostgresTests : TestFixture

View file

@ -1,11 +1,6 @@
using Autofac;
using System.Data;
using Insight.Database;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Extensions.Logging;
using Core.Telemetry;
namespace Tests
namespace PlanTempus.Tests
{ {
} }

View file

@ -1,12 +1,12 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using Autofac; using Autofac;
using Core.Configurations;
using Core.ModuleRegistry;
using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Core.Configurations.JsonConfigProvider; using PlanTempus.Core.Configurations;
namespace Tests using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.ModuleRegistry;
namespace PlanTempus.Tests
{ {
/// <summary> /// <summary>
/// Act as base class for tests. Avoids duplication of test setup code /// Act as base class for tests. Avoids duplication of test setup code
@ -72,9 +72,9 @@ namespace Tests
ConnectionString = configuration.GetConnectionString("DefaultConnection") ConnectionString = configuration.GetConnectionString("DefaultConnection")
}); });
builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule builder.RegisterModule(new TelemetryModule
{ {
TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<Core.ModuleRegistry.TelemetryConfig>() TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<TelemetryConfig>()
}); });

View file

@ -3,6 +3,7 @@
"DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptmain;User Id=sathumper;Password=3911;" "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptmain;User Id=sathumper;Password=3911;"
}, },
"ApplicationInsights": { "ApplicationInsights": {
"ConnectionString": "InstrumentationKey=6d2e76ee-5343-4691-a5e3-81add43cb584;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/" "ConnectionString": "InstrumentationKey=6d2e76ee-5343-4691-a5e3-81add43cb584;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/",
"UseSeqLoggingTelemetryChannel": true
} }
} }