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.Reflection;
using DataAccessLayer;

namespace SmartFTPThread.Logic
{

    public static class FtpProcessSeparated
    {
        // 20181017 AC
        private static string logPath = ConfigurationManager.AppSettings["LogPath"];

        public static int StartProcessing(string ambiente, string tngServer, string tngJobset, string tngJob)
        {
            // 20181017 AC
            Log(new string('*', 50), true);
            Log("StartProcessing");

            //string ambiente = ConfigurationManager.AppSettings["ambiente"];
            string cawTo_Bin = ConfigurationManager.AppSettings["cawTo_Bin"];
            //string tngServer = args[0];
            //string tngJobset = args[1];
            //string tngJob = args[2];
            string funzione = "GESTORE FTP";
            string fac_I_100 = ConfigurationManager.AppSettings["fac_I_100"];
            string fac_T_100 = ConfigurationManager.AppSettings["fac_T_100"];
            string fac_E_100 = ConfigurationManager.AppSettings["fac_E_100"];


            string argomentiCawToInizio = "-n " + tngServer + " " + fac_I_100 + " " + tngJobset + " - " + tngJob + " - Funzione " + funzione + " INIZIATA";
            string argomentiCawToTerminato = "-n " + tngServer + " " + fac_T_100 + " " + tngJobset + " - " + tngJob + " - Funzione " + funzione + " terminata con SUCCESSO";
            string argomentiCawToErrore = "-n " + tngServer + " " + fac_E_100 + " " + tngJobset + " - " + tngJob + " - Funzione "; // +funzione + " terminata con ERRORE";

            //elimino il proxy
            IWebProxy proxy = WebRequest.GetSystemWebProxy();
            WebRequest.DefaultWebProxy = null;

            try
            {
                // AN 04/03/2014
                // Inserimento Gestione Aggiornamento ROL
                Process p = Process.Start(ConfigurationManager.AppSettings["PathRolExe"].ToString(), ConfigurationManager.AppSettings["ArgRolExe"].ToString());
                p.WaitForExit();
                if (p.ExitCode != 0)
                    throw new Exception(ConfigurationManager.AppSettings["PathRolExe"].ToString() + " " + ConfigurationManager.AppSettings["ArgRolExe"].ToString());

                // FC 24/02/2014
                // Modifica numero massimo di report da 3 a 960
                int numeroCfPerZip = 1200; // FC 03/03/2014 1200 temporaneo per reucperopdf

                // 20181017 AC
                Log("Inizio creazione lista PDF da processare.");

                //START
                StartTng(ambiente, cawTo_Bin, argomentiCawToInizio);
                IDataReader pdfs = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, ConfigurationManager.AppSettings["SP_GESTIONE_SELECT_FTP_DA_INVIARE"], null);
                //V Crea una lista di liste di report da processare, ogni lista rappresenta uno ZIP
                List<List<ReportDaProcessare>> zipDaProcessare = new List<List<ReportDaProcessare>>();
                List<ReportDaProcessare> reportsDaProcessare = new List<ReportDaProcessare>();
                int contatoreCf = 0;
                string ultimoCf = string.Empty;
                while (pdfs.Read())
                {

                    // 20181017 AC
                    //log(string.Format("Aggiunta report CF: {0}, id: {1}, file: {2}, tipo: {3}", pdfs["CodiceFiscale"].ToString(), pdfs["IdReport"], pdfs["NomeFile"].ToString(), pdfs["TipoReport"].ToString()));

                    reportsDaProcessare.Add(new ReportDaProcessare((int)pdfs["IdReport"], pdfs["NomeFile"].ToString(), pdfs["TipoReport"].ToString()));
                    if (ultimoCf != pdfs["CodiceFiscale"].ToString())
                    {
                        ultimoCf = pdfs["CodiceFiscale"].ToString();
                        contatoreCf = ++contatoreCf;
                    }

                    //V ho raggiunto la quota massima aggiungo la lista e ne creo una nuova
                    if (contatoreCf == numeroCfPerZip)
                    {
                        zipDaProcessare.Add(reportsDaProcessare);
                        reportsDaProcessare = new List<ReportDaProcessare>();
                        contatoreCf = 0;
                    }

                }

                //V aggiungo l'ultima lista alla lista degli zip, solo nel caso la lista abbia almeno un elemento
                if (contatoreCf > 0)
                    zipDaProcessare.Add(reportsDaProcessare);

                string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];

                //int k = 1;

                Log(string.Format("zipDaProcessare.Count = {0}", zipDaProcessare.Count));

                foreach (List<ReportDaProcessare> lrp in zipDaProcessare)
                {
                    QueryGestioneInsertZip dati = getInfoZip(getZipName(), (tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"]);//,k);
                    CreateDir(dati.nomeCartella);

                    // 20181017 AC
                    Log("Creazione cartella:" + dati.nomeCartella);

                    //++k;
                    SmartFTP m = new SmartFTP(lrp, dati.nomeCartella, ambiente, cawTo_Bin, argomentiCawToErrore);
                    m.Start(dati.IdZip);
                    // FCTodo 27/02/2014 
                    // ZipIt(dati.nomeCartella, dati.nomeFile);
                    // SendFTP(dati.nomeCartella, dati.nomeFile, dati.IdZip);

                    // 20181017 AC
                    Log(string.Format("Inizio Zip {0}\\{1}", dati.nomeCartella, dati.nomeFile));

                    if (!ZipIt(dati.nomeCartella, dati.nomeFile))
                    {
                        funzione = "ScriviErroreNelDB";
                        ScriviErroreNelDB(-000029, "Errore nel Gestore FTP: N Clienti in file IDX non corrispendente al N PDF processati " + dati.nomeFile, -292929, "Gestore FTP", "Gestore FTP");
                        funzione = "GESTORE FTP";

                        // 20181017 AC
                        Log("Errore nel Gestore FTP: N Clienti in file IDX non corrispendente al N PDF processati " + dati.nomeFile);
                    }

                    else
                    {
                        // 20181017 AC
                        Log(string.Format("Inizio invio FTP {0}\\{1} {2}", dati.nomeCartella, dati.nomeFile, dati.IdZip));

                        SendFTP(dati.nomeCartella, dati.nomeFile, dati.IdZip);

                        Log(string.Format("Fine invio FTP {0}\\{1} {2}", dati.nomeCartella, dati.nomeFile, dati.IdZip));
                    }
                }

                // AN 17/02/2014 
                // Errore Abend Processo Archiviazione ZIp Settimanale
                // Commento al metodo inviaFlussoHostFTP, in quanto è un refuso del vecchio codice che scrive su una macchina 
                // non piu attiva 
                //invia flusso ad host
                //inviaFlussoHostFTP();

                //FINISH
                StartTng(ambiente, cawTo_Bin, argomentiCawToTerminato);
                Log(string.Format("Fine processing"));
                
                return 0;
            }
            catch (DataBaseException ex)
            {
                try
                {
                    funzione = "ScriviErroreNelDB";
                    ScriviErroreNelDB(-292929, "Errore nel Gestore FTP: " + getDataBaseException(ex), -292929, "Gestore FTP", "Gestore FTP");
                    funzione = "GESTORE FTP";

                    // 20181017 AC
                    Log("Errore nel Gestore FTP: " + getDataBaseException(ex));
                }
                catch
                {
                }

                argomentiCawToErrore += funzione + " terminata con ERRORE";
                StartTng(ambiente, cawTo_Bin, argomentiCawToErrore);
                return 1;
            }
            catch (Exception ex)
            {
                try
                {
                    funzione = "ScriviErroreNelDB";
                    ScriviErroreNelDB(-292929, "Errore nel Gestore FTP: " + getException(ex), -292929, "Gestore FTP", "Gestore FTP");
                    funzione = "GESTORE FTP";

                    // 20181017 AC
                    Log("Errore nel Gestore FTP: " + getException(ex));
                }
                catch
                {
                }

                argomentiCawToErrore += funzione + " terminata con ERRORE";
                StartTng(ambiente, cawTo_Bin, argomentiCawToErrore);
                return 1;
            }
            finally
            {
                //rimetto il proxy
                WebRequest.DefaultWebProxy = proxy;
            }

        }

        private static void CreateDir(string pathDir)
        {
            if (!Directory.Exists(pathDir))
                Directory.CreateDirectory(pathDir);
        }

        private static void SendFTP(string nomeCartella, string nomeFile, int id)
        {

            short FTP = Convert.ToInt16(ConfigurationManager.AppSettings["FTP"]);
            int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]);
            string extension = ".zip";
            if (useZ == 1)
                extension = ".7z";

            if (FTP == 1)
                SendZipToSelecta(nomeCartella, nomeFile, id, extension);
            else
                CopiaInLocale(id, nomeCartella, nomeFile, extension);

        }

        private static void CopiaInLocaleOld(int idZip, string nomeCartella, string fileName)
        {
            string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];
            string inputPath = (tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"];
            string outputPath = (tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["path_OUTPUT_ZIP"] : ConfigurationManager.AppSettings["path_OUTPUT_ZIP_PERIODICO"];
            if (!Directory.Exists(outputPath))
                Directory.CreateDirectory(outputPath);
            if (!fileName.ToLower().Contains(".zip"))
                fileName += ".zip";
            string[] files = Directory.GetFiles(inputPath, fileName);
            string temp;
            foreach (string file in files)
            {
                temp = file.Replace(inputPath, outputPath);
                File.Copy(file, temp, false);
            }

            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, ConfigurationManager.AppSettings["SP_GESTIONE_UPDATE_ZIP"], parametri);

            Directory.Delete(nomeCartella, true);
        }

        //A seconda del tipo di invio cambia, vedi appConfig.
        private static string getZipName()
        {
            string temp = ConfigurationManager.AppSettings["TIPO_INVIO"] == "G" ? ConfigurationManager.AppSettings["suffissoZIP_T1"] : ConfigurationManager.AppSettings["suffissoZIP_T2"];
            return ConfigurationManager.AppSettings["prefissoZIP"] +
                    DateTime.Now.ToString("_yyyyMMdd") + temp;
            //è questa la parte che cambia      
        }

        private static QueryGestioneInsertZip getInfoZip(string _nomeFile, string _path)//,int k)
        {

            List<Parametro> parametri = new List<Parametro>(3);

            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);


            IDataReader reader = DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, ConfigurationManager.AppSettings["SP_GESTIONE_INSERT_ZIP"], parametri);
            reader.Read();

            QueryGestioneInsertZip result = new QueryGestioneInsertZip();
            result.IdZip = Convert.ToInt32(reader["IdZip"]);
            result.nomeCartella = _path + reader["NomeCartella"].ToString() + "_" + result.IdZip.ToString();//k.ToString();
            result.nomeFile = reader["NomeFile"].ToString() + "_" + result.IdZip.ToString();// k.ToString();

            return result;

        }

        private static void SendZipToSelecta_Old(string path, string fileName, int idZip)
        {
            string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];
            string ext = string.Empty;

            ext = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]) == 1 ? ".7z" : ".zip";

            byte[] flussoInByte = File.ReadAllBytes(((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"]) + fileName + ext);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["FTPServer"] + fileName + ext);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.ContentLength = flussoInByte.Length;
            request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FTPUser"], ConfigurationManager.AppSettings["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, ConfigurationManager.AppSettings["SP_GESTIONE_UPDATE_ZIP"], parametri);

                Directory.Delete(path, true);

            }

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();

        }
        /*
        private static void creaFileFlussoDiAccompagnamentoFTP (string path)
        {
            //Singolo FTP del FLUSSO Di Accompagnamento
            DateTime dataFlusso = DateTime.Now;
            string nomeFileFlusso = ConfigurationManager.AppSettings["PrefissoFile"] + "_" + dataFlusso.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + "_01." + ConfigurationManager.AppSettings["EstensioneFile"];
            SqlDataReader filesInviati = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, ConfigurationManager.AppSettings["SP_GESTIONE_SELECT_FTP_INVIATI"], null);
            if (filesInviati.HasRows)
            {
                StringBuilder flussoAccompagnamento = new StringBuilder();
                while (filesInviati.Read())
                {

                    flussoAccompagnamento.Append(filesInviati["riga"].ToString() + "\r\n");
                }

                File.WriteAllText(path + "\\" + nomeFileFlusso, flussoAccompagnamento.ToString());

            }
        }

        */
        private static int creaFileFlussoDiAccompagnamentoFTP(string path)
        {
            // numero di record letti
            int RecordCount = 0;
            //Singolo FTP del FLUSSO Di Accompagnamento
            DateTime dataFlusso = DateTime.Now;
            string nomeFileFlusso = ConfigurationManager.AppSettings["PrefissoFile"] + "_" + dataFlusso.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + "_01." + ConfigurationManager.AppSettings["EstensioneFile"];
            SqlDataReader filesInviati = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, ConfigurationManager.AppSettings["SP_GESTIONE_SELECT_FTP_INVIATI"], null);
            if (filesInviati.HasRows)
            {
                StringBuilder flussoAccompagnamento = new StringBuilder();
                while (filesInviati.Read())
                {
                    if (!filesInviati["riga"].ToString().Equals(""))
                    {
                        flussoAccompagnamento.Append(filesInviati["riga"].ToString() + "\r\n");
                        RecordCount++;
                    }
                }

                File.WriteAllText(path + "\\" + nomeFileFlusso, flussoAccompagnamento.ToString());
                return RecordCount;

            }

            return 0;
        }


        public static void inviaFlussoHostFTP()
        {
            //Singolo FTP del FLUSSO Di Accompagnamento
            DateTime dataInvioHost = DateTime.Now;
            string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];
            string estensioneFile = "." + ConfigurationManager.AppSettings["EstensioneFileHost"];



            string nomeFile = ((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["NomeFileHostSettimanale"] : ConfigurationManager.AppSettings["NomeFileHostTrimestrale"]);
            string nomeFileHost = nomeFile + estensioneFile;
            string nomeFileBackup = nomeFile + DateTime.Now.ToString("_yyyyMMdd") + estensioneFile;
            string pathFileBackup = ((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["PathFileHostSettimanaleBackup"] : ConfigurationManager.AppSettings["PathFileHostTrimestraleBackup"]);

            if (!pathFileBackup.EndsWith("\\"))
                pathFileBackup += "\\";

            pathFileBackup += nomeFileBackup;


            SqlDataReader righeHost = (SqlDataReader)DataAccess.ExecuteDataReaderStoredProcedure(DBProvider.SqlServerStampeC6, ConfigurationManager.AppSettings["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(CACHE.FTPServerHost + nomeFileHost);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.ContentLength = flussoInByte.Length;
                request.Credentials = new NetworkCredential(CACHE.FTPUserHost,CACHE.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 static 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, ConfigurationManager.AppSettings["SP_GESTIONE_UPDATE_EMAIL_HOST"], parametri);
                }
            }
            catch (Exception ex)
            {
                DataBaseException dataBaseException = (DataBaseException)ex;
                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;
        }

        private static void ScriviErroreNelDB(int codiceErrore, string descrizioErrore, int localeId, string nomePackage, string descrizionePackage)
        {
            int scriviErroreNelDB = int.Parse(ConfigurationManager.AppSettings["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;
                //    Console.WriteLine(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)
        //{

        //    if (!zipName.EndsWith(".zip".ToUpper()))
        //        zipName += ".zip";


        //    //invia lettera accompagnamento FTP
        //    // metodo Sostituito per Chiamata con ritorno valore tot righe elaborate
        //    //creaFileFlussoDiAccompagnamentoFTP(path);

        //    int nListaIdx=creaFileFlussoDiAccompagnamentoFTP(path);

        //    try
        //    {
        //        string[] reports = Directory.GetFiles(path, "*.pdf");

        //        int nTotPDF = reports.Length;


        //        string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];

        //        using (ZipOutputStream stream = new ZipOutputStream(File.Create(((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["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, "*." + ConfigurationManager.AppSettings["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)
        //    {

        //        //Console.Write(ex.ToString());
        //        throw new Exception(ex.Message);
        //    }

        //}


        private static Boolean ZipItOld(string path, string zipName)
        {

            if (!zipName.EndsWith(".zip".ToUpper()))
                zipName += ".zip";


            //invia lettera accompagnamento FTP
            // metodo Sostituito per Chiamata con ritorno valore tot righe elaborate
            //creaFileFlussoDiAccompagnamentoFTP(path);

            int nListaIdx = creaFileFlussoDiAccompagnamentoFTP(path);

            try
            {
                string[] reports = Directory.GetFiles(path, "*.pdf");

                //FCTodo  27/02/2014
                int nTotPDF = reports.Length;

                if (nListaIdx != nTotPDF)
                {
                    Console.WriteLine("nListaIdx : " + nListaIdx);
                    Console.WriteLine("nTotPDF : " + nTotPDF);
                    return false;
                }

                string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];

                using (ZipOutputStream stream = new ZipOutputStream(File.Create(((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["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, "*." + ConfigurationManager.AppSettings["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();
                }
                return true;
            }
            catch (Exception ex)
            {

                //Console.Write(ex.ToString());
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// Assolutamente da ristrutturare l'FTP, aggiunto metodo richiamabile dal generator
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static void GestioneFlussoGiornaliero()
        {

            //Elimino il proxy
            IWebProxy proxy = WebRequest.GetSystemWebProxy();
            WebRequest.DefaultWebProxy = null;

            DateTime dataInvioHost = DateTime.Now;
            string estensioneFile = "." + ConfigurationManager.AppSettings["EstensioneFileHost"];
            string nomeFile = ConfigurationManager.AppSettings["NomeFileHostGiornaliero"];
            string nomeFileHost = nomeFile + estensioneFile;
            string nomeFileBackup = nomeFile + DateTime.Now.ToString("_yyyyMMdd") + estensioneFile;
            string pathFileBackup = ConfigurationManager.AppSettings["PathFileHostGiornalieroBackup"];
            string pathFileAppoggio = ConfigurationManager.AppSettings["PathFileHostGiornalieroAppoggio"];
            string FileBatchFTP = ConfigurationManager.AppSettings["PathFileBatchFTP"];

            if (!pathFileBackup.EndsWith("\\"))
                pathFileBackup += "\\";

            if (!pathFileAppoggio.EndsWith("\\"))
                pathFileAppoggio += "\\";

            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());

                //scrittura file di backup
                pathFileBackup += nomeFileBackup;
                File.WriteAllBytes(pathFileBackup, flussoInByte);

                //cancello il file delle commissioni vecchio sulla dir di appoggio
                pathFileAppoggio += nomeFileHost;
                if (File.Exists(pathFileAppoggio))
                {
                    // Use a try block to catch IOExceptions, to
                    // handle the case of the file already being
                    // opened by another process.
                    try
                    {
                        File.Delete(pathFileAppoggio);
                    }
                    catch (IOException e)
                    {
                        ScriviErroreNelDB(-292929, "Errore nella cancellazione del file delle commissioni del Gestore FTP: " + e, -292929, "Gestore FTP", "Gestore FTP");
                    }
                }

                //scrittura file da trasferire via FTP
                File.WriteAllBytes(pathFileAppoggio, flussoInByte);

            }

            WebRequest.DefaultWebProxy = proxy;

        }

        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);



        }

        // 20181015 AC Provare con questa nuova versione di ZipIt (presa da rootV1Final, che utilizza anche 7Zip)
        private static Boolean ZipIt(string path, string zipName)
        {
            int useZ = Int32.Parse(ConfigurationManager.AppSettings["use7zip"]);

            if (useZ == 1)
            {
                if (!zipName.EndsWith(".7z".ToUpper()))
                    zipName += ".7z";

                int nListaIdx = creaFileFlussoDiAccompagnamentoFTP(path);
                //invia lettera accompagnamento FTP
                string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];
                string destPath = ((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"]);

                // ToDo Fc
                // IL FILE di Accompagnamento deve essere generato in fase di chiusura del file ZIP
                string[] reports = Directory.GetFiles(path, "*.pdf");

                //FCTodo  27/02/2014
                int nTotPDF = reports.Length;

                if (nListaIdx != nTotPDF)
                {
                    Console.WriteLine("nListaIdx : " + nListaIdx);
                    Console.WriteLine("nTotPDF : " + nTotPDF);
                    return false;
                }



                try
                {
                    string appName = String.Concat(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"\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 " + appName + " 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);

                }
                catch (Exception ex)
                {
                    //Console.Write(ex.ToString());
                    throw new Exception(String.Concat(Directory.GetCurrentDirectory(), "/c 7za.exe l \"" + destPath + zipName + "\" | find /i  \".pdf\" /c", ex.Message, " (2)il valore della data era: "));
                }

                return true;
            }
            else
            {

                if (!zipName.EndsWith(".zip".ToUpper()))
                    zipName += ".zip";


                //invia lettera accompagnamento FTP
                // metodo Sostituito per Chiamata con ritorno valore tot righe elaborate
                //creaFileFlussoDiAccompagnamentoFTP(path);

                int nListaIdx = creaFileFlussoDiAccompagnamentoFTP(path);

                try
                {
                    string[] reports = Directory.GetFiles(path, "*.pdf");

                    //FCTodo  27/02/2014
                    int nTotPDF = reports.Length;

                    if (nListaIdx != nTotPDF)
                    {
                        Console.WriteLine("nListaIdx : " + nListaIdx);
                        Console.WriteLine("nTotPDF : " + nTotPDF);
                        return false;
                    }

                    string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];

                    using (ZipOutputStream stream = new ZipOutputStream(File.Create(((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["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, "*." + ConfigurationManager.AppSettings["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();
                    }
                    return true;
                }
                catch (Exception ex)
                {

                    //Console.Write(ex.ToString());
                    throw new Exception(ex.Message);
                }
            }

        }

        // 20181017 AC Utilizzo del metodo già utilizzato nella versione V1Final...
        private static void SendZipToSelecta(string path, string fileName, int idZip, string extension)
        {
            try
            {

                string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];
                string sourceFolder = (tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"];
                string sourceFile = fileName + extension;
                //Console.WriteLine(sourceFile);
                //Console.WriteLine(sourceFolder);
                if (FTPTransferUtil.UploadFile(sourceFolder, sourceFile) != 1)
                {
                    Log(string.Format("Errore durante upload del file {0}", sourceFile));
                    return;
                }

                Log(string.Format("Invio FTP del file {0} riuscito.", sourceFile));

                //byte[] flussoInByte = File.ReadAllBytes(((tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"]) + fileName + extension);// + ".zip"

                //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["FTPServer"] + fileName + extension);// ".zip");
                //request.Method = WebRequestMethods.Ftp.UploadFile;
                //request.ContentLength = flussoInByte.Length;
                //request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FTPUser"], ConfigurationManager.AppSettings["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);

                Log("Aggiornamento tabella Gestione_PDF_FTP");

                DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, ConfigurationManager.AppSettings["SP_GESTIONE_UPDATE_ZIP"], parametri);

                if (Directory.Exists(path)) {

                    Log(string.Format("Inizio eliminazione cartella {0}", path));
                    Directory.Delete(path, true);
                    Log(string.Format("Fine eliminazione cartella {0}", path));
                }

                //FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Log(ex.Message);
            }
        }

        // 20181017 AC Utilizzo del metodo già utilizzato nella versione V1Final
        private static void CopiaInLocale(int idZip, string nomeCartella, string fileName, string extension)
        {
            string tipoInvio = ConfigurationManager.AppSettings["TIPO_INVIO"];
            string inputPath = (tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["pathZIP"] : ConfigurationManager.AppSettings["pathZIP_PERIODICO"];
            string outputPath = (tipoInvio.ToUpper() == "G") ? ConfigurationManager.AppSettings["path_OUTPUT_ZIP"] : ConfigurationManager.AppSettings["path_OUTPUT_ZIP_PERIODICO"];
            if (!Directory.Exists(outputPath))
                Directory.CreateDirectory(outputPath);
            if (!fileName.ToLower().Contains(extension)) //".zip
                fileName += extension;// ".zip";
            string[] files = Directory.GetFiles(inputPath, fileName);
            string temp;
            foreach (string file in files)
            {
                temp = file.Replace(inputPath, outputPath);
                File.Copy(file, temp, false);
            }

            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, ConfigurationManager.AppSettings["SP_GESTIONE_UPDATE_ZIP"], parametri);

            Directory.Delete(nomeCartella, true);
        }

        //public static void Log(string message, bool date = false)
        //{
        //    string logFile = string.Concat(logPath, "log.txt");

        //    if (date)
        //        message = string.Format("{0}{1}{2} {3}", "[", DateTime.Now.ToLongDateString(), "]", message);
        //    else
        //        message = string.Format("{0}{1}{2} {3}", "[", DateTime.Now.ToLongTimeString(), "]", message);

        //    using (FileStream fileLog = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Write))
        //    {
        //        using (var streamWriter = new StreamWriter(fileLog))
        //        {
        //            streamWriter.WriteLine(message);
        //        }
        //    }
        //}

        public static void Log(string message, bool date = false)
        {
            string logFile = string.Concat(logPath, "log.txt");

            if (date)
                message = string.Format("{0}{1}{2} {3}", "[", DateTime.Now.ToLongDateString(), "]", message);
            else
                message = string.Format("{0}{1}{2} {3}", "[", DateTime.Now.ToLongTimeString(), "]", message);

            using (FileStream fileLog = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Write))
            {
                using (var streamWriter = new StreamWriter(fileLog))
                {
                    streamWriter.WriteLine(message);
                }
            }
        }
    }
}