Files
magman/MagMan.Data.Tenant/Services/MessageService.cs
T
2024-01-17 15:17:32 +01:00

481 lines
15 KiB
C#

using Blazored.LocalStorage;
using Blazored.SessionStorage;
using Microsoft.Extensions.Configuration;
using NLog;
using NLog.Fluent;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace MagMan.Data.Tenant.Services
{
public class MessageService
{
#region Public Events
public event Action EA_FilterUpdated = null!;
public event Action EA_HideSearch = null!;
public event Action EA_PageUpdated = null!;
public event Action EA_SearchUpdated = null!;
public event Action EA_ShowSearch = null!;
#endregion Public Events
#region Public Properties
public SelectData DetailFilter
{
get => _detailFilter;
set
{
if (_detailFilter != value)
{
_detailFilter = value;
if (EA_FilterUpdated != null)
{
EA_FilterUpdated?.Invoke();
}
}
}
}
public SelectOrderData Order_Filter { get; set; } = SelectOrderData.Init(5, 30);
public string PageIcon
{
get => _pageIcon;
set
{
if (_pageIcon != value)
{
_pageIcon = value;
ReportPageUpd();
}
}
}
public string PageName
{
get => _pageName;
set
{
if (_pageName != value)
{
_pageName = value;
ReportPageUpd();
}
}
}
public string SearchVal
{
get => _searchVal;
set
{
if (_searchVal != value)
{
_searchVal = value;
if (EA_SearchUpdated != null)
{
EA_SearchUpdated?.Invoke();
}
}
}
}
public string SelOrderCode { get; set; } = "";
public string SelPlantId { get; set; } = "0";
public bool ShowSearch
{
get => _showSearch;
set
{
if (_showSearch != value)
{
_showSearch = value;
if (_showSearch)
{
if (EA_ShowSearch != null)
{
EA_ShowSearch?.Invoke();
}
}
else
{
if (EA_HideSearch != null)
{
EA_HideSearch?.Invoke();
}
}
}
}
}
#endregion Public Properties
public MessageService(IConfiguration configuration, ILocalStorageService genLocalStorage, ISessionStorageService sessStore)
{
_configuration = configuration;
// gestione sessioni in browser
localStore = genLocalStorage;
sessionStore = sessStore;
// setup compoenti REDIS
redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
redisDb = redisConn.GetDatabase();
}
protected static IConfiguration _configuration = null!;
#region Public Methods
/// <summary>
/// Svuota localstorage (clear)
/// </summary>
/// <returns></returns>
public async Task<bool> StoreLocalClear()
{
bool answ = false;
try
{
await localStore.ClearAsync();
answ = true;
}
catch (Exception ex)
{
Log.Error($"Eccezione in StoreLocalClear{Environment.NewLine}{ex}");
}
return answ;
}
/// <summary>
/// Restituisce il valore richiesto da localstorage
/// </summary>
/// <param name="sKey">Chiave</param>
/// <returns></returns>
public async Task<string> StoreLocalGet(string sKey)
{
string answ = "";
var result = await localStore.GetItemAsync<string>(sKey);
if (result != null)
{
answ = result;
}
return answ;
}
/// <summary>
/// Scrive il valore nel localstorage
/// </summary>
/// <param name="sKey">Chiave</param>
/// <param name="sVal">Valore associato</param>
/// <returns></returns>
public async Task<bool> StoreLocalSet(string sKey, string sVal)
{
bool answ = false;
try
{
await localStore.SetItemAsStringAsync(sKey, sVal);
answ = true;
}
catch (Exception ex)
{
Log.Error($"Eccezione in StoreLocalSet{Environment.NewLine}{ex}");
}
return answ;
}
/// <summary>
/// Svuota sessionstorage (clear)
/// </summary>
/// <returns></returns>
public async Task<bool> StoreSessClear()
{
bool answ = false;
try
{
await sessionStore.ClearAsync();
answ = true;
}
catch (Exception ex)
{
Log.Error($"Eccezione in StoreLocalClear{Environment.NewLine}{ex}");
}
return answ;
}
/// <summary>
/// Restituisce il valore richiesto da sessionstorage
/// </summary>
/// <param name="sKey">Chiave</param>
/// <returns></returns>
public async Task<string> StoreSessGet(string sKey)
{
string answ = "";
var result = await sessionStore.GetItemAsync<string>(sKey);
if (result != null)
{
answ = result;
}
return answ;
}
/// <summary>
/// Scrive il valore nel sessionstorage (tab)
/// </summary>
/// <param name="sKey">Chiave</param>
/// <param name="sVal">Valore associato</param>
/// <returns></returns>
public async Task<bool> StoreSessSet(string sKey, string sVal)
{
bool answ = false;
try
{
await sessionStore.SetItemAsStringAsync(sKey, sVal);
answ = true;
}
catch (Exception ex)
{
Log.Error($"Eccezione in StoreSessSet{Environment.NewLine}{ex}");
}
return answ;
}
#endregion Public Methods
#region Protected Properties
protected ILocalStorageService localStore { get; set; } = null!;
protected ISessionStorageService sessionStore { get; set; } = null!;
#endregion Protected Properties
#region Private Fields
private SelectData _detailFilter = SelectData.Init(5, 15);
private string _pageIcon = "";
private string _pageName = "";
private string _searchVal = "";
private bool _showSearch = false;
private Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
#region Private Methods
private void ReportPageUpd()
{
if (EA_PageUpdated != null)
{
EA_PageUpdated?.Invoke();
}
}
private void ReportSearch()
{
if (EA_SearchUpdated != null)
{
EA_SearchUpdated?.Invoke();
}
}
#endregion Private Methods
/// <summary>
/// Recupero HashSet redis come Dictionary
/// </summary>
/// <param name="currKey"></param>
/// <param name="dict"></param>
private Dictionary<string, string> RedisHashDictGet(RedisKey currKey)
{
Dictionary<string, string> answ = new Dictionary<string, string>();
try
{
answ = redisDb
.HashGetAll(currKey)
.ToDictionary(x => $"{x.Name}", x => $"{x.Value}");
}
catch (Exception exc)
{
Log.Info($"Errore RedisHashDictGet | currKey: {currKey}{Environment.NewLine}{exc}");
}
return answ;
}
/// <summary>
/// Oggetto per connessione a REDIS
/// </summary>
protected ConnectionMultiplexer redisConn = null!;
/// <summary>
/// Oggetto DB redis da impiegare x chiamate R/W
/// </summary>
protected IDatabase redisDb = null!;
/// <summary>
/// Salvataggio Dictionary come HashSet Redis
/// </summary>
/// <param name="currKey"></param>
/// <param name="dict"></param>
private bool RedisHashDictSet(RedisKey currKey, Dictionary<string, string> dict)
{
bool fatto = false;
try
{
HashEntry[] data2ins = new HashEntry[dict.Count];
int i = 0;
foreach (KeyValuePair<string, string> kvp in dict)
{
data2ins[i] = new HashEntry(kvp.Key, kvp.Value);
i++;
}
// salvo!
redisDb.HashSet(currKey, data2ins);
fatto = true;
}
catch (Exception exc)
{
Log.Error($"Eccezione in RedisHashDictSet | currKey: {currKey}{Environment.NewLine}{exc}");
}
return fatto;
}
/// <summary>
/// Salvataggio Dictionary come HashSet Redis
/// </summary>
/// <param name="currKey"></param>
/// <param name="dict"></param>
/// <param name="ttl"></param>
private bool RedisHashDictSet(RedisKey currKey, Dictionary<string, string> dict, TimeSpan ttl)
{
bool fatto = false;
try
{
HashEntry[] data2ins = new HashEntry[dict.Count];
int i = 0;
foreach (KeyValuePair<string, string> kvp in dict)
{
data2ins[i] = new HashEntry(kvp.Key, kvp.Value);
i++;
}
// salvo!
redisDb.HashSet(currKey, data2ins);
redisDb.KeyExpire(currKey, ttl);
fatto = true;
}
catch (Exception exc)
{
Log.Error($"Eccezione in RedisHashDictSet(+TTL) | currKey: {currKey} | ttl: {ttl}{Environment.NewLine}{exc}");
}
return fatto;
}
/// <summary>
/// Effettua upsert in HasList redis
/// </summary>
/// <param name="currKey">Chiave redis della Hashlist</param>
/// <param name="chiave">Chiave nella HashList</param>
/// <param name="valore">Valore da salvare</param>
/// <returns>Num record nella HashList</returns>
protected async Task<long> RedisHashUpsert(RedisKey currKey, string chiave, string valore)
{
long numReq = 0;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
await redisDb.HashSetAsync(currKey, chiave, valore);
numReq = await redisDb.HashLengthAsync(currKey);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"RedisHashUpsert | {currKey} | in: {ts.TotalMilliseconds} ms");
return numReq;
}
/// <summary>
/// Get single hash record
/// </summary>
/// <param name="currKey">Redis Key for Hashlist</param>
/// <param name="chiave">Requested key on list</param>
/// <returns>Value as Int</returns>
public async Task<int> RedisHashGetInt(RedisKey currKey, string chiave)
{
int result = 0;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var hasVal = await redisDb.HashExistsAsync(currKey, chiave);
if (hasVal)
{
var rawRes = await redisDb.HashGetAsync(currKey, chiave);
if (rawRes.HasValue)
{
int.TryParse($"{rawRes}", out result);
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"RedisHashGetInt | {currKey} | in: {ts.TotalMilliseconds} ms");
return result;
}
/// <summary>
/// Get single hash record
/// </summary>
/// <param name="currKey">Redis Key for Hashlist</param>
/// <param name="chiave">Requested key on list</param>
/// <returns>Value as string</returns>
public async Task<string> RedisHashGetString(RedisKey currKey, string chiave)
{
string result = "";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var hasVal = await redisDb.HashExistsAsync(currKey, chiave);
if (hasVal)
{
var rawRes = await redisDb.HashGetAsync(currKey, chiave);
if (rawRes.HasValue)
{
result = $"{rawRes}";
}
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"RedisHashGetString | {currKey} | in: {ts.TotalMilliseconds} ms");
return result;
}
/// <summary>
/// Remove for single hash record
/// </summary>
/// <param name="currKey">Chiave redis della Hashlist</param>
/// <param name="chiave">Chiave nella HashList</param>
/// <returns>Esito rimozione</returns>
public async Task<bool> RedisHashRemove(RedisKey currKey, string chiave)
{
bool fatto = false;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
fatto = await redisDb.HashDeleteAsync(currKey, chiave);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"RedisHashRemove | {currKey} | in: {ts.TotalMilliseconds} ms");
return fatto;
}
#if false
/// <summary>
/// Dizionario totale preferenze utente
/// </summary>
public Dictionary<string, string> UsersPrefDict
{
get => RedisHashDictGet((RedisKey)$"{redisBaseKey}:{MatrOpr}");
set => RedisHashDictSet((RedisKey)$"{redisBaseKey}:{MatrOpr}", value);
}
#endif
}
}