using MagMan.Core.DTO; using MagMan.Core; using MagMan.Data.Admin.DbModels; using MagMan.Data.Admin.Services; using MagMan.Data.Tenant.Services; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using NLog; using MagMan.Data.Tenant.DbModels; using k8s.Models; using MimeKit; namespace MagMan.UI.Controllers { [Route("api/[controller]")] [ApiController] public class LogMachineController : ControllerBase { #region Public Constructors public LogMachineController(MTAdminService MTDataService, TenantService TDataService) { MTAdmService = MTDataService; TService = TDataService; // 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 }; Log.Info("Avviata classe LogMachineController"); } #endregion Public Constructors #region Public Methods /// /// Controllo status Alive /// GET: api/LogMachine/alive /// /// [HttpGet("alive")] public string alive() { return $"OK"; } // GET api/LogMachine [HttpGet] public async Task> Get() { // se non ho chiave --> vuoto! List ListRecords = new List(); await Task.Delay(100); return ListRecords; } /// /// Elenco ultimi valori LogMachineModel dato RestToken /// /// Rest Token cliente /// Chiave associata ai progetti /// idMacchina di cui si vuole log /// num rec max da recuperare /// // GET api/LogMachine/2cba60c7-7be4-40b1-aa0d-52e7c71fc1a7 [HttpGet("{id}")] public async Task> Get(string id, int KeyNum, int machineId, int numRec) { List ListRecords = new List(); if (!string.IsNullOrEmpty(id)) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); var rawList = await TService.LogMacGetLast(nKey, machineId, numRec); if (rawList != null) { ListRecords.AddRange(rawList); } } return ListRecords; } /// /// Processa una chiamata POST per esecuzione chiamata remove range /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 /// /// token comunicazione /// ID del progetto creato da usare come CloudId [HttpPost("remove/{id}")] public async Task remove(string id, [FromBody] RestPayload.PeriodData rawData) { int answ = 0; // verifico ci sia valore if (!string.IsNullOrEmpty(id) && rawData != null) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); int machId = 0; var machList = await MTAdmService.MachineGetByToken(id); if (machList != null && machList.Count > 0) { var dbResult = machList .Where(x => x.MainKey == nKey) .FirstOrDefault(); if (dbResult != null) { machId = dbResult.MachineID; } } if (nKey > 0) { try { // rimuovo! answ = await TService.LogMacRemoveRange(nKey, machId, rawData.DtStart, rawData.DtEnd); } catch (Exception exc) { Log.Error($"LogMachineController.remove | Errore in fase esecuzione richiesta{Environment.NewLine}{exc}"); } // resetto cache redis await MTAdmService.FlushRedisCache(); } } return answ; } /// /// Processa una chiamata POST per l'invio di un oggetto di upsert progetto /// PUT: api/Inventory/upsert/00000000-0000-0000-0000-000000000000 /// /// token comunicazione /// ID del progetto creato da usare come CloudId [HttpPost("upsert/{id}")] public async Task upsert(string id, [FromBody] RestPayload.LogData rawData) { int answ = 0; // verifico ci sia valore if (!string.IsNullOrEmpty(id) && rawData != null && rawData.LogList != null) { // in primis recupero codice chiave da token... int nKey = await MTAdmService.MainKeyByToken(id); int machId = 0; var machList = await MTAdmService.MachineGetByToken(id); if (machList != null && machList.Count > 0) { var dbResult = machList .Where(x => x.MainKey == nKey) .FirstOrDefault(); if (dbResult != null) { machId = dbResult.MachineID; } } if (nKey > 0) { // converto elenco da Dto --> DB var listRec = rawData.LogList.Select(x => TService.LogMacFromDto(x, machId, nKey)).ToList(); try { // FixMe ToDo: schematizzare/configurare/implementare/installare online List> listBlock = new List>(); // divido in blocchi... gestire da config! (4/8) int numParall = 4; int numTot = rawData.LogList.Count; int bSize = (int)Math.Ceiling((decimal)numTot / numParall); for (int i = 0; i < numParall; i++) { listBlock.Add(listRec.Skip(i * bSize).Take(bSize).ToList()); } var options = new ParallelOptions { MaxDegreeOfParallelism = numParall }; await Parallel.ForEachAsync(listBlock, async (subList, token) => { // upsert! int numDone = await TService.LogMacUpdate(nKey, subList); answ += numDone; }); #if false // upsert! answ = await TService.LogMacUpdate(nKey, listRec); #endif } catch (Exception exc) { Log.Error($"LogMachineController.upsert | Errore in fase salvataggio di {rawData.LogList.Count} LogMacDTO{Environment.NewLine}{exc}"); } // resetto cache redis await MTAdmService.FlushRedisCache(); } } return answ; } #endregion Public Methods #region Private Fields private static JsonSerializerSettings? JSSettings; /// /// Classe per logging /// private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields #region Private Properties private MTAdminService MTAdmService { get; set; } = null!; private TenantService TService { get; set; } = null!; #endregion Private Properties } }