Files
Data-Coupler/Data_Coupler/Services/VersionService.cs
T

122 lines
4.1 KiB
C#

using Data_Coupler.Models;
using System.Text.Json;
namespace Data_Coupler.Services
{
/// <summary>
/// Interfaccia per il servizio di gestione versione applicazione
/// </summary>
public interface IVersionService
{
/// <summary>
/// Ottiene le informazioni sulla versione corrente dell'applicazione
/// </summary>
VersionInfo GetVersion();
/// <summary>
/// Ottiene la versione formattata per display nell'UI
/// </summary>
string GetDisplayVersion();
}
/// <summary>
/// Servizio per gestire le informazioni di versione dell'applicazione
/// Legge i dati da version.json generato durante il build
/// </summary>
public class VersionService : IVersionService
{
private readonly VersionInfo _versionInfo;
private readonly ILogger<VersionService> _logger;
private readonly IWebHostEnvironment _env;
public VersionService(ILogger<VersionService> logger, IWebHostEnvironment env)
{
_logger = logger;
_env = env;
_versionInfo = LoadVersionInfo();
}
/// <summary>
/// Carica le informazioni di versione dal file version.json
/// </summary>
private VersionInfo LoadVersionInfo()
{
try
{
// Cerca il file version.json nella cartella wwwroot o nella root del progetto
string? versionFilePath = null;
// Prima prova in wwwroot
if (!string.IsNullOrEmpty(_env.WebRootPath))
{
var wwwrootPath = Path.Combine(_env.WebRootPath, "version.json");
if (File.Exists(wwwrootPath))
{
versionFilePath = wwwrootPath;
}
}
// Se non trovato, prova nella root del progetto
if (versionFilePath == null)
{
var contentPath = Path.Combine(_env.ContentRootPath, "wwwroot", "version.json");
if (File.Exists(contentPath))
{
versionFilePath = contentPath;
}
}
if (versionFilePath != null && File.Exists(versionFilePath))
{
var json = File.ReadAllText(versionFilePath);
var version = JsonSerializer.Deserialize<VersionInfo>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (version != null)
{
_logger.LogInformation("Version loaded from {Path}: {Version}", versionFilePath, version.GetFullVersion());
return version;
}
}
else
{
_logger.LogWarning("version.json not found. Searched in WebRootPath: {WebRoot}, ContentRootPath: {ContentRoot}",
_env.WebRootPath ?? "null", _env.ContentRootPath);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading version.json, using default version");
}
// Versione di default se il file non esiste o c'è un errore
return new VersionInfo
{
Version = "2.1.0",
CommitSha = "local",
Branch = "dev",
BuildDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
BuildEnvironment = "Local"
};
}
/// <summary>
/// Ottiene le informazioni complete sulla versione
/// </summary>
public VersionInfo GetVersion()
{
return _versionInfo;
}
/// <summary>
/// Ottiene la versione formattata per display nell'UI
/// </summary>
public string GetDisplayVersion()
{
return _versionInfo.GetShortVersion();
}
}
}