[Feature] Implementata schedulazione completa per file CSV/Excel
- Aggiunta validazione percorsi file prima del salvataggio profili - Implementati metodi di lettura file CSV e Excel per schedulazioni - Supporto doppia modalità: caricamento browser (preview) e percorso manuale (schedulazione) - Gestione completa deletion sync anche per file CSV/Excel - Rilevamento automatico separatori CSV (virgola, punto e virgola, tab, pipe) - Supporto formati Excel legacy (.xls) e moderni (.xlsx) - Abilitati profili file nella UI di schedulazione - Logging dettagliato per troubleshooting - Documentazione completa in CSV_SCHEDULING_IMPLEMENTATION.md - Aggiornati README.md e copilot-instructions.md con nuove feature - Rimosso testo 'TEST' dalla pagina di login
This commit was merged in pull request #5.
This commit is contained in:
@@ -13,6 +13,7 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using Data_Coupler.Models;
|
||||
using Data_Coupler.Services;
|
||||
using ExcelDataReader;
|
||||
|
||||
namespace Data_Coupler.Services;
|
||||
|
||||
@@ -130,9 +131,15 @@ public class ScheduledProfileExecutionService : IScheduledProfileExecutionServic
|
||||
var (restClient, restCredential, restEntity) = await SetupDestinationConnectionAsync(profile);
|
||||
|
||||
// 2. Verifica che le connessioni siano valide
|
||||
if (sourceManager == null)
|
||||
// Per i file, sourceManager sarà null (è normale), per database deve essere presente
|
||||
if (profile.SourceType.ToLower() == "database" && sourceManager == null)
|
||||
{
|
||||
throw new InvalidOperationException("Impossibile stabilire connessione con la sorgente dati");
|
||||
throw new InvalidOperationException("Impossibile stabilire connessione con il database sorgente");
|
||||
}
|
||||
|
||||
if (profile.SourceType.ToLower() == "file" && string.IsNullOrEmpty(profile.SourceFilePath))
|
||||
{
|
||||
throw new InvalidOperationException("Percorso file sorgente non specificato nel profilo");
|
||||
}
|
||||
|
||||
if (restClient == null || restEntity == null)
|
||||
@@ -187,11 +194,18 @@ public class ScheduledProfileExecutionService : IScheduledProfileExecutionServic
|
||||
/// </summary>
|
||||
private async Task<(IDatabaseManager? manager, DatabaseCredential? credential)> SetupSourceConnectionAsync(DataCouplerProfile profile)
|
||||
{
|
||||
if (profile.SourceType.ToLower() != "database")
|
||||
_logger.LogInformation("SetupSourceConnectionAsync - SourceType: '{SourceType}', SourceCredentialId: {SourceCredentialId}, SourceFilePath: '{SourceFilePath}'",
|
||||
profile.SourceType, profile.SourceCredentialId, profile.SourceFilePath);
|
||||
|
||||
// Se la sorgente è un file, non servono credenziali database
|
||||
if (string.IsNullOrEmpty(profile.SourceType) ||
|
||||
profile.SourceType.Equals("file", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return (null, null); // Per i file gestiremo diversamente
|
||||
_logger.LogInformation("Sorgente tipo file, nessuna connessione database necessaria");
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
// Per database, la credenziale è obbligatoria
|
||||
if (!profile.SourceCredentialId.HasValue)
|
||||
{
|
||||
throw new InvalidOperationException("Credenziale sorgente non specificata per il database");
|
||||
@@ -378,18 +392,233 @@ public class ScheduledProfileExecutionService : IScheduledProfileExecutionServic
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ottiene tutti i record da file (implementazione future)
|
||||
/// Ottiene tutti i record da file CSV o Excel
|
||||
/// </summary>
|
||||
private async Task<IEnumerable<Dictionary<string, object>>> GetAllRecordsFromFileAsync(DataCouplerProfile profile)
|
||||
{
|
||||
if (string.IsNullOrEmpty(profile.SourceFilePath))
|
||||
throw new InvalidOperationException("Percorso file sorgente non specificato");
|
||||
|
||||
// TODO: Implementazione per file Excel/CSV per le schedulazioni
|
||||
// Per ora restituiamo una lista vuota
|
||||
_logger.LogWarning("Lettura file non ancora implementata per le schedulazioni. File: {FilePath}", profile.SourceFilePath);
|
||||
await Task.Delay(1); // Placeholder async
|
||||
return new List<Dictionary<string, object>>();
|
||||
if (!System.IO.File.Exists(profile.SourceFilePath))
|
||||
throw new FileNotFoundException($"Il file '{profile.SourceFilePath}' non esiste");
|
||||
|
||||
var extension = System.IO.Path.GetExtension(profile.SourceFilePath).ToLowerInvariant();
|
||||
|
||||
_logger.LogInformation("Lettura file sorgente: {FilePath} (Tipo: {Extension})", profile.SourceFilePath, extension);
|
||||
|
||||
if (extension == ".csv")
|
||||
{
|
||||
return await ReadCsvFileAsync(profile.SourceFilePath);
|
||||
}
|
||||
else if (extension == ".xlsx" || extension == ".xls")
|
||||
{
|
||||
return await ReadExcelFileAsync(profile.SourceFilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException($"Formato file non supportato: {extension}. Utilizzare .csv, .xlsx o .xls");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Legge un file CSV e restituisce i record come dizionari
|
||||
/// </summary>
|
||||
private async Task<IEnumerable<Dictionary<string, object>>> ReadCsvFileAsync(string filePath)
|
||||
{
|
||||
var dataRows = new List<Dictionary<string, object>>();
|
||||
|
||||
try
|
||||
{
|
||||
// Apri in modalità condivisa per permettere ad altri processi di accedere al file
|
||||
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
using var reader = new System.IO.StreamReader(stream);
|
||||
|
||||
var firstLine = await reader.ReadLineAsync();
|
||||
if (string.IsNullOrEmpty(firstLine))
|
||||
{
|
||||
_logger.LogWarning("Il file CSV è vuoto: {FilePath}", filePath);
|
||||
return dataRows;
|
||||
}
|
||||
|
||||
// Detect separator automatically
|
||||
var separator = DetectCsvSeparator(firstLine);
|
||||
_logger.LogDebug("CSV separator rilevato: '{Separator}'", separator);
|
||||
|
||||
// Parse headers (first row)
|
||||
var headers = ParseCsvLine(firstLine, separator);
|
||||
_logger.LogInformation("CSV headers: {Headers} (Totale: {Count})", string.Join(", ", headers), headers.Count);
|
||||
|
||||
// Read data rows
|
||||
string? line;
|
||||
int rowNumber = 2;
|
||||
|
||||
while ((line = await reader.ReadLineAsync()) != null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||
|
||||
var values = ParseCsvLine(line, separator);
|
||||
var row = new Dictionary<string, object>();
|
||||
|
||||
for (int i = 0; i < headers.Count; i++)
|
||||
{
|
||||
var value = i < values.Count ? values[i] : "";
|
||||
row[headers[i]] = string.IsNullOrEmpty(value) ? "" : value;
|
||||
}
|
||||
|
||||
dataRows.Add(row);
|
||||
rowNumber++;
|
||||
}
|
||||
|
||||
_logger.LogInformation("File CSV letto con successo: {FilePath}, Record: {RecordCount}", filePath, dataRows.Count);
|
||||
return dataRows;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Errore nella lettura del file CSV: {FilePath}", filePath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Legge un file Excel e restituisce i record come dizionari
|
||||
/// </summary>
|
||||
private async Task<IEnumerable<Dictionary<string, object>>> ReadExcelFileAsync(string filePath)
|
||||
{
|
||||
var dataRows = new List<Dictionary<string, object>>();
|
||||
|
||||
try
|
||||
{
|
||||
// Registra il provider di encoding per ExcelDataReader
|
||||
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||
|
||||
// Apri in modalità condivisa per permettere ad altri processi di accedere al file
|
||||
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
var extension = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
|
||||
|
||||
ExcelDataReader.IExcelDataReader reader;
|
||||
if (extension == ".xlsx")
|
||||
{
|
||||
reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(stream);
|
||||
}
|
||||
else if (extension == ".xls")
|
||||
{
|
||||
reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(stream);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException($"Formato Excel non supportato: {extension}");
|
||||
}
|
||||
|
||||
using (reader)
|
||||
{
|
||||
var configuration = new ExcelDataReader.ExcelDataSetConfiguration()
|
||||
{
|
||||
ConfigureDataTable = (_) => new ExcelDataReader.ExcelDataTableConfiguration()
|
||||
{
|
||||
UseHeaderRow = true
|
||||
}
|
||||
};
|
||||
|
||||
var dataSet = reader.AsDataSet(configuration);
|
||||
_logger.LogInformation("File Excel letto: {FilePath}, Fogli: {SheetCount}", filePath, dataSet.Tables.Count);
|
||||
|
||||
// Legge il primo foglio (o tutti i fogli se necessario)
|
||||
if (dataSet.Tables.Count > 0)
|
||||
{
|
||||
var table = dataSet.Tables[0];
|
||||
var headers = new List<string>();
|
||||
|
||||
foreach (System.Data.DataColumn column in table.Columns)
|
||||
{
|
||||
headers.Add(column.ColumnName);
|
||||
}
|
||||
|
||||
foreach (System.Data.DataRow dataRow in table.Rows)
|
||||
{
|
||||
var row = new Dictionary<string, object>();
|
||||
foreach (var header in headers)
|
||||
{
|
||||
var value = dataRow[header];
|
||||
row[header] = value == DBNull.Value ? "" : value?.ToString() ?? "";
|
||||
}
|
||||
dataRows.Add(row);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Foglio Excel '{SheetName}' letto con successo: {RecordCount} record",
|
||||
table.TableName, dataRows.Count);
|
||||
}
|
||||
}
|
||||
|
||||
await Task.CompletedTask; // Per mantenere il metodo async
|
||||
return dataRows;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Errore nella lettura del file Excel: {FilePath}", filePath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rileva automaticamente il separatore CSV
|
||||
/// </summary>
|
||||
private char DetectCsvSeparator(string line)
|
||||
{
|
||||
var separators = new[] { ',', ';', '\t', '|' };
|
||||
var maxCount = 0;
|
||||
var detectedSeparator = ',';
|
||||
|
||||
foreach (var sep in separators)
|
||||
{
|
||||
var count = line.Count(c => c == sep);
|
||||
if (count > maxCount)
|
||||
{
|
||||
maxCount = count;
|
||||
detectedSeparator = sep;
|
||||
}
|
||||
}
|
||||
|
||||
return detectedSeparator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parse di una riga CSV gestendo correttamente le virgolette
|
||||
/// </summary>
|
||||
private List<string> ParseCsvLine(string line, char separator = ',')
|
||||
{
|
||||
var result = new List<string>();
|
||||
var current = new System.Text.StringBuilder();
|
||||
bool inQuotes = false;
|
||||
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
{
|
||||
char c = line[i];
|
||||
|
||||
if (c == '"')
|
||||
{
|
||||
if (inQuotes && i + 1 < line.Length && line[i + 1] == '"')
|
||||
{
|
||||
current.Append('"');
|
||||
i++;
|
||||
}
|
||||
else
|
||||
{
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
}
|
||||
else if (c == separator && !inQuotes)
|
||||
{
|
||||
result.Add(current.ToString().Trim());
|
||||
current.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
current.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
result.Add(current.ToString().Trim());
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user