Files
2026-04-27 14:56:48 +02:00

236 lines
8.3 KiB
C#

using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using MP.Core.Conf;
using MP.Core.DTO;
using MP.Core.Objects;
using MP.Data.MgModels;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MP.Data.Controllers
{
public class MpMongoController : IDisposable
{
public MpMongoController(IConfiguration configuration)
{
_configuration = configuration;
string mongoConf = _configuration.GetConnectionString("mdbConnString");
client = new MongoClient(mongoConf);
mongoDb = client.GetDatabase("MAPO");
Log.Info("Avviata classe MpMongoController");
}
/// <summary>
/// Database corrente MongoDB
/// </summary>
private IMongoDatabase mongoDb;
public void Dispose()
{
client = null;
_configuration = null;
}
/// <summary>
/// Ricerca ricetta su MongoDB dato PODL
/// </summary>
/// <param name="idxPODL"></param>
/// <returns></returns>
public async Task<RecipeModel> RecipeGetByPODL(int idxPODL)
{
await Task.Delay(1);
RecipeModel answ = new RecipeModel();
try
{
// definisco filtro
var filtBuilder = Builders<RecipeModel>.Filter;
var filter = filtBuilder.Eq<int>("IdxPODL", idxPODL);
var collectionData = mongoDb.GetCollection<RecipeModel>("RecipeArchive");
// recupero
answ = collectionData.Find(filter).Project<RecipeModel>("{_id: 0}").FirstOrDefault<RecipeModel>();
}
catch
{ }
return answ;
}
/// <summary>
/// Ricerca ricetta su MongoDB dato ID MongoDB
/// </summary>
/// <param name="mID"></param>
/// <returns></returns>
public async Task<RecipeModel> RecipeGetByID(string mID)
{
await Task.Delay(1);
RecipeModel answ = new RecipeModel();
try
{
// definisco filtro
var filtBuilder = Builders<RecipeModel>.Filter;
var filter = filtBuilder.Eq<string>("_id", mID);
var collectionData = mongoDb.GetCollection<RecipeModel>("RecipeArchive");
// recupero
answ = collectionData.Find(filter).Project<RecipeModel>("{_id: 0}").FirstOrDefault<RecipeModel>();
}
catch
{ }
return answ;
}
/// <summary>
/// Salva ricetta su MongoDB
/// </summary>
/// <param name="currRecord"></param>
/// <returns></returns>
public async Task<bool> RecipeSetByPODL(RecipeModel currRecord)
{
await Task.Delay(1);
bool answ = false;
try
{
// definisco filtro
var filtBuilder = Builders<RecipeModel>.Filter;
var filter = filtBuilder.Eq<int>("IdxPODL", currRecord.IdxPODL);
var collectionData = mongoDb.GetCollection<RecipeModel>("RecipeArchive");
// elimino old
collectionData.DeleteMany(filter);
// aggiungo
collectionData.InsertOne(currRecord);
answ = true;
}
catch (Exception exc)
{
Log.Error($"Eccezione in RecipeSetByPODL{Environment.NewLine}{exc}");
}
return answ;
}
/// <summary>
/// Salva i dataItems della macchina indicata in MongoDB
/// </summary>
/// <param name="idxMacchina"></param>
/// <param name="dataItems"></param>
/// <returns></returns>
public bool SaveMachineDataItems(string idxMacchina, List<MachDataItem> dataItems)
{
bool answ = false;
var collMtcSetup = mongoDb.GetCollection<MtcSetupDto>("MtcSetup");
// compongo filtro ricerca e metodo update
var filter = Builders<MtcSetupDto>.Filter.Eq(u => u.IdxMacchina, idxMacchina);
// chiamo update: cerco riga, se c'è aggiorno sennò creo
MtcSetupDto newDoc = new MtcSetupDto()
{
IdxMacchina = idxMacchina,
DataItems = dataItems
};
// elimino se ci fosse già...
collMtcSetup.DeleteMany(filter);
// inserisco ex novo!
collMtcSetup.InsertOne(newDoc);
answ = true;
return answ;
}
/// <summary>
/// Init ricetta dato PODL + conf
/// </summary>
/// <param name="confPath"></param>
/// <param name="idxPODL"></param>
/// <param name="CalcArgs"></param>
/// <returns></returns>
public RecipeModel InitRecipe(string confPath, int idxPODL, Dictionary<string, string> CalcArgs)
{
RecipeModel answ = new RecipeModel();
// per prima cosa leggo file di conf x inizializzare ricetta...
string fullPath = RecipePath(confPath);
bool fileOk = File.Exists(fullPath);
if (fileOk)
{
string rawData = File.ReadAllText(fullPath);
var currRecipe = JsonConvert.DeserializeObject<RecipeConfig>(rawData);
// inizializzo dalla conf...
answ = new RecipeModel(idxPODL, currRecipe, CalcArgs);
}
return answ;
}
/// <summary>
/// Ricetta in formato calcolato (string)
/// </summary>
public string CalcRecipe(RecipeModel currRecipe)
{
string answ = "";
// per prima cosa leggo file di conf x inizializzare ricetta...
string fullPath = RecipePath(currRecipe.TemplateFile);
bool fileOk = File.Exists(fullPath);
if (fileOk)
{
// preparo dati header
var headStrings = currRecipe.HeadVal.Select(x => $"\"{x.Key}\": \"{x.Value}\"").ToList();
string headVals = string.Join(",", headStrings);
// leggo template
string rawData = File.ReadAllText(fullPath);
// recupero configurazione x inizio/fine righe
string[] righe = rawData.Split(Environment.NewLine);
List<string> righeRed = new List<string>();
string sRow = "";
string eRow = "";
foreach (var riga in righe)
{
if (riga.Trim().StartsWith("||SROW:"))
{
sRow = riga.Trim().Replace("||SROW:", "").Replace("||", "");
}
else if (riga.Trim().StartsWith("||EROW:"))
{
eRow = riga.Trim().Replace("||EROW:", "").Replace("||", "");
}
else
{
righeRed.Add(riga);
}
}
// rigenero righe senza le parti da ripetere...
rawData = string.Join(Environment.NewLine, righeRed);
// effettuo sostituzione...
answ = rawData.Replace("||PlaceholderHeader||", headVals);
// per le righe prima calcolo blocchi ripetuti
List<string> rowComp = new List<string>();
foreach (var item in currRecipe.RowsVal)
{
var rowsStrings = item.Value.Select(x => $"\"{x.Key}\": \"{x.Value}\"").ToList();
rowComp.Add($"{sRow}{string.Join(",", rowsStrings)}{eRow}");
}
string rowsVals = string.Join($",{Environment.NewLine}", rowComp);
//...poi sostituisco
answ = answ.Replace("||PlaceholderRows||", rowsVals);
}
return answ;
}
private MongoClient client = new MongoClient("mongodb://localhost:27017");
private static IConfiguration _configuration;
private static Logger Log = LogManager.GetCurrentClassLogger();
public static string RecipePath(string ruleName)
{
return string.Format($"Recipe/{ruleName}");
}
}
}