Files
mapo-core/MP.Prog/Startup.cs
T
2022-02-22 16:24:32 +01:00

225 lines
9.5 KiB
C#

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MP.Prog.Data;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace MP.Prog
{
public class Startup
{
#region Public Constructors
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
#endregion Public Constructors
#region Public Properties
public IConfiguration Configuration { get; }
#endregion Public Properties
#region Public Methods
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// cultura IT...
var supportedCultures = new[]{
new CultureInfo("it-IT")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("it-IT"),
SupportedCultures = supportedCultures,
FallBackToParentCultures = false
});
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("it-IT");
//// Registrazione Elmah:
//// https://github.com/ElmahCore/ElmahCore
//app.UseElmah();
// fix forwarders
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
//app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
//app.UseAuthentication();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
//endpoints.MapControllers();
endpoints.MapBlazorHub();
//endpoints.MapHealthChecksUI();
//endpoints.MapHealthChecks("/health", new HealthCheckOptions
//{
// Predicate = _ => true,
// ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
//});
endpoints.MapFallbackToPage("/_Host");
});
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
#if false
// init info x DB
string dbServerAddr = Configuration["DbConfig:Server"];
string nKey = Configuration["DbConfig:nKey"];
string sKey = Configuration["DbConfig:sKey"];
DbConfig.InitDb(dbServerAddr, nKey, sKey);
// inizializzo il DB e creo (se necessario) l'utente
DbConfig.CheckUser(nKey, sKey);
// verifico se serve applicazione migrazioni
//DbConfig.ExecMigrationMain();
//DbConfig.ExecMigrationIdentity();
// altri parametri per check vari
string connStringDB = DbConfig.CONNECTION_STRING;
string connStringRedis = Configuration.GetConnectionString("Redis");
string redisSrvAddr = connStringRedis.Substring(0, connStringRedis.IndexOf(":"));
//var qrCodeUri = new Uri(Configuration["ZCodeUrl"]);
//string qrCodeAddr = qrCodeUri.Host;
#endif
#if false
// healthchecks
services.AddHealthChecks()
.AddMySql(connStringDB, "MySql instance")
.AddAsyncCheck($"DB PING ({dbServerAddr})", () => Health.Checks.PingCheck(dbServerAddr))
.AddAsyncCheck($"Redis PING ({redisSrvAddr})", () => Health.Checks.PingCheck(redisSrvAddr))
//.AddAsyncCheck($"QrCode PING ({qrCodeAddr})", () => Health.Checks.PingCheck(qrCodeAddr))
.AddProcessAllocatedMemoryHealthCheck(512, "Max Process memory (<512MB)", failureStatus: HealthStatus.Degraded) // 512 MB max allocated memory
.AddRedis(Configuration.GetConnectionString("Redis"), "Redis", failureStatus: HealthStatus.Degraded)
//.AddUrlGroup(new Uri(Configuration["ZCodeUrl"]), name: $"QrCode Gen ({Configuration["ZCodeUrl"]})", failureStatus: HealthStatus.Degraded)
.AddAsyncCheck($"MySql Root User", () => Health.Checks.DbUserRoot("MySql"))
.AddAsyncCheck($"MySql App Users", () => Health.Checks.DbUserApp(DbConfig.DATABASE_NAME))
.AddAsyncCheck($"MySql Identity", () => Health.Checks.DbIdentity(DbConfig.DATABASE_NAME))
.AddAsyncCheck($"MySql PlantLog", () => Health.Checks.DbPlantLogTable(DbConfig.DATABASE_NAME))
;
//.AddDiskStorageHealthCheck(s => s.AddDrive("C:\\", 1024)) // 1024 MB (1 GB) free minimum
//.AddProcessHealthCheck("ProcessName", p => p.Length > 0) // check if process is running
//.AddWindowsServiceHealthCheck("someservice", s => s.Status == ServiceControllerStatus.Running);
services
.AddHealthChecksUI(s =>
{
s.AddHealthCheckEndpoint("GWMS_Services", "health");
s.SetEvaluationTimeInSeconds(60);
s.SetMinimumSecondsBetweenFailureNotifications(120);
s.SetApiMaxActiveRequests(5);
s.SetHeaderText("GWMS Health Check Status");
})
.AddInMemoryStorage();
// abilitazione x email management con MailKit
services.AddTransient<IEmailSender, MailKitEmailSender>();
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"];
});
#endif
// cookie applicazione da 14 gg (defaul) a 30
services.ConfigureApplicationCookie(o =>
{
o.ExpireTimeSpan = TimeSpan.FromDays(30);
o.SlidingExpiration = true;
});
#if false
// token di sicurezza dati a 3h
services.Configure<DataProtectionTokenProviderOptions>(o =>
o.TokenLifespan = TimeSpan.FromHours(3));
#endif
#if false
// setup MySql
//string connString = Configuration.GetConnectionString("AdminConnection");
var serverVersion = DbConfig.MysqlServerVersion(connStringDB);
services.AddDbContext<UserIdentityDbContext>(options =>
options.UseMySql(connStringDB, serverVersion));
// identity management
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<UserIdentityDbContext>();
#endif
//// Elmah
//services.AddElmah();
//string elmaConn = "Data Source=SQL2016DEV;Initial Catalog=Elmah;User ID=sa;Password=keyhammer16;integrated security=False;MultipleActiveResultSets=True;App=SHERPA.BBM;";
//services.AddElmah<SqlErrorLog>(options =>
//{
// options.ConnectionString = elmaConn;
//});
services.AddStackExchangeRedisCache(options =>
{
//options.Configuration = "localhost:6379";
options.ConfigurationOptions = new StackExchange.Redis.ConfigurationOptions() { KeepAlive = 180, DefaultDatabase = 5, EndPoints = { { "localhost", 6379 } } };
options.InstanceName = "MP:Prog";
});
services.AddLocalization();
services.AddRazorPages();
services.AddServerSideBlazor();
#if false
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddDatabaseDeveloperPageExceptionFilter();
#endif
services.AddSingleton<IConfiguration>(Configuration);
//services.AddTransient<Services.BlazorTimer>();
//services.AddSingleton<FileArchDataService>();
services.AddScoped<FileArchDataService>();
services.AddScoped<MessageService>();
}
#endregion Public Methods
}
}