2025-04-15 12:10:19 +02:00

1659 lines
73 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Collections;
using System.Net;
using System.Globalization;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;
using System.Collections.ObjectModel;
using System.Windows;
using DataAccessLayer;
using System.Linq;
using SmartFTP.Logic;
namespace SmartZip.Logic
{
public class ZipProcessSeparated
{
ZipConfiguration myConfig;
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private ObservableCollection<ZipItem> zipPackages;
string approvalSuffix;
string suffixApp;
string suffixNoApp;
bool approval;
bool ftp;
private int scenarioID;
public int IsUltimoZip { get; set; }
public string IDZIP { get; set; }
private void SetupLogFile(string logFileName)
{
NotificationFile = logFileName;
if (!File.Exists(NotificationFile))
{
var z = File.Create(NotificationFile);
z.Close();
}
}
public bool isPdfProcessFinished()
{
//we hope to find C6MartPeriodico.SP_TotaliReportGenerazioneZip here
string procedureName = ConfigurationManager.AppSettings["isGestorePdfStillRunningProcedure"];
List<Parametro> parametri = new List<Parametro>()
{
new Parametro(){
Value = 1, //1 is fine... we just need to find out if at least 1 is still pending
ParameterName = "reportPerZip"
}
};
//running reader
IDataReader r = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, procedureName, parametri);
if (r == null) return false; //error? lets stop the process
if (r.Read()) //if there is a record as expected
{
string x = r["isUltimoZip"].ToString();
string l = r["totReportGenerati"].ToString();
return ((r["isUltimoZip"].ToString() == "2" || r["isUltimoZip"].ToString() == "1") && r["totReportGenerati"].ToString() == "0"); //hope it's clear
}
return false; //if something goes wrong return false and stop the process
}
public static ZipConfiguration ReadConfigurationFromConfig()
{
return ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
}
public ZipProcessSeparated(string logFileName, ObservableCollection<ZipItem> zipPackages = null, string _approvalSuffix = null, string _suffixApp = null, string _suffixNoApp = null, bool _approval = false, int scenarioID = 0)
{
IDZIP = null;
IsUltimoZip = -1;
approvalSuffix = _approvalSuffix;
suffixApp = _suffixApp;
approval = _approval;
suffixNoApp = _suffixNoApp;
SetupLogFile(logFileName);
ftp = bool.Parse(ConfigurationManager.AppSettings["FTP"]);
myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
this.scenarioID = scenarioID;
this.zipPackages = zipPackages;
}
public ZipProcessSeparated(string logFileName, ZipConfiguration customConfig)
{
SetupLogFile(logFileName);
myConfig = customConfig;
}
public string NotificationFile { get; set; }
public void cPushNotification(string message)
{
var f = File.AppendText(NotificationFile);
message = "[" + DateTime.Now.ToLongTimeString() + "]" + message;
f.WriteLine(message);
f.Close();
try
{
logger.Debug(String.Concat("Zip Process:", message));
}
catch { }
Console.WriteLine(message);
}
//20180726 Non serve più, il controllo è stato spostato nell'AppViewModel
//20180725 Inserito controllo sulle tabelle degli stati dei report
//private DataTable ControlloTotaliGenerazioneZipTable(int numeroCfPerZip, int isLotto1 = 0)
//{
// List<Parametro> parametri = new List<Parametro>();
// Parametro parametro = new Parametro();
// parametro.DbType = DbType.Int32;
// parametro.ParameterName = "@reportPerZip";
// parametro.Value = numeroCfPerZip;
// parametri.Add(parametro);
// parametro = new Parametro();
// parametro.DbType = DbType.Int32;
// parametro.ParameterName = "@isLotto1";
// parametro.Value = isLotto1;
// parametri.Add(parametro);
// //20180725 da inserire nel config?
// string nomeStoredProcedure = "C6MartPeriodico.SP_PreTotaliReportGenerazioneZip";
// var result = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerStampeC6, nomeStoredProcedure, parametri);
// cPushNotification("TotaliGenerazioneZipTable received with " + result.Rows.Count.ToString());
// return result;
//}
//--20180725
//--20180726
private DataTable GetTotaliGenerazioneZipTable(int numeroCfPerZip, int isLotto1 = 0)
{
List<Parametro> parametri = new List<Parametro>();
Parametro parametro = new Parametro();
parametro.DbType = DbType.Int32;
parametro.ParameterName = "@reportPerZip";
parametro.Value = numeroCfPerZip;
parametri.Add(parametro);
parametro = new Parametro();
parametro.DbType = DbType.Int32;
parametro.ParameterName = "@isLotto1";
parametro.Value = isLotto1;
parametri.Add(parametro);
string nomeStoredProcedure = myConfig.TotaliReportGenerazioneZip;
var result = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerStampeC6, nomeStoredProcedure, parametri);
cPushNotification("TotaliGenerazioneZipTable received with " + result.Rows.Count.ToString());
return result;
}
private int FissareNumeroCfPerZipSeNecessario(int numeroCfPerZip, string tipoInvio)
{
IDataReader LastZip = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_SELECT_LAST_ZIP, null);
LastZip.Read();
var d_count = LastZip.FieldCount;
var d_val = LastZip.ToString();
if (LastZip["IdZip"].ToString() != "-1")
{
string _path = (tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : myConfig.pathZIP_PERIODICO;
string dirNomeCartella = _path + LastZip["NomeCartella"].ToString() + "_" + LastZip["IdZip"].ToString();
if (!Directory.Exists(dirNomeCartella))
Directory.CreateDirectory(dirNomeCartella);
// cancella file
string[] NumeroFile = Directory.GetFiles(dirNomeCartella);
//
int numeroCFUltimoZipElaborato = Convert.ToInt32(LastZip["NumeroCFZip"].ToString());
if (numeroCFUltimoZipElaborato == 0 && NumeroFile.Length > 0)
{
ripristinaFileRipartenza(NumeroFile);
}
cPushNotification("*** RIPRESA INTERRUZIONE ULTIMO ZIP ***" + numeroCfPerZip);
cPushNotification("NumeroFileNellaCartella: " + NumeroFile.Length);
cPushNotification("NumeroClientiNellaCartella: " + numeroCFUltimoZipElaborato);
cPushNotification("numeroCfPerZip: " + numeroCfPerZip);
if (numeroCFUltimoZipElaborato < numeroCfPerZip)
{
numeroCfPerZip = numeroCfPerZip - numeroCFUltimoZipElaborato;
if (numeroCFUltimoZipElaborato != 0)
MessageBox.Show(numeroCFUltimoZipElaborato.ToString() + " " + myConfig.SP_GESTIONE_SELECT_LAST_ZIP);
}
}
cPushNotification("NumeroCfPerZip " + numeroCfPerZip.ToString());
return numeroCfPerZip;
}
private List<List<ReportDaProcessare>> ProdurreZipDaProcessare(int numeroCfPerZip, DataTable pdfRead)
{
logger.Debug("cccc");
List<List<ReportDaProcessare>> risultato = new List<List<ReportDaProcessare>>();
List<ReportDaProcessare> reportsDaProcessare = new List<ReportDaProcessare>();
//int contatoreCf = 0;
string ultimoCf = string.Empty;
int nTotRead = 0;
nTotRead = pdfRead.Rows.Count;
foreach (DataRow pdfRow in pdfRead.Rows)
{
if (ultimoCf != pdfRow["CodiceFiscale"].ToString())
{
if (reportsDaProcessare.Count() < numeroCfPerZip)
{
//contatoreCf++;
reportsDaProcessare.Add(new ReportDaProcessare((int)pdfRow["IdReport"], pdfRow["NomeFile"].ToString(), pdfRow["TipoReport"].ToString(), pdfRow["nomeFileLocale"].ToString()));
}
else
{
//contatoreCf = 0;
risultato.Add(reportsDaProcessare);
reportsDaProcessare = new List<ReportDaProcessare>();
reportsDaProcessare.Add(new ReportDaProcessare((int)pdfRow["IdReport"], pdfRow["NomeFile"].ToString(), pdfRow["TipoReport"].ToString(), pdfRow["nomeFileLocale"].ToString()));
}
}
else
reportsDaProcessare.Add(new ReportDaProcessare((int)pdfRow["IdReport"], pdfRow["NomeFile"].ToString(), pdfRow["TipoReport"].ToString(), pdfRow["nomeFileLocale"].ToString()));
ultimoCf = pdfRow["CodiceFiscale"].ToString();
}
//V aggiungo l'ultima lista alla lista degli zip, solo nel caso la lista abbia almeno un elemento
if (reportsDaProcessare.Count > 0)
risultato.Add(reportsDaProcessare);
else
cPushNotification("Nessun Pdf da elaborare");
cPushNotification("Risultato done " + risultato.Count.ToString());
return risultato;
}
public int ProcessZip(bool onlyFullPacks, string IdElaborazioneZip = "", string approvalID = null, int sleepInterval = 0, bool sleppAtStart = true, bool wasApprovalFileSend = false, int isLotto1 = 0)
{
string tipoInvio = myConfig.TIPO_INVIO;
string zipFolder = (tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : myConfig.pathZIP_PERIODICO;
int numeroCfPerZip = int.Parse(myConfig.numeroCfPerZip); //920 if(exec ..getzipfrom
//20180726 Controllo spostato prima ancora di lanciare il processo di zipping (in AppViewModel)
//20180725 Inserito controllo sulle tabelle degli stati dei report
//DataTable dtControlloTotaliGenerazioneZip = ControlloTotaliGenerazioneZipTable(numeroCfPerZip, isLotto1);
//if (dtControlloTotaliGenerazioneZip.Rows[0].Field<int>("Esito").ToString().Equals("0"))
//{
// MessageBox.Show(string.Format("Il controllo ha restituito il seguente errore:\n{0}\nProcedura di Zip non eseguibile.", dtControlloTotaliGenerazioneZip.Rows[0].Field<string>("Err")));
// return -1;
//}
//--20180725
//20180726
if (approvalID != "0" && approvalID != "" && wasApprovalFileSend)// && ( isLotto1 == 1 || scenarioID == 0))
{
MessageBoxResult res = MessageBox.Show("Approval file was already send (" + approvalID + ") do you wish to continue sending files by ftp? Press Cancel to stop the process. No will continue zipping process without sending any files.", "Warning", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
if (res == MessageBoxResult.No)
ftp = false;
else if (res == MessageBoxResult.Cancel)
{
if (MessageBox.Show("Do you want to reset settings also?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
ConfigurationManager.AppSettings["WasApprovalFileSent"] = "false";
ConfigurationManager.AppSettings["approvalFileId"] = "";
ConfigurationManager.AppSettings["idFkZip"] = "-1";
}
return -1;
}
// if(res == MessageBoxResult.Yes)
// {
//
// ConfigurationManager.AppSettings["WasApprovalFileSent"] = "false";
// ConfigurationManager.AppSettings["approvalFileId"] = "";
//
// approvalID = null;
// wasApprovalFileSend = false;
// return 0;
// }
}
int result = 0;
while (!isPdfProcessFinished())
{
if (sleppAtStart) Thread.Sleep(sleepInterval);
cPushNotification("Processing zip");
//elimino il proxy
IWebProxy proxy = WebRequest.GetSystemWebProxy();
WebRequest.DefaultWebProxy = null;
cPushNotification("starting");
try
{
int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]);
string type = (useZ == 1) ? ".7z" : ".zip";
int verificationResult = 1;
// ToDo
//bool ftp = bool.Parse(ConfigurationManager.AppSettings["FTP"]);
// FC 28012015 Gestione Parallelizzazione dei processi
#region LetturaTotaliGenerazioneZip
DataTable dtTotaliGenerazioneZip = GetTotaliGenerazioneZipTable(numeroCfPerZip, isLotto1);
#endregion
#region PresenzaTotali
if (dtTotaliGenerazioneZip.Rows.Count == 0) return -1;
if (dtTotaliGenerazioneZip.Rows[0][1].ToString() != "2")
this.scenarioID = 3;
#region gestione ripartenza zip
//Insert Elaborazione Zip
string nomeStoredProcedure = myConfig.SP_GESTIONE_SELECT_FTP_DA_INVIARE;
DataTable pdfRead = null;
logger.Debug("ccccd");
List<Parametro> l = new List<Parametro>();
l.Add(new Parametro() { ParameterName = "isLotto1", Value = isLotto1 });
pdfRead = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerStampeC6, nomeStoredProcedure, l);
// New SP num cf
numeroCfPerZip = FissareNumeroCfPerZipSeNecessario(numeroCfPerZip, tipoInvio);
#endregion gestione ripartenza
#region Esecuzione Zip
//Dati per Verifiche per esecuzione Generazione Zip
DataRow drTotaliReport = dtTotaliGenerazioneZip.Rows[0];
int nReportDisponibili = Convert.ToInt32(drTotaliReport["totReportGenerati"]);
int isUltimoZip = Convert.ToInt32(drTotaliReport["isUltimoZip"]);
this.IsUltimoZip = isUltimoZip;
//V Crea una lista di liste di report da processare, ogni lista rappresenta uno ZIP
List<List<ReportDaProcessare>> zipDaProcessare = ProdurreZipDaProcessare(numeroCfPerZip, pdfRead);
// string idzip = "0";
string pathPdf = ConfigurationManager.AppSettings["pathZIP_PERIODICO"];
int filesCount = new DirectoryInfo(pathPdf).GetFiles().Count();
if (zipDaProcessare.Count > 0 && filesCount > 0)
{
string IDElaborazioneZip = (IdElaborazioneZip == "") ? InizioElaborazioneZip() : IdElaborazioneZip;
cPushNotification("INIZIO elaborazione ZIP");
cPushNotification("IDElaborazioneZip: " + IDElaborazioneZip);
logger.Debug("zipDaProcessare>0");
foreach (List<ReportDaProcessare> lrp in zipDaProcessare)
{
string _suffix = (approval) ? ((isUltimoZip == 2) ? approvalSuffix : suffixNoApp) : suffixApp;
logger.Debug(_suffix + " " + approval.ToString() + " " + isUltimoZip.ToString());
cPushNotification("Number of ReportDaProcessare in element " + lrp.Count.ToString());
QueryGestioneInsertZip dati = getInfoZip(getZipName(), zipFolder, IDElaborazioneZip, approvalID, _suffix, isUltimoZip);//,k);
logger.Debug(dati.nomeCartella);
CreateDir(dati.nomeCartella);
//Lettura File Da DB
//FC Todo Sotituito con lettura da cartella
// if (this.scenarioID != 1 || dati.suffix == ConfigurationManager.AppSettings["SuffixApproval"].ToString())
// {
//ToDo FC
SmartFTP m = new SmartFTP(lrp, dati.nomeCartella, drTotaliReport, null, null, null);
// Copia dei file pdf nella cartella zip appena creata
Boolean bCreaZip = m.CopiaInCartellaToZip(numeroCfPerZip);
m.aggiornaReportDB(dati.IdZip);
List<ReportDaProcessare> reportInZipForlder = m.getListaReport();
// richiamo Sp per aggionamento flag in Gestione PDF FTP
IDZIP = dati.IdZip.ToString();
if (bCreaZip)
{
cPushNotification("INIZIO " + DateTime.Now + " creazione ZIP nome file: " + dati.nomeFile + " in corso...");
//ZipIt(dati.nomeCartella, dati.nomeFile);
ZipIt(dati);
if (this.scenarioID == 1)
{
logger.Debug("verifier started");
IDXVerificator id = new IDXVerificator();
string fileName = fullFileName(dati.fileName);
string mes = string.Empty;
verificationResult = id.Execute(fileName, true, out mes);
logger.Debug("verifier result: " + verificationResult.ToString());
if (verificationResult < 0)
{
MessageBox.Show(string.Concat("Attention, the file ", dati.fileName, " is invalid"));
return -4;
//if (verificationResult == 3)
//{
// if (MessageBox.Show("Attention, the file is empty. Do you really want to send it?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.No)
// {
// return -4;
// }
//}
}
}
else
{
bool disableVerification = bool.Parse(ConfigurationManager.AppSettings["DisableIDXVerification"]);
if (!disableVerification)
{
logger.Debug("verifier started");
IDXVerificator id = new IDXVerificator();
string fileName = fullFileName(dati.fileName);
string mes = string.Empty;
verificationResult = id.Execute(fileName, true, out mes);
logger.Debug("verifier result: " + verificationResult.ToString());
if (verificationResult < 0)
{
logger.Error(mes);
return -4;
}
if (verificationResult == 3)
{
logger.Error("Attention, the file is empty.");
return -3;
}
}
}
bool doNotCloseElaborazione = false;
string folderName = ConfigurationManager.AppSettings["path_OUTPUT_ZIP_PERIODICO"].ToString();
this.SendFTP(folderName, string.Concat(dati.nomeFile, "[", dati.suffix, "]"), dati.IdZip, type, scenarioID, ftp); //dati.dati.nomeCartella
if (this.scenarioID == 1)
{
this.scenarioID = 0;
ConfigurationManager.AppSettings["WasApprovalFileSent"] = "true";
ConfigurationManager.AppSettings["approvalFileId"] = dati.IdZip.ToString();
ConfigurationManager.AppSettings["idFkZip"] = IDElaborazioneZip;
}
if (!ftp && this.scenarioID != 4 && this.scenarioID != 3) //pk 3 ->4
{
if (MessageBox.Show("Approval fie has been created and the Auto Send FTP parameter is checked out. Do you want to continue zipping process? No files will be send to SELECTA.", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) != MessageBoxResult.Yes)
{
ConfigurationManager.AppSettings["idFkZip"] = IDElaborazioneZip;
return 3;
}
else
{
doNotCloseElaborazione = true;
wasApprovalFileSend = false;
}
}
//SendFTP(dati.nomeCartella, dati.nomeFile, dati.IdZip);
if (!doNotCloseElaborazione)
FineElaborazioneZip(IDElaborazioneZip);
cPushNotification("FINE " + DateTime.Now + " creazione ZIP nome file: " + dati.nomeFile);
cPushNotification("");
//}
if (isUltimoZip == 2)
{
if (ProcessZip(onlyFullPacks, IDElaborazioneZip, IDZIP, 0, false, wasApprovalFileSend) < 0)//IdElaborazioneZip
return -1;
}
}
}
//invia flusso ad host
//inviaFlussoHostFTP();
}
else if (isUltimoZip > 0 && filesCount > 0) //#8488
{
string IDElaborazioneZip = (IdElaborazioneZip == "") ? InizioElaborazioneZip() : IdElaborazioneZip;
cPushNotification("INIZIO elaborazione ZIP");
cPushNotification("IDElaborazioneZip: " + IDElaborazioneZip);
cPushNotification("is it Ultini zip:" + isUltimoZip.ToString());
if (zipDaProcessare.Count > 0)
{
string _nomeFile = getZipName();
string _path = (tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : myConfig.pathZIP_PERIODICO;
string _IDElaborazioneZip = IDElaborazioneZip;
QueryGestioneInsertZip dati = getInfoZip(_nomeFile, _path, _IDElaborazioneZip, approvalID, approvalSuffix, isUltimoZip);//,k);
CreateDir(dati.nomeCartella);
cPushNotification("INIZIO " + DateTime.Now + " creazione ZIP nome file: " + dati.nomeFile + " in corso...");
//ZipIt(dati.nomeCartella, dati.nomeFile);
ZipIt(dati);
SendFTP(dati.nomeCartella, dati.nomeFile, dati.IdZip, type, 0, ftp);
FineElaborazioneZip(IDElaborazioneZip);
cPushNotification("FINE " + DateTime.Now + " creazione ZIP nome file: " + dati.nomeFile);
cPushNotification("");
}
else
{
Console.Write("TODO: remove the records created by getInfoZip");
logger.Error("TODO: remove the records created by getInfoZip");
};
if (isUltimoZip == 1)
{
FineElaborazioneZip(IDElaborazioneZip);
}
}//#8488
else
{
cPushNotification("FilesCount = 0");
}
cPushNotification("FINE elaborazione ZIP");
#endregion esecuzione zip
result = 0;
#endregion PresenzaTotali
}
catch (DataBaseException ex)
{
try
{
logger.Error(String.Concat("Zip Error: ", getDataBaseException(ex)));
ScriviErroreNelDB(3, getDataBaseException(ex), 1, "MotoreZip", "Main");
}
catch
{
}
result = 1;
}
catch (Exception ex)
{
try
{
logger.Error(String.Concat("Zip Error: ", ex.Message));
ScriviErroreNelDB(3, getException(ex), 2, "MotoreZip", "Main");
}
catch
{
}
result = 1;
}
finally
{
//rimetto il proxy
WebRequest.DefaultWebProxy = proxy;
}
}
return result;
}
string fullFileName(string fileName)
{
return ConfigurationManager.AppSettings["path_OUTPUT_ZIP_PERIODICO"].ToString() + fileName + ((int.Parse(ConfigurationManager.AppSettings["use7zip"]) == 1) ? ".7z" : ".zip");
}
public void EnforcePacking(string workingDirectory = null)
{
logger.Debug("start enforicng packaging");
string IDElaborazioneZip = "";
string idZipObtainProcedure = workingDirectory == null ? myConfig.SP_GESTIONE_SELECT_LAST_ZIP : myConfig.GESTIONE_SELECT_SPECIFIC_ZIP;
List<Parametro> parameters = null;
if (workingDirectory != null)
{
parameters = new List<Parametro>()
{
new Parametro()
{
ParameterName = "CARTELLA",
Value = new DirectoryInfo(workingDirectory).Name.ToUpper()
}
};
}
SqlDataReader reader = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, idZipObtainProcedure, parameters);
if (reader.HasRows)
{
reader.Read();
IDElaborazioneZip = reader["IdZip"].ToString();
logger.Debug("IDElaborazioneZip " + IDElaborazioneZip);
}
string tipoInvio = myConfig.TIPO_INVIO;
logger.Debug("tipoInvio " + tipoInvio);
QueryGestioneInsertZip dati = null;
if (string.IsNullOrEmpty(workingDirectory))
{
dati = getInfoZip(getZipName(), (tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : myConfig.pathZIP_PERIODICO, IDElaborazioneZip);//,k);
}
else
{
dati = getInfoZipEnforce(new DirectoryInfo(workingDirectory).Name.ToUpper(), workingDirectory, IDElaborazioneZip);//,k);
}
ZipIt(dati, workingDirectory);
}
private static DateTime dataZip = DateTime.Now;
//Adriano 20180227
private bool formatErrors = false;
//--Adriano 20180227
//static
public void GestioneFlussoGiornaliero()
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
//Elimino il proxy
IWebProxy proxy = WebRequest.GetSystemWebProxy();
WebRequest.DefaultWebProxy = null;
DateTime dataInvioHost = DateTime.Now;
string estensioneFile = "." + myConfig.EstensioneFileHost;
string nomeFile = myConfig.NomeFileHostGiornaliero;
string nomeFileHost = nomeFile + estensioneFile;
string nomeFileBackup = nomeFile + DateTime.Now.ToString("_yyyyMMdd") + estensioneFile;
string pathFileBackup = myConfig.PathFileHostGiornalieroBackup;
if (!pathFileBackup.EndsWith("\\"))
pathFileBackup += "\\";
pathFileBackup += nomeFileBackup;
SqlDataReader righeHost = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, "[C6Mart].[GESTIONE_SELECT_HOST_GIORNALIERO]", null);
if (righeHost.HasRows)
{
StringBuilder flussoHost = new StringBuilder();
while (righeHost.Read())
{
flussoHost.Append(righeHost["riga"].ToString() + "\r\n");
//updateDataComunicazioneHost(righeHost["idEmail"]);
}
byte[] flussoInByte = StrToByteArray(flussoHost.ToString());
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(myConfig.FTPServerHost + nomeFileHost);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.ContentLength = flussoInByte.Length;
request.Credentials = new NetworkCredential(myConfig.FTPUserHost, myConfig.FTPPasswordHost);
byte[] buffer = new byte[4096];
using (Stream writer = request.GetRequestStream())
using (MemoryStream ms = new MemoryStream(flussoInByte))
{
int bytesRead = 0;
int totalBytes = 0;
do
{
bytesRead = ms.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
writer.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
} while (bytesRead > 0);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
LogFTP(response);
response.Close();
File.WriteAllBytes(pathFileBackup, flussoInByte);
}
WebRequest.DefaultWebProxy = proxy;
}
//V Logga in una tabella del db l'esito dell'FTP
private static void LogFTP(FtpWebResponse response)
{
List<Parametro> parametri = new List<Parametro>();
Parametro p = new Parametro();
p.DbType = DbType.AnsiString;
p.ParameterName = "WelcomeMessage";
p.Value = response.WelcomeMessage;
parametri.Add(p);
p = new Parametro();
p.DbType = DbType.AnsiString;
p.ParameterName = "BannerMessage";
p.Value = response.BannerMessage;
parametri.Add(p);
p = new Parametro();
p.DbType = DbType.AnsiString;
p.ParameterName = "ResponseURI";
p.Value = response.ResponseUri.AbsolutePath;
parametri.Add(p);
p = new Parametro();
p.DbType = DbType.AnsiString;
p.ParameterName = "StatusDescription";
p.Value = response.StatusDescription;
parametri.Add(p);
p = new Parametro();
p.DbType = DbType.AnsiString;
p.ParameterName = "StatusCode";
p.Value = response.StatusCode.ToString();
parametri.Add(p);
DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServerStampeC6, "[dbo].[LogFTP]", parametri);
}
//static
public static string InizioElaborazioneZip()
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
ZipConfiguration config = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
IDataReader reader = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, config.SP_GESTIONE_INSERT_ELABORAZIONE_ZIP, null);
reader.Read();
return reader["IDElaborazioneZip"].ToString();
}
//static
private void FineElaborazioneZip(string IDElaborazioneZip)
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
List<Parametro> parametri = new List<Parametro>();
Parametro p = new Parametro();
p.ParameterName = "IDElaborazioneZip";
p.DbType = DbType.Int32;
p.Value = IDElaborazioneZip;
parametri.Add(p);
DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_UPDATE_ELABORAZIONE_ZIP, parametri);
}
private static void CreateDir(string pathDir)
{
try
{
logger.Debug(pathDir);
if (!Directory.Exists(pathDir))
Directory.CreateDirectory(pathDir);
}
catch (Exception ex)
{
try
{
logger.Error(String.Concat(ex.Message, pathDir));
}
catch { }
}
}
//static
private bool ripristinaFileRipartenza(string[] files)
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
int IDReport = 0;
string pathPdf = myConfig.pathZIP_PERIODICO;
string pathPdfToDb = myConfig.pathPDFToDB_PERIODICO;
string nomeFile = string.Empty;
try
{
foreach (string fileName in files)
{
nomeFile = fileName.Substring(31, 19);
IDReport = leggiIDReportDaFileName(nomeFile);
nomeFile = IDReport + "_" + nomeFile + ".PDF";
if (IDReport > 0)
{
File.Move(pathPdfToDb + nomeFile, pathPdf + nomeFile);
File.Delete(fileName);
}
//File.Copy (pathPdfToDb + nomeFile, pathPdf + nomeFile);
}
return true;
}
catch { return false; }
}
//static
private int leggiIDReportDaFileName(string nomefile)
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
int IDReport = 0;
List<Parametro> parametri = new List<Parametro>();
Parametro p = new Parametro();
p.ParameterName = "nomeFile";
p.DbType = DbType.String;
p.Value = nomefile;
parametri.Add(p);
IDataReader reader = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, "C6Martperiodico.sp_getIDReport", parametri);
reader.Read();
IDReport = Convert.ToInt32(reader["IDReport"].ToString());
return IDReport;
}
//static
private void SendFTP(string nomeCartella, string nomeFile, int id, string type = "zip", int scenarioid = 0, bool ftp = false)
{
ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
if (ftp && (scenarioid == 1 || scenarioID == 3 || scenarioID == 4)) //pk 3-> 4
SendZipToSelecta(nomeCartella, nomeFile, id);
else
CopiaInLocale(id, nomeCartella, nomeFile, type);
}
public string OutputZipFolder
{
get
{
string tipoInvio = myConfig.TIPO_INVIO;
return (tipoInvio.ToUpper() == "G") ? myConfig.path_OUTPUT_ZIP : myConfig.path_OUTPUT_ZIP_PERIODICO;
}
}
//static
private void CopiaInLocale(int idZip, string nomeCartella, string fileName, string type)
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
string tipoInvio = myConfig.TIPO_INVIO;
string inputPath = (tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : myConfig.pathZIP_PERIODICO;
string outputPath = OutputZipFolder;
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
if (!fileName.ToLower().Contains(type))
fileName += type;
string[] files = Directory.GetFiles(inputPath, fileName);
string temp;
foreach (string file in files)
{
temp = file.Replace(inputPath, outputPath);
File.Copy(file, temp, true);
File.Delete(file);
}
List<Parametro> parametri = new List<Parametro>();
Parametro p = new Parametro();
p.ParameterName = "id";
p.DbType = DbType.Int32;
p.Value = idZip;
parametri.Add(p);
DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_UPDATE_ZIP, parametri);
// Directory.Delete(nomeCartella, true);
}
//A seconda del tipo di invio cambia, vedi appConfig.
//static
private string getZipName()
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
string temp = myConfig.TIPO_INVIO == "G" ? myConfig.suffissoZIP_T1 : myConfig.suffissoZIP_T2;
//modifica Atzeri Emanuele 20/01/2012 (DataLotto)
string sDataLotto = myConfig.DataLotto;
if (sDataLotto != string.Empty)
{
return myConfig.prefissoZIP + "_" + sDataLotto + temp;
}
//Fine modifica Atzeri Emanuele 20/01/2012 (DataLotto)
else
{
if (dataZip == null)
dataZip = DateTime.Now;
return myConfig.prefissoZIP +
dataZip.ToString("_yyyyMMdd") + temp;
//è questa la parte che cambia
}
}
//static
private QueryGestioneInsertZip getInfoZip(string _nomeFile, string _path, string _IDElaborazioneZip, string approvalID = null, string _suffix = null, int _isUltimoZip = 0, bool noInsert = false)//,int k)
{
logger.Debug("aa " + _nomeFile + " " + _path + " " + _IDElaborazioneZip);
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
List<Parametro> parametri = new List<Parametro>(4);
Parametro nomeCartella = new Parametro();
nomeCartella.Value = _nomeFile;
nomeCartella.DbType = DbType.String;
nomeCartella.ParameterName = "NomeCartella";
parametri.Add(nomeCartella);
string sp = myConfig.SP_GESTIONE_INSERT_ZIP_IDX_NOINSERT;
if (!noInsert)
{
sp = myConfig.SP_GESTIONE_INSERT_ZIP;
Parametro nomeFile = new Parametro();
nomeFile.Value = _nomeFile;
nomeFile.DbType = DbType.String;
nomeFile.ParameterName = "NomeFile";
parametri.Add(nomeFile);
Parametro FKIDElaborazioneZip = new Parametro();
FKIDElaborazioneZip.Value = _IDElaborazioneZip;
FKIDElaborazioneZip.DbType = DbType.Int32;
FKIDElaborazioneZip.ParameterName = "FKIDElaborazioneZip";
parametri.Add(FKIDElaborazioneZip);
}
IDataReader reader = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, sp, parametri);
reader.Read();
QueryGestioneInsertZip result = new QueryGestioneInsertZip();
result.IdZip = Convert.ToInt32(reader["IdZip"]);
if (noInsert)
{
result.nomeCartella = _path;
result.nomeFile = reader["NomeFile"].ToString();
}
else
{
result.nomeCartella = _path + reader["NomeFile"].ToString() + "_" + result.IdZip.ToString();//k.ToString();
result.nomeFile = reader["NomeFile"].ToString() + "_LOTTO_" + _IDElaborazioneZip + "_PACK_" + result.IdZip.ToString();// k.ToString();
}
result.approvalID = (approvalID == null) ? string.Empty : approvalID;
result.suffix = (_suffix == null) ? string.Empty : _suffix;
return result;
}
private QueryGestioneInsertZip getInfoZipEnforce(string _nomeFile, string _path, string _IDElaborazioneZip, string approvalID = null)//,int k)
{
logger.Debug("aa " + _nomeFile + " " + _path + " " + _IDElaborazioneZip);
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
List<Parametro> parametri = new List<Parametro>(4);
Parametro nomeCartella = new Parametro();
nomeCartella.Value = _nomeFile;
nomeCartella.DbType = DbType.String;
nomeCartella.ParameterName = "NomeCartella";
parametri.Add(nomeCartella);
string sp = myConfig.SP_GESTIONE_INSERT_ZIP_IDX_NOINSERT;
IDataReader reader = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, sp, parametri);
reader.Read();
QueryGestioneInsertZip result = new QueryGestioneInsertZip();
result.IdZip = Convert.ToInt32(reader["IdZip"]);
result.nomeCartella = _path;
result.nomeFile = reader["NomeFile"].ToString();
result.approvalID = (approvalID == null) ? string.Empty : approvalID;
result.suffix = string.Empty;
return result;
}
private void SendZipToSelecta(string path, string fileName, int idZip)
{
logger.Debug("Starting ftp transfer process");
string zipFolder = ConfigurationManager.AppSettings["path_OUTPUT_ZIP_PERIODICO"];
string backupFolder = ConfigurationManager.AppSettings["path_ZIP_BACKUP_FOLDER"];
string ftpServer = ConfigurationManager.AppSettings["FTPServer"];
string ftpUser = ConfigurationManager.AppSettings["FTPUser"];
string ftpPath = ConfigurationManager.AppSettings["FTPPath"];
string ftpPassword = ConfigurationManager.AppSettings["FTPPassword"];
string suffixApproval = ConfigurationManager.AppSettings["suffixApproval"];
bool isFirstLotto = bool.Parse(ConfigurationManager.AppSettings["isFirstLotto"]);
string fullFileName = path + (path.EndsWith(@"\") ? "" : @"\") + fileName;
if (isFirstLotto || scenarioID == 1)
{
logger.Debug("Starting sending approval package.");
bool result = FTPProcessSeparated.UploadFirstApprovalLottoPackage(suffixApproval, zipFolder, ftpServer, ftpPath, ftpUser, ftpPassword, backupFolder, fileName);
string msg = result ? "Approval file sent successfully. Do you want to continue with other packages?" : "Approval file not sent. Do you want to continue with other packages?";
logger.Debug(msg);
if (result)
{
logger.Debug("Package approval sent successfully.");
}
else
{
logger.Debug("Failed to send approval package.");
}
}
if (scenarioID == 4) // pk 3->4
{
FTPProcessSeparated.UploadTrimestraleFiles(zipFolder, ftpServer, ftpPath, ftpUser, ftpPassword, backupFolder, null, fileName);
}
else if (scenarioID != 1)
{
FTPProcessSeparated.UploadTrimestraleFiles(zipFolder, ftpServer, ftpPath, ftpUser, ftpPassword, backupFolder);
}
}
//static
//private void SendZipToSelecta(string path, string fileName, int idZip)
//{
// //ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
// string tipoInvio = myConfig.TIPO_INVIO;
// string extension = ((int.Parse(ConfigurationManager.AppSettings["use7zip"]) == 1) ? ".7z" : ".zip");
// byte[] flussoInByte = File.ReadAllBytes(((tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : path) + fileName + extension); //myConfig.pathZIP_PERIODICO
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create(myConfig.FTPServer + fileName + extension);
// request.Method = WebRequestMethods.Ftp.UploadFile;
// request.ContentLength = flussoInByte.Length;
// request.Credentials = new NetworkCredential(myConfig.FTPUser, myConfig.FTPPassword);
// byte[] buffer = new byte[4096];
// using (Stream writer = request.GetRequestStream())
// using (MemoryStream ms = new MemoryStream(flussoInByte))
// {
// int bytesRead = 0;
// int totalBytes = 0;
// do
// {
// bytesRead = ms.Read(buffer, 0, buffer.Length);
// if (bytesRead > 0)
// {
// writer.Write(buffer, 0, bytesRead);
// totalBytes += bytesRead;
// }
// } while (bytesRead > 0);
// //Aggiorno la tabella dello zip
// //[C6Mart].[GESTIONE_UPDATE_ZIP]
// List<Parametro> parametri = new List<Parametro>();
// Parametro p = new Parametro();
// p.ParameterName = "id";
// p.DbType = DbType.Int32;
// p.Value = idZip;
// parametri.Add(p);
// DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_UPDATE_ZIP, parametri);
// Directory.Delete(path, true);
// }
// FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// response.Close();
//}
//static
private string creaFileFlussoDiAccompagnamento(QueryGestioneInsertZip dati, string workingDirectory = null)
{
string idxPath = string.Empty;
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
//Singolo FTP del FLUSSO Di Accompagnamento
//DateTime dataFlusso = DateTime.Now;
DateTime dataFlusso = dataZip;
string dt = myConfig.DataLotto;
if (dt == string.Empty)
{
dt = dataFlusso.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
}
//Adriano 20180227
int RowCount = 0;
int maxRowLen = 0;
string additionalLogFileFolder = ConfigurationManager.AppSettings["AdditionalLogFolder"];
string additionalLogFileName = string.Concat("ZipLog_", dataFlusso.ToString("yyyyMMdd"), ".txt");
string additionalLogPath = Path.Combine(additionalLogFileFolder, additionalLogFileName);
string errStr = "";
//--Adriano 20180227
string nomeFileFlusso = myConfig.PrefissoFile + "_" + dt + "_01." + myConfig.EstensioneFile;
List<Parametro> parametri = new List<Parametro>();
Parametro parametro = new Parametro();
parametro.DbType = DbType.Int32;
parametro.ParameterName = "idFkzip";
parametro.Value = dati.IdZip;
parametri.Add(parametro);
string sp = workingDirectory == null ? myConfig.SP_GESTIONE_SELECT_FTP_INVIATI : myConfig.SP_GESTIONE_SELECT_FTP_INVIATI_INCLUDINGFILENAME;
List<string> filesFromDisc = workingDirectory != null ? Directory.GetFiles(workingDirectory).Select(x => Path.GetFileNameWithoutExtension(x).ToUpper()).ToList() : null;
SqlDataReader filesInviati = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, sp, parametri);
if (filesInviati.HasRows)
{
StringBuilder flussoAccompagnamento = new StringBuilder();
while (filesInviati.Read())
{
//Adriano 20180227
maxRowLen = filesInviati["Tipo"].ToString().Equals("1") ? Int32.Parse(ConfigurationManager.AppSettings["IDXMaxRowLen1"]) : Int32.Parse(ConfigurationManager.AppSettings["IDXMaxRowLen2"]);
RowCount++;
if (filesInviati["riga"].ToString().Length > maxRowLen)
{
formatErrors = true;
errStr = string.Format("{0} -> Pack {1} -> File {2} -> Riga {3}: Il numero di caratteri ({4}) eccede la lunghezza massima per la riga corrente ({5}).", DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture), dati.nomeFile, nomeFileFlusso, RowCount.ToString(), filesInviati["riga"].ToString().Length, maxRowLen.ToString());
cPushNotification(errStr);
//scrittura nel file log
File.AppendAllText(additionalLogPath, errStr + Environment.NewLine);
}
//--Adriano 20180227
if (filesFromDisc != null)
{
string riga = filesInviati["riga"].ToString() + "\r\n";
foreach (var fileName in filesFromDisc)
{
if (riga.ToUpper().Contains(Path.GetFileNameWithoutExtension(fileName.ToUpper())))
{
flussoAccompagnamento.Append(riga);
}
}
}
else
{
flussoAccompagnamento.Append(filesInviati["riga"].ToString() + "\r\n");
}
}
string folder = dati.nomeCartella;
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
if (workingDirectory != null)
{
idxPath = Path.Combine(workingDirectory, nomeFileFlusso);
}
else
{
idxPath = dati.nomeCartella + "\\" + nomeFileFlusso;
}
File.WriteAllText(idxPath, flussoAccompagnamento.ToString());
}
//Adriano 20180305: inserisce una riga di separazione tra le elaborazioni
if (formatErrors)
File.AppendAllText(additionalLogPath, Environment.NewLine);
//--Adriano 20180305
return idxPath;
}
private int getRecordsNumberForZip(string _nomeFile, string _path, string _IDElaborazioneZip)
{
List<Parametro> parametri = new List<Parametro>(4);
Parametro nomeFile = new Parametro();
nomeFile.Value = _nomeFile;
nomeFile.DbType = DbType.String;
nomeFile.ParameterName = "NomeFile";
parametri.Add(nomeFile);
Parametro nomeCartella = new Parametro();
nomeCartella.Value = _nomeFile;
nomeCartella.DbType = DbType.String;
nomeCartella.ParameterName = "NomeCartella";
parametri.Add(nomeCartella);
Parametro FKIDElaborazioneZip = new Parametro();
FKIDElaborazioneZip.Value = _IDElaborazioneZip;
FKIDElaborazioneZip.DbType = DbType.Int32;
FKIDElaborazioneZip.ParameterName = "FKIDElaborazioneZip";
parametri.Add(FKIDElaborazioneZip);
int result = (int)DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_INSERT_ZIP, parametri);
return result;
}
//static
public void inviaFlussoHostFTP()
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
//Singolo FTP del FLUSSO Di Accompagnamento
//DateTime dataInvioHost = DateTime.Now;
DateTime dataInvioHost = dataZip;
string tipoInvio = myConfig.TIPO_INVIO;
string estensioneFile = "." + myConfig.EstensioneFileHost;
string nomeFile = ((tipoInvio.ToUpper() == "G") ? myConfig.NomeFileHostSettimanale : myConfig.NomeFileHostTrimestrale);
string nomeFileHost = nomeFile + estensioneFile;
string nomeFileBackup = nomeFile + DateTime.Now.ToString("_yyyyMMdd") + estensioneFile;
string pathFileBackup = ((tipoInvio.ToUpper() == "G") ? myConfig.PathFileHostSettimanaleBackup : myConfig.PathFileHostTrimestraleBackup);
if (!pathFileBackup.EndsWith("\\"))
pathFileBackup += "\\";
pathFileBackup += nomeFileBackup;
SqlDataReader righeHost = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_SELECT_HOST, null);
if (righeHost.HasRows)
{
StringBuilder flussoHost = new StringBuilder();
while (righeHost.Read())
{
flussoHost.Append(righeHost["riga"].ToString() + "\r\n");
//updateDataComunicazioneHost(righeHost["idEmail"]);
}
byte[] flussoInByte = StrToByteArray(flussoHost.ToString());
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(myConfig.FTPServerHost + nomeFileHost);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.ContentLength = flussoInByte.Length;
request.Credentials = new NetworkCredential(myConfig.FTPUserHost, myConfig.FTPPasswordHost);
byte[] buffer = new byte[4096];
using (Stream writer = request.GetRequestStream())
using (MemoryStream ms = new MemoryStream(flussoInByte))
{
int bytesRead = 0;
int totalBytes = 0;
do
{
bytesRead = ms.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
writer.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
} while (bytesRead > 0);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//V
//LogFTP(response);
//
response.Close();
File.WriteAllBytes(pathFileBackup, flussoInByte);
}
}
private void updateDataComunicazioneHost(object idEmail)
{
try
{
if (idEmail != null)
{
List<Parametro> parametri = new List<Parametro>();
Parametro parametro = new Parametro();
parametro.DbType = DbType.Int32;
parametro.ParameterName = "Email_Id";
parametro.Value = idEmail;
parametri.Add(parametro);
DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServerStampeC6, myConfig.SP_GESTIONE_UPDATE_EMAIL_HOST, parametri);
}
}
catch (Exception ex)
{
DataBaseException dataBaseException = (DataBaseException)ex;
cPushNotification(dataBaseException.Message);
Console.WriteLine(dataBaseException.Message);
}
}
private static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
private static string getDataBaseException(DataBaseException ecc)
{
const string aCapo = "#/n#";
string ritorno = "";
ritorno += aCapo;
ritorno += " Informazioni Comando SQL:" + aCapo;
ritorno += " sql file name: " + ecc.SqlFileName + aCapo;
ritorno += " connection string: " + ecc.ConnectionStringWithoutCredentials + aCapo;
//ritorno += " command text: " + ecc.CommandText + aCapo;
//controllo se ci sono i parametri
if (ecc.Parameters != null)
{
foreach (Parametro parametro in ecc.Parameters)
{
ritorno += aCapo;
ritorno += " parametro: " + parametro.ParameterName + aCapo;
ritorno += " dimensione: " + parametro.Size.ToString() + aCapo;
ritorno += " direzione: " + parametro.Direction.ToString() + aCapo;
ritorno += " tipo: " + parametro.DbType.ToString() + aCapo;
if (parametro.Value == null)
ritorno += " valore: null" + aCapo;
else
{
string valoreParametro = "";
if (parametro.Size > 500)
{
valoreParametro = " valore: null(sono visualizzati solo i primi 500 bytes): " + parametro.Value.ToString().Substring(0, 500);
}
else
{
valoreParametro = " valore: " + parametro.Value.ToString();
}
ritorno += valoreParametro + aCapo;
}
}
}
ritorno += aCapo;
ritorno += " tipo: DataBaseException" + aCapo;
ritorno += " descrizione: " + ecc.Eccezione.Message + aCapo;
ritorno += " sorgente: " + ecc.Eccezione.Source + aCapo;
ritorno += " traccia: " + FormattaErrore(ecc.StackTrace) + aCapo;
return ritorno;
}
private static string getException(Exception ecc)
{
const string aCapo = "#/n#";
string ritorno = "";
ritorno += aCapo;
ritorno += " tipo: " + ecc.GetType().ToString() + aCapo;
ritorno += " descrizione: " + ecc.Message + aCapo;
ritorno += " sorgente: " + ecc.Source + aCapo;
if (ecc.InnerException != null)
{
ritorno += " descrizione Inner: " + ecc.InnerException.Message + aCapo;
ritorno += " sorgente Inner: " + ecc.InnerException.Source + aCapo;
}
ritorno += " traccia: " + FormattaErrore(ecc.StackTrace) + aCapo;
return ritorno;
}
private static string FormattaErrore(string errore)
{
const string aCapo = "#/n#";
const string spazio = " ";
string separatore1 = " at ";
string separatore2 = " in ";
string separatore3 = ":line ";
string erroreInterno = errore.Replace(separatore1, "@");
string ritorno = aCapo;
//nome metodo e tutto il resto
string[] messaggioErrore = erroreInterno.Split('@');
string messaggioSenzaSpazi;
string[] messaggioInterno;
foreach (string messaggio in messaggioErrore)
{
messaggioSenzaSpazi = messaggio.Trim();
if (messaggioSenzaSpazi != "")
{
messaggioSenzaSpazi = messaggioSenzaSpazi.Replace(separatore2, "@");
messaggioInterno = messaggioSenzaSpazi.Split('@');
if (messaggioInterno.GetUpperBound(0) == 1)
{
ritorno += spazio + "metodo: " + messaggioInterno[0] + aCapo;
string fileLineaSingolo = messaggioInterno[1].Replace(separatore3, "@");
string[] fileLinea = fileLineaSingolo.Split('@');
ritorno += spazio + "percorsoFile: " + fileLinea[0] + aCapo;
ritorno += spazio + "linea: " + fileLinea[1] + aCapo;
ritorno += aCapo;
}
else
{
ritorno += spazio + "metodo: " + messaggioInterno[0] + aCapo;
}
}
}
return ritorno;
}
//static
private void ScriviErroreNelDB(int codiceErrore, string descrizioErrore, int localeId, string nomePackage, string descrizionePackage)
{
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
int scriviErroreNelDB = int.Parse(myConfig.scriviErroreNelDB);
if (scriviErroreNelDB == 1)
{
//try {
List<Parametro> parametri = new List<Parametro>();
Parametro parametro = new Parametro();
parametro.DbType = DbType.Int32;
parametro.ParameterName = "codiceErrore";
parametro.Value = codiceErrore;
parametri.Add(parametro);
parametro = new Parametro();
parametro.DbType = DbType.String;
parametro.ParameterName = "descrizioErrore";
parametro.Value = descrizioErrore;
parametri.Add(parametro);
parametro = new Parametro();
parametro.DbType = DbType.DateTime;
parametro.ParameterName = "dataTime";
parametro.Value = DateTime.Now;
parametri.Add(parametro);
parametro = new Parametro();
parametro.DbType = DbType.String;
parametro.ParameterName = "localeID";
if (localeId == 0)
parametro.Value = System.DBNull.Value;
else
parametro.Value = localeId;
parametri.Add(parametro);
parametro = new Parametro();
parametro.DbType = DbType.String;
parametro.ParameterName = "descrizionePackage";
parametro.Value = descrizionePackage;
parametri.Add(parametro);
parametro = new Parametro();
parametro.DbType = DbType.String;
parametro.ParameterName = "nomePackage";
parametro.Value = nomePackage;
parametri.Add(parametro);
DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServerStampeC6, "[C6Mart].[UT_INSERT_ERROR]", parametri);
//}
//catch (Exception ex) {
// DataBaseException dataBaseException = (DataBaseException)ex;
// cPushNotification(dataBaseException.Message);
//}
}
}
private static void StartTng(string ambiente, string cawTo_Bin, string argomentiCaw)
{
if (!ambiente.Equals("SVILUPPO"))
{
Process processTng = new Process();
try
{
processTng = Process.Start(cawTo_Bin, argomentiCaw);
while (!processTng.HasExited)
;
}
catch (Exception ex)
{
throw new Exception("cawTo_Bin: Non riesco ad eseguire " + cawTo_Bin + " sulla macchina " + System.Environment.MachineName + ":" + ex.Message);
}
finally
{
processTng.Close();
processTng.Dispose();
}
}
}
//ZIPPATORE
//private static void ZipIt(string path, string zipName)
private void ZipIt(QueryGestioneInsertZip dati, string workingDirectory = null)
{
//Adriano 20180227
formatErrors = false;
//--Adriano 20180227
int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]);
//ZipConfiguration myConfig = ZipConfiguration.ReadFromConfiguration(ConfigurationManager.AppSettings);
string path = dati.nomeCartella;
string zipName = dati.fileName;
string dir = (workingDirectory == null) ? path : workingDirectory;
string idxFilePath = creaFileFlussoDiAccompagnamento(dati, workingDirectory);
string destPath = string.IsNullOrEmpty(workingDirectory) ? ConfigurationManager.AppSettings["path_OUTPUT_ZIP_PERIODICO"].ToString() : workingDirectory;
if (useZ == 1)
{
if (!zipName.EndsWith(".zip".ToUpper()))
zipName += ".7z";
//invia lettera accompagnamento FTP
// ToDo Fc
// IL FILE di Accompagnamento deve essere generato in fase di chiusura del file ZIP
try
{
string appName = "7za.exe";
string appParam = String.Concat("a -t7z ", destPath, zipName, " ", path, @"\*.*");
Process p = Process.Start(appName, appParam);
p.WaitForExit();
Process getPdfCount = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c 7za.exe l \"" + destPath + zipName + "\" | find /i \".pdf\" /c";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
getPdfCount.StartInfo = startInfo;
getPdfCount.Start();
string output = getPdfCount.StandardOutput.ReadToEnd().Replace("\n", "").Replace("\r", "");
int pdfCount = -1;
int.TryParse(output, out pdfCount);
if (pdfCount != -1 && zipPackages != null)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
zipPackages.Insert(0, new ZipItem()
{
CreationDate = DateTime.Now,
FilesCount = pdfCount,
PackName = zipName,
//Adriano 20180227
Notes = !formatErrors ? "" : "Controllare il file di Log"
//--Adriano 20180227
});
}));
}
}
catch (Exception ex)
{
cPushNotification(ex.Message);
//Console.Write(ex.ToString());
throw new Exception(ex.Message + " il valore della data era: " + dataZip);
}
if (File.Exists(idxFilePath))
{
File.Delete(idxFilePath);
}
if (Directory.Exists(path))
{
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles("*.7z"))
{
string s = myConfig.path_OUTPUT_ZIP_PERIODICO + @"\" + fi.Name;
if (File.Exists(s))
{
File.Move(s, s + ".bak");
}
fi.MoveTo(s);
}
foreach (FileInfo fi in di.GetFiles())
fi.Delete();
di.Delete();
}
}
else
{
try
{
if (!zipName.EndsWith(".zip".ToUpper()))
zipName += ".zip";
//string[] reports = Directory.GetFiles(path, "*.pdf");
//string[] reports = Directory.GetFiles(path, "*.pdf");
string pathPdf = dati.nomeCartella;
string[] reports = Directory.GetFiles(pathPdf, "*.pdf");
string tipoInvio = myConfig.TIPO_INVIO;
if (reports.Length > 0)
{
using (ZipOutputStream stream = new ZipOutputStream(File.Create(((tipoInvio.ToUpper() == "G") ? myConfig.pathZIP : myConfig.pathZIP_PERIODICO) + zipName)))
{
//appconfig 9 best compression
stream.UseZip64 = UseZip64.Off;
stream.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string report in reports)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(report));
entry.DateTime = DateTime.Now;
stream.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(report))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
reports = Directory.GetFiles(path, "*." + myConfig.EstensioneFile);
foreach (string report in reports)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(report));
entry.DateTime = DateTime.Now;
stream.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(report))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
stream.Finish();
stream.Close();
}
}
}
catch (Exception ex)
{
cPushNotification(ex.Message);
//Console.Write(ex.ToString());
throw new Exception(ex.Message + " il valore della data era: " + dataZip);
}
}
}
}
}