496 lines
16 KiB
C#
496 lines
16 KiB
C#
using MagMan.Core;
|
|
using MagMan.Data.Admin.Controllers;
|
|
using MagMan.Data.Admin.DbModels;
|
|
using Microsoft.AspNetCore.Identity.UI.Services;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.VisualBasic;
|
|
using Newtonsoft.Json;
|
|
using NLog;
|
|
using StackExchange.Redis;
|
|
using System.Diagnostics;
|
|
|
|
namespace MagMan.Data.Admin.Services
|
|
{
|
|
public class MultiTenantService
|
|
{
|
|
#region Public Fields
|
|
|
|
public static MultiTenantController dbController = null!;
|
|
|
|
#endregion Public Fields
|
|
|
|
#region Public Constructors
|
|
|
|
public MultiTenantService(IConfiguration configuration, IConnectionMultiplexer redisConnMult, IEmailSender emailSender)
|
|
{
|
|
Log.Info("MultiTenantService starting...");
|
|
_configuration = configuration;
|
|
_emailSender = emailSender;
|
|
// Conf cache
|
|
redisConn = redisConnMult;
|
|
redisDb = this.redisConn.GetDatabase();
|
|
|
|
// json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/
|
|
JSSettings = new JsonSerializerSettings()
|
|
{
|
|
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
|
|
};
|
|
|
|
// cod app
|
|
CodApp = _configuration["CodApp"];
|
|
dbController = new MultiTenantController(configuration);
|
|
|
|
// chiudo log
|
|
Log.Info("MultiTenantService started!");
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Properties
|
|
|
|
public string CodApp { get; set; } = "";
|
|
|
|
#endregion Public Properties
|
|
|
|
#region Public Methods
|
|
|
|
/// <summary>
|
|
/// Delete record AuthKey + refresh cache
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> AuthKeyDelete(AuthKeyModel currItem)
|
|
{
|
|
bool fatto = false;
|
|
try
|
|
{
|
|
fatto = dbController.AuthKeyDelete(currItem);
|
|
if (fatto)
|
|
{
|
|
await FlushRedisCache();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during AuthKeyDelete:{Environment.NewLine}{exc}");
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Lista AuthKey
|
|
/// </summary>
|
|
/// <param name="CustomerId">0 = tutti</param>
|
|
/// <returns></returns>
|
|
public async Task<List<AuthKeyModel>> AuthKeyGetFilt(int CustomerId)
|
|
{
|
|
string source = "DB";
|
|
List<AuthKeyModel>? dbResult = new List<AuthKeyModel>();
|
|
try
|
|
{
|
|
string currKey = $"{Const.rKeyConfig}:AuthKeyList:{CustomerId}";
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
string? rawData = await redisDb.StringGetAsync(currKey);
|
|
if (!string.IsNullOrEmpty(rawData))
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<List<AuthKeyModel>>(rawData);
|
|
if (tempResult == null)
|
|
{
|
|
dbResult = new List<AuthKeyModel>();
|
|
}
|
|
else
|
|
{
|
|
dbResult = tempResult;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
dbResult = dbController.AuthKeyGetFilt(CustomerId);
|
|
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
|
|
await redisDb.StringSetAsync(currKey, rawData, TSCacheLong);
|
|
}
|
|
if (dbResult == null)
|
|
{
|
|
dbResult = new List<AuthKeyModel>();
|
|
}
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Debug($"AuthKeyGetFilt | {source} in: {ts.TotalMilliseconds} ms");
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during AuthKeyGetFilt:{Environment.NewLine}{exc}");
|
|
}
|
|
return dbResult;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Update record AuthKey + refresh cache
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> AuthKeyUpdate(AuthKeyModel currItem)
|
|
{
|
|
bool fatto = false;
|
|
try
|
|
{
|
|
fatto = dbController.AuthKeyUpdate(currItem);
|
|
if (fatto)
|
|
{
|
|
await FlushRedisCache();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during AuthKeyUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Delete record customer + refresh cache
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> CustomerDelete(CustomerModel currItem)
|
|
{
|
|
bool fatto = false;
|
|
try
|
|
{
|
|
fatto = dbController.CustomerDelete(currItem);
|
|
if (fatto)
|
|
{
|
|
await FlushRedisCache();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during CustomerDelete:{Environment.NewLine}{exc}");
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Lista Customers
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<List<CustomerModel>> CustomerGetAll()
|
|
{
|
|
string source = "DB";
|
|
List<CustomerModel>? dbResult = new List<CustomerModel>();
|
|
try
|
|
{
|
|
string currKey = $"{Const.rKeyConfig}:CustomersList";
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
string? rawData = await redisDb.StringGetAsync(currKey);
|
|
if (!string.IsNullOrEmpty(rawData))
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<List<CustomerModel>>(rawData);
|
|
if (tempResult == null)
|
|
{
|
|
dbResult = new List<CustomerModel>();
|
|
}
|
|
else
|
|
{
|
|
dbResult = tempResult;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
dbResult = dbController.CustomerGetAll();
|
|
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
|
|
await redisDb.StringSetAsync(currKey, rawData, TSCacheLong);
|
|
}
|
|
if (dbResult == null)
|
|
{
|
|
dbResult = new List<CustomerModel>();
|
|
}
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Debug($"CustomerGetAll | {source} in: {ts.TotalMilliseconds} ms");
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during CustomerGetAll:{Environment.NewLine}{exc}");
|
|
}
|
|
return dbResult;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Update record customer + refresh cache
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> CustomerUpdate(CustomerModel currItem)
|
|
{
|
|
bool fatto = false;
|
|
try
|
|
{
|
|
fatto = dbController.CustomerUpdate(currItem);
|
|
if (fatto)
|
|
{
|
|
await FlushRedisCache();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during CustomerUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Refresh globale cache redis
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public async Task<bool> FlushRedisCache()
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
await Task.Delay(1);
|
|
RedisValue pattern = new RedisValue($"{Const.rKeyConfig}:*");
|
|
bool answ = await ExecFlushRedisPattern(pattern);
|
|
stopWatch.Stop();
|
|
Log.Debug($"FlushRedisCache in {stopWatch.Elapsed.TotalMilliseconds} ms");
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Delete record Machine + refresh cache
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> MachineDelete(MachineModel currItem)
|
|
{
|
|
bool fatto = false;
|
|
try
|
|
{
|
|
fatto = dbController.MachineDelete(currItem);
|
|
if (fatto)
|
|
{
|
|
await FlushRedisCache();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during MachineDelete:{Environment.NewLine}{exc}");
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Lista Macchine
|
|
/// </summary>
|
|
/// <param name="CustomerId">0 = tutti</param>
|
|
/// <returns></returns>
|
|
public async Task<List<MachineModel>> MachineGetFilt(int CustomerId)
|
|
{
|
|
string source = "DB";
|
|
List<MachineModel>? dbResult = new List<MachineModel>();
|
|
try
|
|
{
|
|
string currKey = $"{Const.rKeyConfig}:MachineList:{CustomerId}";
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
string? rawData = await redisDb.StringGetAsync(currKey);
|
|
if (!string.IsNullOrEmpty(rawData))
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<List<MachineModel>>(rawData);
|
|
if (tempResult == null)
|
|
{
|
|
dbResult = new List<MachineModel>();
|
|
}
|
|
else
|
|
{
|
|
dbResult = tempResult;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
dbResult = dbController.MachineGetFilt(CustomerId);
|
|
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
|
|
await redisDb.StringSetAsync(currKey, rawData, TSCacheLong);
|
|
}
|
|
if (dbResult == null)
|
|
{
|
|
dbResult = new List<MachineModel>();
|
|
}
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Debug($"MachineGetFilt | {source} in: {ts.TotalMilliseconds} ms");
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during MachineGetFilt:{Environment.NewLine}{exc}");
|
|
}
|
|
return dbResult;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Update record Machine + refresh cache
|
|
/// </summary>
|
|
/// <param name="currItem"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> MachineUpdate(MachineModel currItem)
|
|
{
|
|
bool fatto = false;
|
|
try
|
|
{
|
|
fatto = dbController.MachineUpdate(currItem);
|
|
if (fatto)
|
|
{
|
|
await FlushRedisCache();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Error during MachineUpdate:{Environment.NewLine}{exc}");
|
|
}
|
|
return fatto;
|
|
}
|
|
|
|
#endregion Public Methods
|
|
|
|
#region Private Fields
|
|
|
|
private static IConfiguration _configuration = null!;
|
|
private static JsonSerializerSettings? JSSettings;
|
|
private static Logger Log = LogManager.GetCurrentClassLogger();
|
|
private readonly IEmailSender _emailSender;
|
|
|
|
/// <summary>
|
|
/// Durata cache lunga IN SECONDI
|
|
/// </summary>
|
|
private int cacheTtlLong = 60 * 5;
|
|
|
|
/// <summary>
|
|
/// Durata cache breve IN SECONDI
|
|
/// </summary>
|
|
private int cacheTtlShort = 60 * 1;
|
|
|
|
/// <summary>
|
|
/// Oggetto per connessione a REDIS
|
|
/// </summary>
|
|
private IConnectionMultiplexer redisConn;
|
|
|
|
/// <summary>
|
|
/// Oggetto DB redis da impiegare x chiamate R/W
|
|
/// </summary>
|
|
private IDatabase redisDb = null!;
|
|
|
|
/// <summary>
|
|
/// Generatore random
|
|
/// </summary>
|
|
private Random rnd = new Random();
|
|
|
|
#endregion Private Fields
|
|
|
|
#if false
|
|
/// <summary>
|
|
/// Update company
|
|
/// </summary>
|
|
/// <param name="currRec"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> CompanyAddMod(CompanyModel currRec)
|
|
{
|
|
var dbResult = await dbController.CompanyAddMod(currRec);
|
|
try
|
|
{
|
|
// elimino cache redis...
|
|
RedisValue pattern = new RedisValue($"{Constants.rKeyCompany}");
|
|
bool answ = await ExecFlushRedisPattern(pattern);
|
|
await Task.Delay(1);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Exception during CompanyAddMod: {exc}{Environment.NewLine}");
|
|
}
|
|
return dbResult;
|
|
}
|
|
#endif
|
|
|
|
#if false
|
|
// <summary>
|
|
/// Getting a list of all the active components </summary> <param name="rootPath">Path to
|
|
/// start</param> <returns></returns>
|
|
public async Task<List<string>> CompoGetAllActive(string rootPath)
|
|
{
|
|
await Task.Delay(1);
|
|
List<string> listActiveCompo = new List<string>();
|
|
|
|
try
|
|
{
|
|
//estraggo la lista di componenti che sono attive per il cliente
|
|
IniFile fIni = new IniFile(rootPath);
|
|
string compoDDF = fIni.ReadString("CompoOrder", "CompoDDFOrder", "CONFIG");
|
|
var compoDDFList = compoDDF.Split(",");
|
|
foreach (string compo in compoDDFList)
|
|
{
|
|
listActiveCompo.Add(compo.Trim());
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Log.Error($"Exception during CompoGetAllActive: {exc}{Environment.NewLine}");
|
|
}
|
|
return listActiveCompo;
|
|
}
|
|
#endif
|
|
|
|
#region Private Properties
|
|
|
|
/// <summary>
|
|
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
|
|
/// </summary>
|
|
private TimeSpan TSCacheLong
|
|
{
|
|
get => TimeSpan.FromSeconds(cacheTtlLong * 1 * rnd.Next(900, 1100) / 1000);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Durata cache lunghissima (+ perturbazione percentuale +/-10%)
|
|
/// </summary>
|
|
private TimeSpan TSCacheultraLong
|
|
{
|
|
get => TimeSpan.FromSeconds(cacheTtlLong * 10 * rnd.Next(900, 1100) / 1000);
|
|
}
|
|
|
|
#endregion Private Properties
|
|
|
|
#region Private Methods
|
|
|
|
/// <summary>
|
|
/// Esegue flush memoria redis dato pattern
|
|
/// </summary>
|
|
/// <param name="pattern"></param>
|
|
/// <returns></returns>
|
|
private async Task<bool> ExecFlushRedisPattern(RedisValue pattern)
|
|
{
|
|
bool answ = false;
|
|
var listEndpoints = redisConn.GetEndPoints();
|
|
foreach (var endPoint in listEndpoints)
|
|
{
|
|
//var server = redisConnAdmin.GetServer(listEndpoints[0]);
|
|
var server = redisConn.GetServer(endPoint);
|
|
if (server != null)
|
|
{
|
|
var keyList = server.Keys(redisDb.Database, pattern);
|
|
foreach (var item in keyList)
|
|
{
|
|
await redisDb.KeyDeleteAsync(item);
|
|
}
|
|
answ = true;
|
|
}
|
|
}
|
|
|
|
return answ;
|
|
}
|
|
|
|
#endregion Private Methods
|
|
}
|
|
} |