public async Task <ActionResult <HttpResponseMessage> > CaricaSmarriti() { var connectionString = RepositoryContext.ConnectionString; var isError = false; var exMessage = String.Empty; var isXlsFiles = IsDocumentUploaded(_uploadFolder, out string[] xlsFiles); _logger.LogInformation("Controller started!"); if (!isXlsFiles) { return(BadRequest("Nessun file excel caricato!")); } try { foreach (var excelfile in _dictFile.DictionaryOfFiles.Values) { var filenamepath = _uploadFolder + @"\" + excelfile; // add upload folder to path of filename await Task.Run(() => _outputNames.Add(OpenDocument(filenamepath, connectionString))); _logger.LogInformation("open excel document"); } _logger.LogInformation("Reading ended."); } catch (Exception ex) { _logger.LogInformation("Exception : " + ex.Message); isError = true; exMessage = ex.Message; } finally { if (isError) { // build filename append guid to end of filename to have unique name var fileName = "log_error_" + DateTime.Now.ToString("yyyy-MM-dd") + "_" + DateTime.Now.ToString("HH.mm.ss_") + Guid.NewGuid() + ".txt"; _outputNames.Add(fileName); ReportFile.InitFile(fileName); ReportFile.WriteLine("Problemi durante il caricamento dei codici"); ReportFile.WriteLine(exMessage); ReportFile.CloseFile(); CopyLogErrorFile2SharedFolder(fileName); } } // return all filename generated included file of errors if (isError) { isError = false; return(BadRequest("Problema durante la lettura del/i file di codici!")); } // Serialize text file to json var result = ConvertToFileContentResult(_outputNames); return(result); }
// Read xls file private string OpenDocument(string fileName, string connectionString) { // hardcoded max lenght for file and path in windows because not easy to retrieve this limit from .net const int maxPathLenght = 255; // source filename // Open a document based on a filepath in read only mode var extension = Path.GetExtension(fileName).ToLower(); var pathReportFile = new StringBuilder(_configuration["PathReportFile"]).Append(@"\").Append(_lostFolder).Append(@"\"); //.Append(Path.GetFileName(fileName)).Append("-SCARTI_LOAD.TXT"); // Create folder 'smarriti' if not exist Directory.CreateDirectory(pathReportFile.ToString()); // Append final //var filenameWithOutcomesLoad= Path.GetFileName(fileName)).Append("-SCARTI_LOAD_").Append( Guid.NewGuid().ToString("N"); pathReportFile.Append(Path.GetFileName(fileName)).Append("-SCARTI_LOAD_").Append((Guid.NewGuid().ToString("N"))).Append(".TXT"); if (pathReportFile.Length > maxPathLenght) // truncate filename if own lenght is over the max path lenght of OS { pathReportFile = new StringBuilder(pathReportFile.ToString().Substring(0, maxPathLenght)).Append(".txt"); } // Open for write file esitati ReportFile.InitFile(pathReportFile.ToString()); // fileEsistati =Helper.WriteReportFile(pathReportFile); string reportFileName = Path.GetFileName(pathReportFile.ToString()); using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { IExcelDataReader reader = null; switch (extension) // *** optional manage more extension than xls { case ".xls": reader = ExcelReaderFactory.CreateBinaryReader(stream); break; //case ".xlsx": // reader = ExcelReaderFactory.CreateOpenXmlReader(stream); // break; //case ".csv": // reader = ExcelReaderFactory.CreateCsvReader(stream); // break; default: break; } if (reader == null) { return(reportFileName); } _logger.LogInformation("Try to parse document"); ParseDocument(connectionString, reader, fileName, _logger); _logger.LogInformation("Copy document in sharedFolder"); } // end using return(reportFileName); }
public IActionResult AggiornaRacc() { var isError = false; var nomefileErr = String.Empty; try { _logger.LogInformation("Controller update data started!"); long cons = 0; var today = DateTime.Now.ToString("yyyy-MM-dd"); if (!Directory.Exists(_outputFolder)) { _logger.LogInformation("create directory " + _outputFolder); Directory.CreateDirectory(_outputFolder); } var outputFileName = DateTime.Now.ToString("yyyy-MM-dd") + "-SCARTI_UPDATE_" + DateTime.Now.ToString("hh.mm.ss") + ".txt"; var outcomesFilename = Path.Combine(_outputFolder, _lostFolder) + @"\" + outputFileName; //esegue stored prodecedure _logger.LogInformation("execute stored procedure: SP_aggiorna_esa_racc"); var updatedRecords = new DAL.StoredProcedure.SP_aggiorna_esa_racc(RepositoryContext); long itemsUpdated = updatedRecords.Set(today); cons += itemsUpdated; //controlla se esistono esiti scartati per data non corretta _logger.LogInformation("execute stored procedure: SP_controlla_esiti_scartati"); var esitiScartati = new RAR.DAL.StoredProcedure.SP_controlla_esiti_scartati(RepositoryContext); long scarti = esitiScartati.Get(today).Result.Count(); ReportFile.InitFile(outcomesFilename); _logger.LogInformation("create end write file: " + outcomesFilename); if (scarti != 0) { foreach (var rowScartati in esitiScartati.Get(today).Result) { ReportFile.WriteLine(rowScartati.CodiceInvio + " - " + $"{rowScartati.DataDenuncia:yyyy-MM-dd}" + " - NOTIFICA ERRATA"); } } //scrive il riepilogo ReportFile.WriteLine(""); ReportFile.WriteLine(""); ReportFile.WriteLine(cons + " esiti aggiornati"); ReportFile.WriteLine(scarti + " scartati"); ReportFile.CloseFile(); _logger.LogInformation("Esiti recuperati correttamente"); //return Content(JsonConvert.SerializeObject(new { messaggio = "Esiti recuperati correttamente", avviso = "Creati files di riepilogo in " + _outputFolder })); CopyOutcomesFile2SharedFolder(outcomesFilename, outputFileName); if (Directory.Exists(@"\\" + _sharedOutputFolder)) { return(Content(new String("Esiti recuperati correttamente.\n Creati files di riepilogo in : " + _sharedOutputFolder))); } else { return(Content(new String("Esiti recuperati correttamente.\n Creati files di riepilogo."))); } } catch (Exception ex) { _logger.LogError("Problemi durante l'aggiornamento degli esiti"); _logger.LogError(ex.Message); isError = true; nomefileErr = "log_error_" + DateTime.Now.ToString("yyyy-MM-dd") + "_" + DateTime.Now.ToString("hh.mm.ss") + ".txt"; ReportFile.InitFile(nomefileErr); ReportFile.WriteLine("Problemi durante l'aggiornamento degli esiti"); ReportFile.WriteLine(ex.Message); ReportFile.WriteLine(ex.Source); ReportFile.CloseFile(); return(BadRequest("Problemi durante l'aggiornamento degli esiti. Impossibile proseguire.")); } finally { if (isError) { CopyLogErrorFile2SharedFolder(nomefileErr); } } }