Files
2024-05-09 17:22:10 +02:00

164 lines
6.0 KiB
C#

using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Localization;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using StackExchange.Redis;
using StackExchange.Redis.Extensions.Core.Configuration;
using StackExchange.Redis.Extensions.Newtonsoft;
using System.Globalization;
using System.Text.Json.Serialization;
using WebDoorCreator.Data;
using WebDoorCreator.Data.Services;
var builder = WebApplication.CreateBuilder(args);
// configuration setup
ConfigurationManager configuration = builder.Configuration;
// Redis
var connStringRedis = configuration.GetConnectionString("Redis");
if (string.IsNullOrEmpty(connStringRedis))
{
connStringRedis = "localhost:6379, DefaultDatabase=11, connectTimeout=5000, syncTimeout=5000, asyncTimeout=5000, abortConnect=false, ssl=false";
}
string redisSrvAddr = connStringRedis.Substring(0, connStringRedis.IndexOf(":"));
// avvio oggetto shared x redis...
var redisMultiplexer = ConnectionMultiplexer.Connect(connStringRedis);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// APP MAIN setup
string connectionString = configuration.GetConnectionString("WDC.DB") ?? "";
string dbServerAddr = "127.0.0.1";
if (string.IsNullOrEmpty(connectionString))
{
connectionString = "Server=SQL2016DEV;Database=WebDoorCreator; User ID=sa;Password=keyhammer16; integrated security=False; MultipleActiveResultSets=True; App=WebDoorCreator.SRV;";
}
else
{
if (connectionString.Contains("Server"))
{
bool trovato = false;
var dbTokens = connectionString.Split(";");
int numTok = dbTokens.Count();
int idx = 0;
while (!trovato && idx < numTok)
{
if (dbTokens[idx].StartsWith("Server="))
{
// rimuovo la chaive Server...
dbServerAddr = dbTokens[idx].Replace("Server=", "");
// se ci fosse un nome (tipo \\sqlexpress) rimuovo...
if (dbServerAddr.Contains("\\"))
{
int sIdx = dbServerAddr.IndexOf("\\");
dbServerAddr = dbServerAddr.Substring(0, sIdx);
}
trovato = true;
}
idx++;
}
}
}
// healthchecks
builder.Services.AddHealthChecks()
.AddSqlServer(connectionString, healthQuery: "SELECT 1;", name: "SqlServer", failureStatus: HealthStatus.Degraded, tags: new string[] { "DB", "MsSql" })
.AddAsyncCheck($"DB PING ({dbServerAddr})", () => WebDoorCreator.API.Health.Checks.PingCheck(dbServerAddr))
.AddAsyncCheck($"Redis PING ({redisSrvAddr})", () => WebDoorCreator.API.Health.Checks.PingCheck(redisSrvAddr))
// 512 MB max allocated memory
.AddProcessAllocatedMemoryHealthCheck(512, "Max Process memory (<512MB)", failureStatus: HealthStatus.Degraded)
.AddRedis(connStringRedis, "Redis", failureStatus: HealthStatus.Degraded)
.AddAsyncCheck($"Config Table", () => WebDoorCreator.API.Health.Checks.ConfigCount(configuration))
.AddAsyncCheck($"Orders Table", () => WebDoorCreator.API.Health.Checks.OrdersCount(configuration))
.AddAsyncCheck($"Doors Table", () => WebDoorCreator.API.Health.Checks.DoorsCount(configuration))
;
#if false
builder.Services
.AddHealthChecksUI(s =>
{
s.AddHealthCheckEndpoint("WDC_API_HC", "health");
s.SetEvaluationTimeInSeconds(60);
s.SetMinimumSecondsBetweenFailureNotifications(120);
s.SetApiMaxActiveRequests(5);
s.SetHeaderText("WDC.API Health Check Status");
})
.AddInMemoryStorage();
#endif
// abilitazione x email management con MailKit
//builder.Services.AddTransient<IEmailSender, MailKitEmailSender>();
builder.Services.AddSingleton<IEmailSender, MailKitEmailSender>();
builder.Services.Configure<MailKitEmailSenderOptions>(options =>
{
options.Host_Address = configuration["ExternalProviders:MailKit:SMTP:Address"] ?? "";
options.Host_Port = Convert.ToInt32(configuration["ExternalProviders:MailKit:SMTP:Port"] ?? "");
options.Host_Username = configuration["ExternalProviders:MailKit:SMTP:Account"] ?? "";
options.Host_Password = configuration["ExternalProviders:MailKit:SMTP:Password"] ?? "";
options.Sender_EMail = configuration["ExternalProviders:MailKit:SMTP:SenderEmail"] ?? "";
options.Sender_Name = configuration["ExternalProviders:MailKit:SMTP:SenderName"] ?? "";
});
// aggiunta servizi x accesso dati...
builder.Services.AddControllers()
.AddJsonOptions(c => c.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
builder.Services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>((options) =>
{
List<RedisConfiguration> newConf = new List<RedisConfiguration>();
var currConf = configuration.GetSection("Redis").Get<RedisConfiguration>();
if (currConf != null)
{
newConf.Add(currConf);
}
return newConf;
//return configuration.GetSection("Redis").Get<RedisConfiguration>();
});
builder.Services.AddSingleton<QueueDataService>();
builder.Services.AddSingleton<WebDoorCreatorService>();
builder.Services.AddSingleton<IConnectionMultiplexer>(redisMultiplexer);
var app = builder.Build();
// Configure the HTTP request pipeline.
// abilitato temporaneamente anche in iis01...
if (app.Environment.IsDevelopment() || app.Environment.IsStaging())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// config healthcheck: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks
// prende tutti i predicati
app.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
// nasconde tutti i dettagli
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = _ => false
});
app.Run();