using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using DevExpress.Data;
using DevExpress.Web;
using System.Reflection;
using System.IO;
using System.Data.SqlClient;
using System.Net;
using System.Threading;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using PdfSharp.Pdf;
using System.Web.UI;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Text;
using PdfSharp.Drawing;
using MySqlConnector;

namespace OlympiaIntranet
{
    public class CommonClass
    {
        public static DataTable GetGestori()
        {
            string query = "GDN_GetGestore";

            using (SqlConnection conn = new SqlConnection(OlympiaIntranet.Properties.Settings.Default.SqlConnection))
            {
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        return dt;
                    }
                }
            }
        }

        public static void SqlBulkCopyTable(Page page, DataTable dt, string sqlTable)
        {
            //var table = "Events";
            using (var conn = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = sqlTable };
                bulkCopy.BulkCopyTimeout = 6000;
                conn.Open();
                var schema = conn.GetSchema("Columns", new[] { null, null, sqlTable, null });
                foreach (DataColumn schemaColumn in dt.Columns)
                {
                    foreach (DataRow row in schema.Rows)
                    {
                        if (string.Equals(schemaColumn.ColumnName, (string)row["COLUMN_NAME"], StringComparison.OrdinalIgnoreCase))
                        {
                            bulkCopy.ColumnMappings.Add(schemaColumn.ColumnName, (string)row["COLUMN_NAME"]);
                            break;
                        }
                    }
                }
                try
                {
                    bulkCopy.WriteToServer(dt);
                }
                catch (Exception ex)
                {
                    CommonClass.MessageBox(page, ex.Message);
                }
            }
        }

        public static DataTable execQuery_Datatable_MySql(string query, string connectionString)
        {
            MySqlDataReader result;
            DataTable dt = new DataTable();
            using (var con = new MySqlConnection(connectionString))
            {
                var cmd = new MySqlCommand
                {
                    CommandText = query,
                    CommandType = CommandType.Text,
                    Connection = con
                };
                cmd.CommandTimeout = 0;
                con.Open(); // Open the MySqlConnection.
                result = cmd.ExecuteReader();
                dt.Load(result);
            }
            return (dt);
        }
        //public static DataTable execQuery_Datatable_Sql(string storedProc, 
        //                                                string connectionString, 
        //                                                string Gestore = "", 
        //                                                string Consulente = "", 
        //                                                string Linea = "", 
        //                                                int FiltroRanking = -1 , 
        //                                                int TipoRanking = -1, 
        //                                                DateTime? DataIns = null, 
        //                                                string TipoAttivita = "", 
        //                                                string Societa = "", 
        //                                                DateTime? MeseRiferimento = null)
        //{
        //    SqlDataReader result;
        //    DataTable dt = new DataTable();
        //    using (var con = new SqlConnection(connectionString))
        //    {
        //        var cmd = new SqlCommand
        //        {
        //            CommandText = storedProc,
        //            CommandType = CommandType.StoredProcedure,
        //            Connection = con
        //        };
        //        cmd.CommandTimeout = 600;
        //        if (String.IsNullOrEmpty(Gestore) == false) cmd.Parameters.Add("@cod_ges", SqlDbType.VarChar).Value = Gestore;
        //        if (String.IsNullOrEmpty(Consulente) == false) cmd.Parameters.Add("@cod_pro", SqlDbType.VarChar).Value = Consulente;
        //        if (String.IsNullOrEmpty(Linea) == false) cmd.Parameters.Add("@cod_lin", SqlDbType.VarChar).Value = Linea;
        //        if (DataIns != null) cmd.Parameters.Add("@data_ins", SqlDbType.Date).Value = DataIns;
        //        if (FiltroRanking != -1) cmd.Parameters.Add("@FiltroRanking", SqlDbType.Int).Value = FiltroRanking;
        //        if (TipoRanking != -1) cmd.Parameters.Add("@TipoRanking", SqlDbType.Int).Value = TipoRanking;
        //        if (String.IsNullOrEmpty(TipoAttivita) == false) cmd.Parameters.Add("@TipoAttivita", SqlDbType.VarChar).Value = TipoAttivita;
        //        if (String.IsNullOrEmpty(Societa) == false) cmd.Parameters.Add("@Societa", SqlDbType.VarChar).Value = Societa;
        //        if (MeseRiferimento != null) cmd.Parameters.Add("@MeseRiferimento", SqlDbType.Date).Value = MeseRiferimento;
        //        con.Open(); // Open the SqlConnection.
        //        result = cmd.ExecuteReader();
        //        dt.Load(result);
        //    }
        //    return (dt);
        //}
        public static DataTable execQuery_Datatable_Sql(string storedProc,
                                                        string connectionString,
                                                        string Gestore = "",
                                                        string Consulente = "",
                                                        string Linea = "",
                                                        int FiltroRanking = -1,
                                                        int TipoRanking = -1,
                                                        DateTime? DataIns = null,
                                                        string TipoAttivita = "",
                                                        string Societa = "",
                                                        DateTime? MeseRiferimento = null,
                                                        string Advisor = "",
                                                        string Titolo = "")
        {
            SqlDataReader result;
            DataTable dt = new DataTable();
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = storedProc,
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.CommandTimeout = 600;
                if (String.IsNullOrEmpty(Gestore) == false) cmd.Parameters.Add("@cod_ges", SqlDbType.VarChar).Value = Gestore;
                if (String.IsNullOrEmpty(Consulente) == false) cmd.Parameters.Add("@cod_pro", SqlDbType.VarChar).Value = Consulente;
                if (String.IsNullOrEmpty(Linea) == false) cmd.Parameters.Add("@cod_lin", SqlDbType.VarChar).Value = Linea;
                if (DataIns != null) cmd.Parameters.Add("@data_ins", SqlDbType.Date).Value = DataIns;
                if (FiltroRanking != -1) cmd.Parameters.Add("@FiltroRanking", SqlDbType.Int).Value = FiltroRanking;
                if (TipoRanking != -1) cmd.Parameters.Add("@TipoRanking", SqlDbType.Int).Value = TipoRanking;
                if (String.IsNullOrEmpty(TipoAttivita) == false) cmd.Parameters.Add("@TipoAttivita", SqlDbType.VarChar).Value = TipoAttivita;
                if (String.IsNullOrEmpty(Societa) == false) cmd.Parameters.Add("@Societa", SqlDbType.VarChar).Value = Societa;
                if (MeseRiferimento != null) cmd.Parameters.Add("@MeseRiferimento", SqlDbType.Date).Value = MeseRiferimento;
                if (String.IsNullOrEmpty(Advisor) == false) cmd.Parameters.Add("@cod_adv", SqlDbType.VarChar).Value = Advisor;
                if (String.IsNullOrEmpty(Titolo) == false) cmd.Parameters.Add("@Titolo", SqlDbType.VarChar).Value = Titolo;
                con.Open(); // Open the SqlConnection.
                result = cmd.ExecuteReader();
                dt.Load(result);
            }
            return (dt);
        }

        public static string ExecSql(string proc, string Param1 = "", string Param2 = "", string Param3 = "", string Param4 = "", string Param5 = "")
        {
            string result;
            using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmd = new SqlCommand
                {
                    CommandText = proc,
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                if (proc == "monitorVaR_LoadData1") // Se viene chiamata da MonitorVaR allora passa i parametri anche se vuoti , altrimenti schianta!!
                {
                    //cmd.Parameters.Add("@gruppo", SqlDbType.VarChar).Value = Param1;
                    //cmd.Parameters.Add("@linea", SqlDbType.VarChar).Value = Param2;
                    //cmd.Parameters.Add("@gestore", SqlDbType.VarChar).Value = Param3;
                    //cmd.Parameters.Add("@advisor", SqlDbType.VarChar).Value = Param4;
                    //cmd.Parameters.Add("@consulente", SqlDbType.VarChar).Value = Param5;
                    cmd.Parameters.Add("@gestore", SqlDbType.VarChar).Value = Param1;
                    cmd.Parameters.Add("@linea", SqlDbType.VarChar).Value = Param2;
                }
                if (proc.Contains("GDN_EsposizioneTitoli_Rating") == true) // se viene chiamata da GDN_EsposizioneTitoli_RatingX allora passa il cod_tit altrimenti schianta!!
                {
                    cmd.Parameters.Add("@cod_tit", SqlDbType.VarChar).Value = Param1;
                    cmd.Parameters.Add("@TipoRanking", SqlDbType.Int).Value = Convert.ToInt16(Param2);
                }
                con.Open(); // Open the SqlConnection.
                result = cmd.ExecuteScalar().ToString();
            }
            return (result);
        }

        public static void SetColumnVisibility (ASPxGridView grid, bool visibility, string columnName)
        {
            if (visibility == true) grid.DataColumns[columnName].EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.True;
            if (visibility == false) grid.DataColumns[columnName].EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.False;

        }

        public static bool IsIsinValid(string isin)
        {
            isin = isin.Trim().ToUpper();
            Regex r = new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$");
            if (!r.IsMatch(isin))
            {
                return false;
            }

            StringBuilder sb = new StringBuilder();
            foreach (char c in isin.Substring(0, 12))
            {
                sb.Append(Digit(c, 36));
            }

            return LuhnTest(sb.ToString());
        }
        static int DigitValue(char c, int b)
        {
            if (c >= '0' && c <= '9')
            {
                return c - '0';
            }
            return c - 'A' + 10;
        }

        static int Digit(char c, int b)
        {
            int result = DigitValue(c, b);
            if (result >= b)
            {
                Console.Error.WriteLine("Invalid Number");
                return -1;
            }
            return result;
        }
        static string ReverseString(string input)
        {
            char[] intermediate = input.ToCharArray();
            Array.Reverse(intermediate);
            return new string(intermediate);
        }

        static bool LuhnTest(string number)
        {
            int s1 = 0;
            int s2 = 0;
            string reverse = ReverseString(number);
            for (int i = 0; i < reverse.Length; i++)
            {
                int digit = Digit(reverse[i], 10);
                //This is for odd digits, they are 1-indexed in the algorithm.
                if (i % 2 == 0)
                {
                    s1 += digit;
                }
                else
                { // Add 2 * digit for 0-4, add 2 * digit - 9 for 5-9.
                    s2 += 2 * digit;
                    if (digit >= 5)
                    {
                        s2 -= 9;
                    }
                }
            }

            return (s1 + s2) % 10 == 0;
        }

        public static string SincronizzaInCedLab(string linkApi)
        {
            string callPage = string.Empty;
            string response = "";
            try
            {                
                using (WebClient web = new WebClient())
                {
                    callPage = web.DownloadString(linkApi);
                }
                if (callPage.IndexOf("STATUSCODE : OK") != -1)
                {
                    int posStart = callPage.IndexOf("STATUSCODE : START") + 18;
                    int posEnd = callPage.IndexOf("STATUSCODE : OK");
                    response = callPage.Substring(posStart, posEnd - posStart).Replace(System.Environment.NewLine, @"\n");                   
                }
                
                if (callPage.IndexOf("Eccezione rilevata") != -1)
                {
                    int posStart = callPage.IndexOf("Eccezione rilevata :") + 20;
                    int posEnd = callPage.IndexOf("@");
                    response = callPage.Substring(posStart, posEnd - posStart);
                    string error = response.Replace(System.Environment.NewLine, @"\n"); // rimpiazzo \r\n con \\n che viene 'digerito' da javascript nell'alert
                    return (error);
                }

                return (response);
            }
            catch (Exception ex)
            {
                return (ex.Message);
            }
        }

        public static void SendEmail(string msgBody, string msgSubject = "", string msgFrom = "")
        {
            var mailFrom = "info@gl-software.it";
            var mailTo = "glicciardello@gmail.com";
            //var mailTo1 = "federico.costalonga@gmail.com";
            var host = "mail.gl-software.it";
            var user = "gl-software.it";
            var pass = "kohriwoo";
            //var ComputerName = System.Environment.MachineName;
            //int port = 0;

            //if (ComputerName == "DELL-NOTEBOOK") port = 587; // dal notebook usa porta 587
            //else port = 25; // dal server usa porta 25

            // Invio email tramite .Net 
            using (MailMessage message = new MailMessage())//  msgFrom, DestMail, tbOggetto.Text, htmlBody))
            {
                message.From = new MailAddress(mailFrom, msgFrom);
                message.To.Add(new MailAddress(mailTo));
                //if (!isDebug) message.To.Add(new MailAddress(mailTo1)); // invia mail a Fede solo se non è in debug mode!
                message.IsBodyHtml = true;
                message.Body = msgBody;
                message.Subject = msgSubject;

                using (SmtpClient client = new SmtpClient(host))
                {
                    client.Port = 25;
                    client.EnableSsl = false;
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(user, pass);
                    client.Send(message);
                }
            }
        }

        public static void MessageBox(System.Web.UI.Page page, string strMsg)
        {
            //+ character added after strMsg "')"
            ScriptManager.RegisterClientScriptBlock(page,page.GetType(), "alertMessage", "alert('" + strMsg.Replace("'", string.Empty) + "')", true);

        }

        public static void CopyPages(PdfDocument from, PdfDocument to)
        {
            for (int i = 0; i < from.PageCount; i++)
            {
                to.AddPage(from.Pages[i]);
            }
        }

        public static DateTime AddBusinessDays(DateTime date, int days)
        {
            int d = 4 - Math.Sign(days) * (4 - ((int)date.DayOfWeek + 1)); //SET @d = 4 - SIGN(@n) * (4 - DATEPART(DW, @Date)); Aggiunto uno a DayOfWeek perchè in C# Sunday = 0 mentre in sql DATEPART(dw,..) Sunday = 1
            DateTime returnDate = date.AddDays(days + ((Math.Abs(days) + d - 2) / 5) * 2 * Math.Sign(days) - d / 7); // DATEADD(D, @n + ((ABS(@n) + @d - 2) / 5) * 2 * SIGN(@n) - @d / 7, @Date);
            return (returnDate);
        }

        public static string CallWebApi(string linkApi)
        {
            // Create a request for the URL.   
            WebRequest request = WebRequest.Create(linkApi);
            request.Timeout = 60 * 1000; // 60 secondi timeout
            // If required by the server, set the credentials.  
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.  
            WebResponse response = request.GetResponse();
            // Display the status.  
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.  
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.  
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            // Display the content.  
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.  
            reader.Close();
            response.Close();
            return (responseFromServer);
        }
        public static bool IsValidJson(string strInput)
        {
            strInput = strInput.Trim();
            if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
                (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
            {
                try
                {
                    var obj = JToken.Parse(strInput);
                    //ScriveLog("BBG Service OK!");
                    return true;
                }
                catch (JsonReaderException )
                {
                    //Exception in parsing json
                    //ScriveLog(string.Format(" Error (JsonReaderException) from BBGservice : {0} {1}", jex.Message, jex.InnerException));
                    return false;
                }
                catch (Exception ) //some other exception
                {
                    //Console.WriteLine(ex.ToString());
                    //ScriveLog(string.Format(" Error (Exception) from BBGservice : {0} {1}", ex.Message, ex.InnerException));
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static void SaveHits(int idSite, int hits, string user = "")
        {
            using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "SaveHits1",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                if (idSite == 0) cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = "ROMA";
                if (idSite == 1) cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = "LONDRA";                
                cmd.Parameters.Add("@hits", SqlDbType.Int).Value = hits;
                cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = user;
                con.Open(); // Open the SqlConnection.
                cmd.ExecuteNonQuery();
            }
        }

        // Verifica server bbg sia online prendendo dalla lista server in tabella BBGServer
        // Restituisce l'ip:porta del server attivo altrimenti N/A
        public static string[] IsBBGServiceOnline()
        {
            string[] result = new string[2];
            result[0] = QueryBBGService("ROMA");
            result[1] = QueryBBGService("LONDRA");
            return (result);
        }

        public static int CheckHitsManuali(string Site)
        {
            int result = 0;
            using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "hits_TotalHitsManuali",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = Site;
                //cmd.Parameters.Add("@utente", SqlDbType.VarChar).Value = utente;
                con.Open(); // Open the SqlConnection.
                result = (int)cmd.ExecuteScalar(); 
            }
            return (result);
        }

        public static string QueryBBGService(string site)
        {
            DataTable serverlistTable = null;
            // Rileva elenco server BBG disponibili
            using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "bbg_ServerList1",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = site;
                con.Open(); // Open the SqlConnection.
                SqlDataReader result = cmd.ExecuteReader();
                serverlistTable = new DataTable();
                serverlistTable.Load(result);
            }
            // Test per verificare che BBG Service sia attivo e raggiungibile...
            bool callEsito = false;
            string testjson = "";
            string jsonString = "";
            string ActualServerIP = "";
            foreach (DataRow serverRow in serverlistTable.Rows)
            {
                if (callEsito == true) break; // esce se il server ha risposto al precedente IP

                if (!String.IsNullOrEmpty(serverRow["Port"].ToString())) ActualServerIP = serverRow["IP"].ToString() + ":" + serverRow["Port"].ToString();
                else ActualServerIP = serverRow["IP"].ToString();

                int callNum = 1;
                while (callNum < 5 && callEsito == false) // Effettua 5 tentativi per ogni server in lista
                {
                    testjson = string.Format("http://{0}/api/bbgservicehst?security=XS1431873659@ETLX%20Corp&field=PX_LAST&startDate=20170331&endDate=20170331&type=json", ActualServerIP);
                    using (WebClient web = new WebClient())
                    {
                        try
                        {
                            jsonString = web.DownloadString(testjson);
                            Console.WriteLine(string.Format("Test N°{0} connessione a BBG Service...", callNum));
                            //ScriveLog(string.Format("Test N°{0} connessione a BBG Service...", callNum));
                        }
                        catch (Exception)
                        {
                            //ScriveLog(string.Format("Errore connessione Test N°{0} a BBG Service - ErrMsg {1} - InnerMsg {2} - jsonResult {3}", callNum, e.Message, e.InnerException, jsonString));
                            jsonString = "";
                            callNum++;
                            Thread.Sleep(1000); // aspetta 1 secondo e poi riscarica i dati...
                        }
                        if (!String.IsNullOrEmpty(jsonString)) callEsito = true; // esce se riesce a connettersi a BBG Service...                    
                    }
                }
            }
            if (callEsito == false) return ("N/A");
            else return (ActualServerIP);
        }
        //public static string IsBBGServiceOnline(string logFileName)
        //{
        //    DataTable serverlistTable = null;
        //    // Rileva elenco server BBG disponibili
        //    using (var con = new SqlConnection(Properties.Settings.Default.DBSettings))
        //    {
        //        var cmd = new SqlCommand
        //        {
        //            CommandText = "bbg_ServerList",
        //            CommandType = CommandType.StoredProcedure,
        //            Connection = con
        //        };
        //        con.Open(); // Open the SqlConnection.
        //        SqlDataReader result = cmd.ExecuteReader();
        //        serverlistTable = new DataTable();
        //        serverlistTable.Load(result);
        //    }
        //    // Test per verificare che BBG Service sia attivo e raggiungibile...

        //    bool callEsito = false;
        //    string testjson = "";
        //    string jsonString = "";
        //    string ActualServerIP = "";
        //    foreach (DataRow serverRow in serverlistTable.Rows)
        //    {
        //        if (callEsito == true) break; // esce se il server ha risposto al precedente IP

        //        if (!String.IsNullOrEmpty(serverRow["Port"].ToString())) ActualServerIP = serverRow["IP"].ToString() + ":" + serverRow["Port"].ToString();
        //        else ActualServerIP = serverRow["IP"].ToString();

        //        int callNum = 1;
        //        while (callNum < 20 && callEsito == false) // Effettua 20 tentativi per ogni server in lista
        //        {
        //            testjson = string.Format("http://{0}/api/bbgservicehst?security=XS1431873659@ETLX%20Corp&field=OPEN,PX_BID,PX_ASK,PX_OPEN,PX_LAST&startDate=20170331&endDate=20170331&type=json", ActualServerIP);
        //            using (WebClient web = new WebClient())
        //            {
        //                try
        //                {
        //                    jsonString = web.DownloadString(testjson);
        //                    //Console.WriteLine(string.Format("Test N°{0} connessione a BBG Service...", callNum));
        //                    //ScriveLog(string.Format("Test N°{0} connessione a BBG Service...", callNum));
        //                }
        //                catch (Exception e)
        //                {
        //                    //ScriveLog(string.Format("Errore connessione Test N°{0} a BBG Service - ErrMsg {1} - InnerMsg {2} - jsonResult {3}", callNum, e.Message, e.InnerException, jsonString));
        //                    jsonString = "";
        //                    callNum++;
        //                    Thread.Sleep(1000); // aspetta 1 secondo e poi riscarica i dati...
        //                }
        //                if (!String.IsNullOrEmpty(jsonString)) callEsito = true; // esce se riesce a connettersi a BBG Service...                    
        //            }
        //        }
        //    }
        //    if (callEsito == false) return ("N/A");
        //    else return (ActualServerIP);

        //}

        public static double[] shiftArray(double[] list, int m)
        {

            var from = 0;
            var val = list[from];
            var nextGroup = 1;
            for (int i = 0; i < list.Length; i++)
            {
                var to = ((from - m) + list.Length) % list.Length;
                if (to == from)
                    break;

                var temp = list[to];
                list[to] = val;
                from = to;
                val = temp;

                if (from < nextGroup)
                {
                    from = nextGroup++;
                    val = list[from];
                }
            }
            return (list);
        }

        public static string CreaBuildNumber()
        {
            DateTime compiledOn = File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location);
            string result = "Build version "+compiledOn.ToString("ddMMyyyy.HHmm")+" - DE 18.1.6";
            return (result);
        }

        public static void CreaColonna(ASPxGridView webGrid, string tipoCol, string nomeCampo, ref int ordineColonna, bool applicaFormattazione=true)
        {
            webGrid.Columns.Remove(webGrid.Columns[nomeCampo]); // Rimuove colonna prima di crearla
            if (tipoCol== "Text")
            {
                var col = new GridViewDataTextColumn() { FieldName = nomeCampo };
                if (ordineColonna == 0) webGrid.TotalSummary.Add(SummaryItemType.Count, nomeCampo).DisplayFormat = "n0";
                if (applicaFormattazione) col.PropertiesTextEdit.DisplayFormatString = "n2";
                col.VisibleIndex = ordineColonna;
                webGrid.Columns.Add(col);
            }
            if (tipoCol == "Date")
            {
                var col = new GridViewDataDateColumn() { FieldName = nomeCampo };
                col.PropertiesDateEdit.DisplayFormatString = "dd/MM/yyyy";
                col.VisibleIndex = ordineColonna;
                webGrid.Columns.Add(col);
            }
            ordineColonna++;
        }

        public static void SettaFormatiNumerici()
        {
            CultureInfo newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            newCulture.NumberFormat.NumberGroupSeparator = ".";
            newCulture.NumberFormat.NumberDecimalSeparator = ",";

            System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;
        }

        public static void SettaWebGrid(ASPxGridView webgrid, bool showAll=true)
        {
            if (!showAll)
            {
                webgrid.SettingsPager.Mode = GridViewPagerMode.ShowPager;
                webgrid.SettingsPager.PageSize = 20;
                webgrid.SettingsPager.PageSizeItemSettings.ShowAllItem = true;
                webgrid.Settings.ShowGroupPanel = true;
                webgrid.Settings.ShowFilterRow = true; 
                webgrid.Settings.ShowFooter = true;
                webgrid.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;
                webgrid.Settings.ShowHeaderFilterButton = true;
                //webgrid.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;
                //webgrid.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.HideDataCells;
                //webgrid.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = true;                
                webgrid.Theme = "MetropolisBlue";
            }
            else
            {
                webgrid.SettingsPager.Mode = GridViewPagerMode.ShowAllRecords;
                webgrid.Settings.ShowGroupPanel = false;
                webgrid.Settings.ShowFilterRow = false;
                webgrid.Settings.ShowFooter = false;
                //webgrid.Theme = "Moderno";
                webgrid.Theme = "MetropolisBlue";
            }
        }

        public static void SetColumnFilterContains(ASPxGridView grid)
        {
            // Abilita in tutte le colonne di default la ricerca con 'Contains'             
            for (int i = 0; i < Math.Min(grid.VisibleRowCount, grid.Columns.Count); i++)
            {
                GridViewDataColumn col = (grid.Columns[i]) as GridViewDataColumn;
                if (col != null) col.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
            }
        }

        public static void CustomDataBind(string tipo,ASPxGridView webgrid, string sp, Label label, string testolabel, bool usaParametri=true)
        {            
            //var sqlDS = new SqlDataSource
            //{
            //    ConnectionString = Properties.Settings.Default.DBSettings,
            //    SelectCommandType = SqlDataSourceCommandType.StoredProcedure,
            //    SelectCommand = sp
            //};
            //if (usaParametri)
            //{
            //    var sqlParam = new Parameter("Filter", DbType.String, tipo);
            //    sqlDS.SelectParameters.Add(sqlParam);

            //    switch (tipo)
            //    {
            //        case "P":
            //            label.Text = testolabel + " (Utenti Public)";
            //            break;
            //        case "F":
            //            label.Text = testolabel + " (Utenti Full)";
            //            break;
            //        case "C":
            //            label.Text = testolabel + " (Utenti Customer)";
            //            break;
            //        case "R":
            //            label.Text = testolabel + " (Utenti Registered)";
            //            break;
            //    }
            //}
            //webgrid.DataSource = sqlDS;
            //webgrid.DataBind();
        }

        public static void SalvaLogSync(string paramCall, string paramUtente)
        {
            using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.logsync_Ins",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("Call", SqlDbType.VarChar).Value = paramCall;
                cmd.Parameters.Add("Utente", SqlDbType.VarChar).Value = paramUtente;
                con.Open(); // Open the SqlConnection.
                cmd.ExecuteNonQuery();
            }
        }

        public static string SQLProc(string proc, string date = "", int idSite = -1)
        {
            string result;
            using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmd = new SqlCommand
                {
                    CommandText = proc,
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                if (String.IsNullOrEmpty(date) == false) cmd.Parameters.Add("@Date", SqlDbType.Date).Value = Convert.ToDateTime(date);
                if (idSite == 0) cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = "ROMA";
                if (idSite == 1) cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = "LONDRA";
                con.Open(); // Open the SqlConnection.
                result = cmd.ExecuteScalar().ToString();
            }
            return (result);
        }

        public static void DrawImage(XGraphics gfx, string jpegFileNamePath, int x, int y, int width, int height)
        {
            XImage image = XImage.FromFile(jpegFileNamePath);
            gfx.DrawImage(image, x, y, width, height);
        }
    }
}