Files
Mapo-IOB/SMGen/Pages/SMEvent2State.razor.cs
T
zaccaria.majid 6cd06e6278 aggiunto log
2023-07-28 14:59:11 +02:00

420 lines
16 KiB
C#

using EgwCoreLib.Razor;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components;
using SMGen.Data.DbModels;
using SMGen.Data.Services;
using SMGen.Data;
using Microsoft.VisualBasic;
using NLog;
namespace SMGen.Pages
{
public partial class SMEvent2State
{
protected SelectSMIn2EvParams currFilter = new SelectSMIn2EvParams();
protected DataPager? pagerSMIn2Ev = null!;
protected bool b_rules_definition { get; set; } = false;
protected static Logger Log = LogManager.GetCurrentClassLogger();
[Inject]
protected IConfiguration conf { get; set; } = null!;
[Inject]
protected IWebHostEnvironment env { get; set; } = null!;
[Inject]
protected SMGDataService SMGDService { get; set; } = null!;
protected List<string> Events_to_send { get; set; } = new List<string>();
protected List<AnagEventiModelTemp> events2Add { get; set; } = new List<AnagEventiModelTemp>();
protected List<string> fileLines { get; set; } = new List<string>();
private Dictionary<string, bool> filesStatus
{
get => currFilter.FilesStatus;
set => currFilter.FilesStatus = value;
}
private Dictionary<string, string> files2Download
{
get => currFilter.Files2Download;
set => currFilter.Files2Download = value;
}
protected Dictionary<string, string> files2Read { get; set; } = new Dictionary<string, string>();
protected List<TransizioneIngressiModelTemp> TranInList2add { get; set; } = new List<TransizioneIngressiModelTemp>();
protected string n_state_machine_index { get; set; } = "";
protected int n_states { get; set; } = 0;
protected string pathDir { get; set; } = "";
protected string pathFile { get; set; } = "";
protected string procRootDir
{
get => conf.GetValue<string>("ServerConf:ProcCsvRootPath");
}
protected bool calcItself
{
get => conf.GetValue<bool>("SetupOptions:DoCalcItself");
}
protected bool calcEmptyState
{
get => conf.GetValue<bool>("SetupOptions:DoCalcEmptyState");
}
protected string statiCsvPath
{
get => conf.GetValue<string>("ServerConf:StatiCsvPath");
}
protected List<RuleClass> Rules { get; set; } = new List<RuleClass>();
protected Dictionary<string, int> StatesAll { get; set; } = new Dictionary<string, int>();
protected Dictionary<string, int> StatesAll2 { get; set; } = new Dictionary<string, int>();
protected List<string> States2Rules { get; set; } = new List<string>();
//protected string sz_file2Read { get; set; } = "D:\\Repo\\Mapo-IOB\\StateMachine\\_DEFAULT\\60_STD_MACHINE.rul";
protected string sz_file2Read { get; set; } = "";
protected string sz_file2Write { get; set; } = "prova.csv";
protected string sz_state_machine_name { get; set; } = "";
protected bool checkDirExist(string dir)
{
bool answ = false;
var dirEx = Directory.Exists(dir);
if (dirEx)
{
answ = true;
}
else
{
var dirCreate = Directory.CreateDirectory(dir);
if (dirCreate != null)
{
answ = true;
}
else
{
answ = false;
}
}
return answ;
}
protected async Task Read_rule_file_transitions()
{
foreach (var item in files2Read)
{
sz_file2Read = item.Value;
using (StreamReader sr = new StreamReader(sz_file2Read))
{
StatesAll.Clear();
Events_to_send.Clear();
Rules.Clear();
string line = "";
while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null)
{
if (!line.StartsWith("#") && !string.IsNullOrEmpty(line))
{
var sz_tokens = line.Split(":");
var sz_temp = sz_tokens[0].Trim();
switch (sz_temp)
{
case "$DEFINITIONS":
b_rules_definition = false;
break;
case "$NAME":
sz_state_machine_name = sz_tokens[1].Trim();
break;
case "$IDX":
n_state_machine_index = sz_tokens[1].Trim();
break;
#if false
case "$N_STATES":
n_states = int.Parse(sz_tokens[1].Trim());
break;
#endif
case "$STATE":
StatesAll.Add(sz_tokens[2].Trim().ToUpper(), int.Parse(sz_tokens[1].Trim().ToUpper()));
break;
case "$EVENT":
Events_to_send.Add(sz_tokens[2].Trim().ToUpper());
var newEvent = new AnagEventiModelTemp()
{
IdxTipo = int.Parse(sz_tokens[1].Trim().ToUpper()),
Nome = sz_tokens[2].Trim().ToUpper()
};
events2Add.Add(newEvent);
break;
case "$RULES":
b_rules_definition = true;
break;
case "$DO":
b_rules_definition = false;
var isOk = checkDirExist(Path.Combine(procRootDir, statiCsvPath));
if (isOk)
{
var fileName = $"{item.Key.Split(".")[0]}.csv";
evaluate_transitions($"{Path.Combine(procRootDir, statiCsvPath, fileName)}", item.Key);
}
break;
default:
if (b_rules_definition)
{
var state = sz_temp.Trim().ToUpper();
var event_to_send = sz_tokens[1].Trim().ToUpper();
var next_state = sz_tokens[2].Trim().ToUpper();
var temp_rule = new RuleClass()
{
state = state,
event_to_send = event_to_send,
next_state = next_state
};
Rules.Add(temp_rule);
States2Rules.Add(next_state);
}
break;
}
//fileLines.Add(lineSplit[0]);
}
}
}
}
}
protected async void evaluate_transitions(string sz_file2Write, string origFileName)
{
TranInList2add.Clear();
//events2Add.Clear();
using (StreamWriter sw = new StreamWriter(sz_file2Write))
{
sw.WriteLine("IdxFamiglia;IdxStato;IdxTipo;next_IdxStato");
int sz_actual_state = 0;
string sz_line = "";
foreach (var item in States2Rules)
{
if (!StatesAll2.ContainsKey(item))
{
StatesAll2.Add(item, StatesAll[item]);
StatesAll2 = StatesAll2.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
}
}
//ciclo negli stati
try
{
foreach (var item in StatesAll2)
{
sz_actual_state = item.Value;
foreach (var act_rule in Rules)
{
var exitFor = false;
if ((act_rule.state == "ALL_STATES") || (act_rule.state == StatesAll.Where(x => x.Value == sz_actual_state).FirstOrDefault().Key))
{
//DA RESETTARE A FALSE (errore da principianti...)
int nextState = StatesAll2[act_rule.next_state];
if (!exitFor)
{
sz_line = "";
//eseguo solo se diverso dallo stato corrente
// || calcItself
if (nextState != item.Value || calcItself)
{
if (nextState < 0)
{
nextState = 0;
}
if ((nextState == 0 && calcEmptyState) || (nextState > 0))
{
sz_line = $"{n_state_machine_index}" +
$";" +
$"{item.Value}" +
$";" +
$"{Events_to_send.IndexOf(act_rule.event_to_send)}" +
$";" +
$"{nextState}";
sw.WriteLine(sz_line);
var newTranIn = new TransizioneIngressiModelTemp()
{
IdxFamigliaIngresso = int.Parse(n_state_machine_index),
IdxMicroStato = item.Value,
IdxTipoEvento = Events_to_send.IndexOf(act_rule.event_to_send),
next_IdxMicroStato = nextState
};
TranInList2add.Add(newTranIn);
}
}
exitFor = true;
}
}
}
}
//await SMGDService.AnagEventinInsert(events2Add);
await Task.Delay(1);
filesStatus[origFileName] = true;
// await SMGDService.TranInInsert(TranInList2add, int.Parse(n_state_machine_index));
files2Download.Add(origFileName, sz_file2Write);
}
catch
{
filesStatus[origFileName] = false;
}
}
}
/// <summary>
/// Procedee a bonificare la cartella di upload dei files + vecchi di 3 mesi
/// </summary>
private void deleteOldFiles(string dirPath)
{
// elenco files nella directory
string[] files = Directory.GetFiles(dirPath);
// li guardo tutti e se vecchi li elimino...
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.LastAccessTime < DateTime.Now.AddMinutes(-20))
{
fi.Delete();
}
}
}
private int totalCount
{
get => currFilter.TotCount;
set => currFilter.TotCount = value;
}
private int numRecord
{
get => currFilter.NumRec;
set => currFilter.NumRec = value;
}
private int currPage
{
get => currFilter.CurrPage;
set => currFilter.CurrPage = value;
}
protected void UpdateTotCount(int newTotCount)
{
totalCount = newTotCount;
}
protected async Task updateFilter(SelectSMIn2EvParams newParams)
{
await Task.Delay(1);
currPage = 1;
// salvo comunque filtro reparto x utente
await Task.Delay(1);
await InvokeAsync(() => StateHasChanged());
currFilter = newParams;
}
protected async Task pgResetReq(bool doReset)
{
if (doReset)
{
await Task.Delay(1);
if (pagerSMIn2Ev != null)
{
pagerSMIn2Ev.resetCurrPage();
}
}
}
//// va dopo
//private StreamWriter objWriter { get; set; };
private async Task LoadFiles(InputFileChangeEventArgs e)
{
List<IBrowserFile> loadedFiles = new();
long maxFileSize = 1024 * 50;
int maxAllowedFiles = 150;
loadedFiles.Clear();
filesStatus.Clear();
files2Read.Clear();
foreach (var file in e.GetMultipleFiles(maxAllowedFiles))
{
try
{
loadedFiles.Add(file);
//assegno un nome file randomico x sicurezza
var trustedFileNameForFileStorage = Path.GetRandomFileName();
//path del file da scrivere
pathFile = Path.Combine(env.ContentRootPath,
env.EnvironmentName, "unsafe_uploads",
trustedFileNameForFileStorage);
//path cartella root (development)
pathDir = Path.Combine(env.ContentRootPath,
env.EnvironmentName, "unsafe_uploads");
//se la cartella non esiste, creo
if (!Directory.Exists(pathDir))
{
Directory.CreateDirectory(pathDir);
}
else
{
}
//creo file
await using FileStream fs = new(pathFile, FileMode.Create);
//copio il contenuto del file
await file.OpenReadStream(maxFileSize).CopyToAsync(fs);
if (file.Name.Contains(".rul"))
{
files2Read.Add(file.Name, pathFile);
filesStatus.Add(file.Name, false);
}
}
catch (Exception ex)
{
Log.Error($"Generato errore durante caricamento file: {Environment.NewLine}{ex}");
}
}
}
protected void ForceReload(int newNum)
{
numRecord = newNum;
}
protected void ForceReloadPage(int newNum)
{
currPage = newNum;
}
}
}