[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:
@@ -232,7 +232,8 @@ public class ScheduledJobService : BackgroundService
|
||||
var result = await dataTransferService.ExecuteProfileAsync(
|
||||
schedule.Profile,
|
||||
schedule.SourceDatabaseOverride,
|
||||
schedule.DestinationDatabaseOverride);
|
||||
schedule.DestinationDatabaseOverride,
|
||||
schedule.EnableDeletionSync);
|
||||
|
||||
// Aggiorna lo storico con il risultato
|
||||
executionHistory.EndTime = DateTime.Now;
|
||||
|
||||
@@ -294,13 +294,56 @@
|
||||
<!-- Sezione File -->
|
||||
@if (selectedSourceType == "file")
|
||||
{
|
||||
<div class="alert alert-info" role="alert">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
<strong>Due modalità disponibili:</strong>
|
||||
<ul class="mb-0 mt-2">
|
||||
<li><strong>Caricamento Browser:</strong> Carica un file per preview e configurazione mapping (file temporaneo)</li>
|
||||
<li><strong>Percorso File:</strong> Specifica il percorso completo del file sul server per schedulazioni</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Opzione 1: Caricamento Browser per Preview -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Seleziona File (Excel/CSV):</label>
|
||||
<label class="form-label">
|
||||
<i class="fas fa-upload"></i> Carica File per Preview (opzionale):
|
||||
</label>
|
||||
<InputFile class="form-control" OnChange="OnFileSelected" accept=".xlsx,.xls,.csv" />
|
||||
@if (!string.IsNullOrEmpty(selectedFileName))
|
||||
{
|
||||
<small class="text-muted">File selezionato: @selectedFileName</small>
|
||||
<small class="text-muted">File caricato: @selectedFileName</small>
|
||||
}
|
||||
<small class="form-text text-muted">
|
||||
Carica un file per vedere preview e configurare il mapping. Questo file non verrà salvato.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Opzione 2: Percorso File Manuale (Richiesto per Schedulazione) -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label">
|
||||
<i class="fas fa-folder-open"></i> Percorso File sul Server (richiesto per schedulazione): *
|
||||
</label>
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control" @bind="manualFilePath"
|
||||
placeholder="Es: C:\Data\products.csv o /data/products.csv" />
|
||||
<button class="btn btn-outline-primary" @onclick="ValidateAndLoadFileFromPath"
|
||||
disabled="@(string.IsNullOrEmpty(manualFilePath) || isProcessingFile)">
|
||||
@if (isProcessingFile)
|
||||
{
|
||||
<span class="spinner-border spinner-border-sm me-1"></span>
|
||||
}
|
||||
<i class="fas fa-check"></i> Valida e Carica
|
||||
</button>
|
||||
</div>
|
||||
@if (!string.IsNullOrEmpty(uploadedFilePath) && uploadedFilePath == manualFilePath)
|
||||
{
|
||||
<small class="text-success">
|
||||
<i class="fas fa-check-circle"></i> File validato e caricato con successo!
|
||||
</small>
|
||||
}
|
||||
<small class="form-text text-muted">
|
||||
Inserisci il percorso completo del file. Il file deve essere accessibile dal server.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
@if (isProcessingFile)
|
||||
@@ -1016,7 +1059,7 @@
|
||||
SourceSchema="@GetCurrentDatabaseSchema()"
|
||||
SourceTable="@(useCustomQuery ? "custom_query" : selectedTable)"
|
||||
SourceCustomQuery="@(useCustomQuery ? customQuery : null)"
|
||||
SourceFilePath="@selectedFileName"
|
||||
SourceFilePath="@uploadedFilePath"
|
||||
DestinationType="rest"
|
||||
DestinationCredentialId="@(GetCurrentDestinationCredentialIdAsync().Result)"
|
||||
DestinationCredentialName="@selectedRestCredential"
|
||||
|
||||
@@ -36,6 +36,8 @@ public partial class DataCoupler : ComponentBase
|
||||
|
||||
// File handling
|
||||
private string selectedFileName = "";
|
||||
private string manualFilePath = ""; // Percorso inserito manualmente dall'utente
|
||||
private string uploadedFilePath = ""; // Percorso completo del file validato
|
||||
private bool isProcessingFile = false;
|
||||
private string fileErrorMessage = "";
|
||||
private Dictionary<string, IEnumerable<string>> fileSheets = new(); // SheetName -> Columns
|
||||
@@ -250,8 +252,10 @@ public partial class DataCoupler : ComponentBase
|
||||
// Per i file, non possiamo ricreare il file caricato, ma possiamo impostare le informazioni
|
||||
if (!string.IsNullOrEmpty(profile.SourceFilePath))
|
||||
{
|
||||
uploadedFilePath = profile.SourceFilePath;
|
||||
selectedFileName = Path.GetFileName(profile.SourceFilePath);
|
||||
Logger.LogInformation("Informazioni file impostate: {FileName}", selectedFileName);
|
||||
Logger.LogInformation("Informazioni file impostate - Nome: {FileName}, Percorso: {FilePath}",
|
||||
selectedFileName, uploadedFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,6 +405,37 @@ public partial class DataCoupler : ComponentBase
|
||||
var profileService = new DataCouplerProfileService(null!); // Usa il service di conversione
|
||||
var profile = profileService.FromDto(profileDto, "System"); // TODO: Usa utente corrente
|
||||
|
||||
// Validazione specifica per file CSV
|
||||
if (profile.SourceType == "file" && !string.IsNullOrEmpty(profile.SourceFilePath))
|
||||
{
|
||||
Logger.LogInformation("Validazione file CSV: {FilePath}", profile.SourceFilePath);
|
||||
|
||||
// Verifica che il file esista
|
||||
if (!System.IO.File.Exists(profile.SourceFilePath))
|
||||
{
|
||||
await JSRuntime.InvokeVoidAsync("alert",
|
||||
$"Errore: Il file '{profile.SourceFilePath}' non esiste o non è accessibile. " +
|
||||
"Verifica il percorso del file prima di salvare il profilo.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Verifica che il file sia leggibile
|
||||
try
|
||||
{
|
||||
using var fs = new System.IO.FileStream(profile.SourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
fs.Close();
|
||||
Logger.LogInformation("File CSV validato con successo: {FilePath}", profile.SourceFilePath);
|
||||
}
|
||||
catch (Exception fileEx)
|
||||
{
|
||||
Logger.LogError(fileEx, "Errore nella lettura del file CSV: {FilePath}", profile.SourceFilePath);
|
||||
await JSRuntime.InvokeVoidAsync("alert",
|
||||
$"Errore: Il file '{profile.SourceFilePath}' non può essere letto. " +
|
||||
$"Dettagli: {fileEx.Message}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Controlla se esiste già un profilo con lo stesso nome (inclusi quelli inattivi)
|
||||
Logger.LogInformation("Controllo esistenza profilo con nome: {ProfileName}", profileDto.Name);
|
||||
var existingProfile = await ProfileService.GetProfileByNameIncludingInactiveAsync(profileDto.Name);
|
||||
@@ -685,6 +720,8 @@ public partial class DataCoupler : ComponentBase
|
||||
|
||||
// Reset file state
|
||||
selectedFileName = "";
|
||||
manualFilePath = "";
|
||||
uploadedFilePath = "";
|
||||
isProcessingFile = false;
|
||||
fileErrorMessage = "";
|
||||
fileSheets.Clear();
|
||||
@@ -698,6 +735,213 @@ public partial class DataCoupler : ComponentBase
|
||||
ClearAllMappings();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valida e carica un file dal percorso specificato manualmente
|
||||
/// </summary>
|
||||
private async Task ValidateAndLoadFileFromPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
isProcessingFile = true;
|
||||
fileErrorMessage = "";
|
||||
fileSheets.Clear();
|
||||
fileData.Clear();
|
||||
selectedSheet = "";
|
||||
uploadedFilePath = "";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manualFilePath))
|
||||
{
|
||||
fileErrorMessage = "Inserire il percorso del file";
|
||||
return;
|
||||
}
|
||||
|
||||
// Valida che il file esista
|
||||
if (!System.IO.File.Exists(manualFilePath))
|
||||
{
|
||||
fileErrorMessage = $"Il file '{manualFilePath}' non esiste o non è accessibile";
|
||||
Logger.LogWarning("File non trovato: {FilePath}", manualFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
// Valida estensione
|
||||
var extension = Path.GetExtension(manualFilePath).ToLowerInvariant();
|
||||
if (extension != ".xlsx" && extension != ".xls" && extension != ".csv")
|
||||
{
|
||||
fileErrorMessage = "Formato file non supportato. Utilizzare Excel (.xlsx, .xls) o CSV (.csv)";
|
||||
return;
|
||||
}
|
||||
|
||||
// Verifica che il file sia leggibile
|
||||
try
|
||||
{
|
||||
using var testStream = new System.IO.FileStream(manualFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
testStream.Close();
|
||||
}
|
||||
catch (Exception readEx)
|
||||
{
|
||||
fileErrorMessage = $"Il file non può essere letto: {readEx.Message}";
|
||||
Logger.LogError(readEx, "Errore nella lettura del file: {FilePath}", manualFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("Validazione file completata: {FilePath}", manualFilePath);
|
||||
|
||||
// Carica il file dal percorso per preview
|
||||
selectedFileName = Path.GetFileName(manualFilePath);
|
||||
|
||||
if (extension == ".csv")
|
||||
{
|
||||
await ProcessCsvFileFromPath(manualFilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ProcessExcelFileFromPath(manualFilePath);
|
||||
}
|
||||
|
||||
// Se tutto è andato bene, salva il percorso validato
|
||||
uploadedFilePath = manualFilePath;
|
||||
Logger.LogInformation("File caricato con successo dal percorso: {FilePath}", uploadedFilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Errore nella validazione/caricamento del file dal percorso: {FilePath}", manualFilePath);
|
||||
fileErrorMessage = $"Errore: {ex.Message}";
|
||||
uploadedFilePath = "";
|
||||
}
|
||||
finally
|
||||
{
|
||||
isProcessingFile = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processa un file CSV dal percorso specificato
|
||||
/// </summary>
|
||||
private async Task ProcessCsvFileFromPath(string filePath)
|
||||
{
|
||||
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(stream);
|
||||
|
||||
var firstLine = await reader.ReadLineAsync();
|
||||
if (string.IsNullOrEmpty(firstLine))
|
||||
{
|
||||
fileErrorMessage = "Il file CSV è vuoto";
|
||||
return;
|
||||
}
|
||||
|
||||
var separator = DetectCsvSeparator(firstLine);
|
||||
var headers = ParseCsvLine(firstLine, separator);
|
||||
|
||||
var sheetName = Path.GetFileNameWithoutExtension(filePath);
|
||||
fileSheets[sheetName] = headers;
|
||||
|
||||
var dataRows = new List<Dictionary<string, object>>();
|
||||
string? line;
|
||||
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);
|
||||
}
|
||||
|
||||
fileData[sheetName] = dataRows;
|
||||
selectedSheet = sheetName;
|
||||
|
||||
Logger.LogInformation("File CSV processato: {FilePath}, Headers: {HeaderCount}, Rows: {RowCount}",
|
||||
filePath, headers.Count, dataRows.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processa un file Excel dal percorso specificato
|
||||
/// </summary>
|
||||
private async Task ProcessExcelFileFromPath(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||
|
||||
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
var extension = Path.GetExtension(filePath).ToLowerInvariant();
|
||||
|
||||
IExcelDataReader reader;
|
||||
if (extension == ".xlsx")
|
||||
{
|
||||
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
|
||||
}
|
||||
else if (extension == ".xls")
|
||||
{
|
||||
reader = ExcelReaderFactory.CreateBinaryReader(stream);
|
||||
}
|
||||
else
|
||||
{
|
||||
fileErrorMessage = "Formato Excel non supportato";
|
||||
return;
|
||||
}
|
||||
|
||||
using (reader)
|
||||
{
|
||||
var configuration = new ExcelDataSetConfiguration()
|
||||
{
|
||||
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
|
||||
{
|
||||
UseHeaderRow = true
|
||||
}
|
||||
};
|
||||
|
||||
var dataSet = reader.AsDataSet(configuration);
|
||||
|
||||
foreach (DataTable table in dataSet.Tables)
|
||||
{
|
||||
var sheetName = table.TableName;
|
||||
var headers = new List<string>();
|
||||
var dataRows = new List<Dictionary<string, object>>();
|
||||
|
||||
foreach (DataColumn column in table.Columns)
|
||||
{
|
||||
headers.Add(column.ColumnName);
|
||||
}
|
||||
|
||||
foreach (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);
|
||||
}
|
||||
|
||||
fileSheets[sheetName] = headers;
|
||||
fileData[sheetName] = dataRows;
|
||||
}
|
||||
|
||||
if (fileSheets.Any())
|
||||
{
|
||||
selectedSheet = fileSheets.First().Key;
|
||||
}
|
||||
|
||||
Logger.LogInformation("File Excel processato: {FilePath}, Sheets: {SheetCount}",
|
||||
filePath, dataSet.Tables.Count);
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Errore nel processing del file Excel: {FilePath}", filePath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnFileSelected(InputFileChangeEventArgs e)
|
||||
{
|
||||
try
|
||||
@@ -719,7 +963,9 @@ public partial class DataCoupler : ComponentBase
|
||||
return;
|
||||
}
|
||||
|
||||
// Process file based on type
|
||||
Logger.LogInformation("File caricato per preview: {FileName}", file.Name);
|
||||
|
||||
// Process file based on type (solo per preview, non salva sul server)
|
||||
if (extension == ".csv")
|
||||
{
|
||||
await ProcessCsvFile(file);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<div class="login-container">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<h2>TEST Data Coupler</h2>
|
||||
<h2>Data Coupler</h2>
|
||||
<p>Accedi per continuare</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -174,9 +174,9 @@
|
||||
<option value="0">-- Seleziona Profilo --</option>
|
||||
@if (availableProfiles != null)
|
||||
{
|
||||
@foreach (var profile in availableProfiles.Where(p => p.SourceType != "file"))
|
||||
@foreach (var profile in availableProfiles)
|
||||
{
|
||||
<option value="@profile.Id">@profile.Name</option>
|
||||
<option value="@profile.Id">@profile.Name @(profile.SourceType == "file" ? "(File)" : "")</option>
|
||||
}
|
||||
}
|
||||
</InputSelect>
|
||||
@@ -184,7 +184,8 @@
|
||||
@if (availableProfiles?.Any(p => p.SourceType == "file") == true)
|
||||
{
|
||||
<small class="form-text text-muted">
|
||||
⚠️ I profili con file come sorgente sono esclusi dalle schedulazioni per motivi di sicurezza.
|
||||
ℹ️ I profili con file CSV/Excel come sorgente sono ora supportati per le schedulazioni.
|
||||
Il file specificato nel profilo verrà letto ad ogni esecuzione.
|
||||
</small>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -86,7 +86,8 @@ public partial class Scheduling : ComponentBase
|
||||
IntervalValue = schedule.IntervalValue,
|
||||
IntervalUnit = schedule.IntervalUnit,
|
||||
SourceDatabaseOverride = schedule.SourceDatabaseOverride,
|
||||
DestinationDatabaseOverride = schedule.DestinationDatabaseOverride
|
||||
DestinationDatabaseOverride = schedule.DestinationDatabaseOverride,
|
||||
EnableDeletionSync = schedule.EnableDeletionSync
|
||||
};
|
||||
|
||||
// Imposta il profilo selezionato per mostrare i campi di override
|
||||
@@ -278,7 +279,8 @@ public partial class Scheduling : ComponentBase
|
||||
var result = await DataTransferService.ExecuteProfileAsync(
|
||||
schedule.Profile,
|
||||
schedule.SourceDatabaseOverride,
|
||||
schedule.DestinationDatabaseOverride);
|
||||
schedule.DestinationDatabaseOverride,
|
||||
schedule.EnableDeletionSync);
|
||||
|
||||
// Aggiorna lo storico con il risultato
|
||||
executionHistory.EndTime = DateTime.Now;
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace Data_Coupler.Services;
|
||||
/// </summary>
|
||||
public interface IDataTransferService
|
||||
{
|
||||
Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null);
|
||||
Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null, bool enableDeletionSync = false);
|
||||
}
|
||||
|
||||
public class DataTransferResult
|
||||
@@ -37,7 +37,7 @@ public class DataTransferService : IDataTransferService
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null)
|
||||
public async Task<DataTransferResult> ExecuteProfileAsync(DataCouplerProfile profile, string? sourceDatabaseOverride = null, string? destinationDatabaseOverride = null, bool enableDeletionSync = false)
|
||||
{
|
||||
var result = new DataTransferResult
|
||||
{
|
||||
@@ -59,21 +59,11 @@ public class DataTransferService : IDataTransferService
|
||||
return result;
|
||||
}
|
||||
|
||||
// Controlla se il profilo ha file come sorgente e blocca l'esecuzione
|
||||
if (profile.SourceType?.ToLower() == "file")
|
||||
{
|
||||
result.IsSuccess = false;
|
||||
result.ErrorMessage = "I profili con file come sorgente non sono supportati nelle schedulazioni per motivi di sicurezza.";
|
||||
result.EndTime = DateTime.Now; // Usa l'ora locale per coerenza
|
||||
_logger.LogWarning("Tentativo di esecuzione di profilo con file come sorgente bloccato: {ProfileName}", profile.Name);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Applica override del database se specificati
|
||||
var profileToExecute = await ApplyDatabaseOverrides(profile, sourceDatabaseOverride, destinationDatabaseOverride);
|
||||
|
||||
// Utilizza il servizio esistente per l'esecuzione
|
||||
var executionResult = await _scheduledExecutionService.ExecuteProfileAsync(profileToExecute.Id);
|
||||
var executionResult = await _scheduledExecutionService.ExecuteProfileAsync(profileToExecute.Id, enableDeletionSync);
|
||||
|
||||
result.IsSuccess = executionResult.Success;
|
||||
result.RecordsProcessed = executionResult.RecordsProcessed;
|
||||
@@ -175,7 +165,8 @@ public class DataTransferService : IDataTransferService
|
||||
if (string.IsNullOrEmpty(profile.DestinationType))
|
||||
return (false, "Tipo destinazione non specificato");
|
||||
|
||||
if (!profile.SourceCredentialId.HasValue)
|
||||
// Per le sorgenti file, la credenziale non è richiesta
|
||||
if (profile.SourceType != "file" && !profile.SourceCredentialId.HasValue)
|
||||
return (false, "Credenziale sorgente non specificata");
|
||||
|
||||
if (!profile.DestinationCredentialId.HasValue)
|
||||
|
||||
@@ -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