using DevExpress.Export;
using DevExpress.XtraPrinting;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using System.Drawing;
using System.Data.SqlClient;
using System.Collections;
using System.Text;
using MySqlConnector;

namespace OlympiaIntranet
{
    public partial class Mifir : System.Web.UI.Page
    {
        DataTable dtOutputExcel;
        DataTable dtDatiUBS;
        //DataTable dtProcessedCSV;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                Response.Redirect("~/SignIn.aspx");
            }

            if (Session["DatiUBS"] != null)
            {
                gvDatiUBS.DataSource = (DataTable)Session["DatiUBS"];
                gvDatiUBS.DataBind();
            }
            if (Session["outputTable"] != null)
            {
                gvOuputExcel.DataSource = (DataTable)Session["outputTable"];
                gvOuputExcel.DataBind();
            }

            if (!IsPostBack) dateeditBancaSella.Date = DateTime.Now.Date; // setta la data odierna solo la prima volta, se è un postback no altrimenti se viene cambiata la data poi la risetta a oggi
        }

        // ref link: https://github.com/DevExpress-Examples/bind-a-grid-to-a-datatable-via-code-e168
        private DataTable ProcessaInputDatiUBS()
        {
            lblError.Text = "";

            // dtDatiUBS è popolata in evento ASPxUploadControl1_FileUploadComplete in Session["DatiUBS"]
            DataTable dtDatiUBS = new DataTable();
            dtDatiUBS = (DataTable)Session["DatiUBS"];
            if (dtDatiUBS.Rows.Count > 0)
            {
                // Aggiunge colonna a dt 
                DataTable dt = new DataTable();
                foreach (DataColumn column in dtDatiUBS.Columns)
                {
                    dt.Columns.Add(column.ColumnName);
                }
                dt.Columns.Add("PROC1"); // Colonna che conterrà elaborazione procedura1
                dt.Columns.Add("KeyID"); // Colonna che conterrà primary key 
                dt.PrimaryKey = new DataColumn[] { dt.Columns["KeyID"] }; // setta primary key per datatable dt

                // Aggiunge righe a dt e per ogni riga esegue una select
                int keyID = 1; // chiave primaria per dt 
                foreach (DataRow row in dtDatiUBS.Rows)
                {
                    DataRow dr = dt.NewRow();
                    using (var con = new SqlConnection(Properties.Settings.Default.SqlConnection))
                    {
                        SqlCommand cmd = con.CreateCommand();
                        //string query = string.Format("SELECT distinct tra.cod_ope from tra LEFT JOIN tit ON tra.cod_tit=tit.cod_tit WHERE  tit.cod_isin ='{0}' AND  ABS(tra.qta)={1} AND  tra.data_ope > date_sub(CURDATE(), INTERVAL 10  DAY) and tra.cod_ope in ('B','S')", row["TAG_41"], row["TAG_30"]);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "mifir_UBS_codope";
                        cmd.Parameters.Add("@ISIN", SqlDbType.VarChar).Value = row["TAG_41"];
                        cmd.Parameters.Add("@Qta", SqlDbType.Int).Value = row["TAG_30"];
                        con.Open(); // Open the SqlConnection.
                        SqlDataReader dataReader = cmd.ExecuteReader();
                        var dtResult = new DataTable();
                        dtResult.Load(dataReader);
                        if (dtResult.Rows.Count == 1) dr["PROC1"] = dtResult.Rows[0][0].ToString(); // 'S' o 'B'
                        else dr["PROC1"] = "";
                    }
                    int col = 0;
                    foreach (var item in row.ItemArray)
                    {
                        dr[col] = item;
                        col++;
                    }
                    dr["KeyID"] = keyID;
                    dt.Rows.Add(dr);
                    keyID++;
                }
                if (dt != null)
                {
                    Session["DatiUBS"] = dt;
                    gvDatiUBS.DataSource = dt;

                    // Aggiunge colonne a gvInputCSV
                    gvDatiUBS.Columns.Clear();
                    foreach (DataColumn column in dtDatiUBS.Columns)
                    {
                        GridViewDataColumn c = new GridViewDataColumn();
                        c.FieldName = column.ColumnName;
                        gvDatiUBS.Columns.Add(c);
                    }
                    GridViewDataColumn d = new GridViewDataColumn();
                    d.FieldName = "PROC1";
                    gvDatiUBS.Columns.Add(d);
                    GridViewDataColumn e = new GridViewDataColumn();
                    e.FieldName = "KeyID";
                    gvDatiUBS.Columns.Add(d);
                    gvDatiUBS.KeyFieldName = "KeyID";
                    GridViewCommandColumn cc = new GridViewCommandColumn();
                    gvDatiUBS.Columns.Add(cc);
                    cc.ShowEditButton = true;
                    cc.ShowNewButton = false;
                    cc.ShowDeleteButton = false;
                    cc.ShowCancelButton = true;
                    cc.ShowUpdateButton = true;

                    gvDatiUBS.DataBind();
                }
                return (dt);
            }
            else
            {
                lblError.Text = "CSV non rilevato!";
                return (null);
            }
        }

        private DataTable CreateOutputDataTable()
        {
            // Crea struttura datatable per output file
            DataTable dtOutput = new DataTable();
            dtOutput.Columns.Add("Report Status");
            dtOutput.Columns.Add("Transaction Reference Number");
            dtOutput.Columns.Add("Venue Transaction ID");
            dtOutput.Columns.Add("Submitting Entity ID");
            dtOutput.Columns.Add("Executing Entity ID");
            dtOutput.Columns.Add("Investment Firm Indicator");
            dtOutput.Columns.Add("Buyer ID Type");
            dtOutput.Columns.Add("Buyer ID Sub Type");
            dtOutput.Columns.Add("Buyer ID");
            dtOutput.Columns.Add("Buyer Country of Branch");
            dtOutput.Columns.Add("Buyer First Name");
            dtOutput.Columns.Add("Buyer Surname");
            dtOutput.Columns.Add("Buyer DOB");
            dtOutput.Columns.Add("Buyer Decision Maker ID Type");
            dtOutput.Columns.Add("Buyer Decision Maker ID Sub Type");
            dtOutput.Columns.Add("Buyer Decision Maker ID");
            dtOutput.Columns.Add("Buyer Decision Maker First Name");
            dtOutput.Columns.Add("Buyer Decision Maker Surname");
            dtOutput.Columns.Add("Buyer Decision Maker DOB");
            dtOutput.Columns.Add("Seller ID Type");
            dtOutput.Columns.Add("Seller ID Sub Type");
            dtOutput.Columns.Add("Seller ID");
            dtOutput.Columns.Add("Seller Country of Branch");
            dtOutput.Columns.Add("Seller First Name");
            dtOutput.Columns.Add("Seller Surname");
            dtOutput.Columns.Add("Seller DOB");
            dtOutput.Columns.Add("Seller Decision Maker ID Type");
            dtOutput.Columns.Add("Seller Decision Maker ID Sub Type");
            dtOutput.Columns.Add("Seller Decision Maker ID");
            dtOutput.Columns.Add("Seller Decision Maker First Name");
            dtOutput.Columns.Add("Seller Decision Maker Surname");
            dtOutput.Columns.Add("Seller Decision Maker DOB");
            dtOutput.Columns.Add("Order Transmission Indicator");
            dtOutput.Columns.Add("Buyer Transmitter ID");
            dtOutput.Columns.Add("Seller Transmitter ID");
            dtOutput.Columns.Add("Trading Date Time");
            dtOutput.Columns.Add("Trading Capacity");
            dtOutput.Columns.Add("Quantity");
            dtOutput.Columns.Add("Quantity Type");
            dtOutput.Columns.Add("Quantity Currency");
            dtOutput.Columns.Add("Derivative Notional Change");
            dtOutput.Columns.Add("Price");
            dtOutput.Columns.Add("Price Type");
            dtOutput.Columns.Add("Price Currency");
            dtOutput.Columns.Add("Net Amount");
            dtOutput.Columns.Add("Venue");
            dtOutput.Columns.Add("Country of Branch");
            dtOutput.Columns.Add("Up-Front Payment");
            dtOutput.Columns.Add("Up-Front Payment Currency");
            dtOutput.Columns.Add("Complex Trade Component ID");
            dtOutput.Columns.Add("Instrument ID");
            dtOutput.Columns.Add("Instrument ID Type");
            dtOutput.Columns.Add("Instrument Name");
            dtOutput.Columns.Add("Instrument Classification");
            dtOutput.Columns.Add("Notional Currency 1");
            dtOutput.Columns.Add("Notional Currency 2");
            dtOutput.Columns.Add("Notional Currency 2 Type");
            dtOutput.Columns.Add("Price Multiplier");
            dtOutput.Columns.Add("UV Instrument Classification");
            dtOutput.Columns.Add("Underlying Instrument ID");
            dtOutput.Columns.Add("UV Index Classification");
            dtOutput.Columns.Add("Underlying Index ID");
            dtOutput.Columns.Add("Underlying Index Name");
            dtOutput.Columns.Add("Underlying Index Term");
            dtOutput.Columns.Add("Option Type");
            dtOutput.Columns.Add("Strike Price");
            dtOutput.Columns.Add("Strike Price Type");
            dtOutput.Columns.Add("Strike Price Currency");
            dtOutput.Columns.Add("Option Style");
            dtOutput.Columns.Add("Maturity Date");
            dtOutput.Columns.Add("Expiry Date");
            dtOutput.Columns.Add("Delivery Type");
            dtOutput.Columns.Add("Investment Decision ID Type");
            dtOutput.Columns.Add("Investment Decision ID Sub Type");
            dtOutput.Columns.Add("Investment Decision ID");
            dtOutput.Columns.Add("Investment Decision Country of Branch");
            dtOutput.Columns.Add("Firm Execution ID Type");
            dtOutput.Columns.Add("Firm Execution ID Sub Type");
            dtOutput.Columns.Add("Firm Execution ID");
            dtOutput.Columns.Add("Firm Execution Country of Branch");
            dtOutput.Columns.Add("Waiver Indicator");
            dtOutput.Columns.Add("Short Selling Indicator");
            dtOutput.Columns.Add("OTC Post Trade Indicator");
            dtOutput.Columns.Add("Commodity Derivative Indicator");
            dtOutput.Columns.Add("SFT Indicator");
            dtOutput.Columns.Add("Internal Client Identification");
            dtOutput.Columns.Add("Data Category");

            return (dtOutput);

        }

        protected void btnCreaOutput_Click(object sender, EventArgs e)
        {
            // Salva csv in db tabella MifirReport
            SqlBulkCopyTable((DataTable)Session["outputTable"], "MifirReport");

            // ref link: https://stackoverflow.com/questions/1746701/export-datatable-to-excel-file
            lblError.Text = "";
            try
            {                             
                ASPxGridViewExporter1.ExportSelectedRowsOnly = false;
                ASPxGridViewExporter1.FileName = "Olympia_Wealth_Management_Ltd_MiFIR_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
                CsvExportOptionsEx op = new CsvExportOptionsEx() { ExportType = ExportType.DataAware }; // in DataAware mode l'evento ASPxGridViewExporter_RenderBrick non viene eseguito!!
                ASPxGridViewExporter1.WriteCsvToResponse(op);
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        private void SqlBulkCopyTable(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)
                {
                    lblError.Text = ex.Message;
                }
            }
        }
        private void Flusso_BancaSella()
        {
            // Definizione datatable Input e Output
            DataTable dtInput = new DataTable();
            DataTable dtOutput = new DataTable();
            string dataBancaSella = dateeditBancaSella.Date.Year+"-"+ dateeditBancaSella.Date.Month+"-"+dateeditBancaSella.Date.Day;
            dtOutput = (DataTable)Session["outputTable"];

            // Carica dati banca sella da Guardian in dtInput
            string query = string.Empty;
            //SqlConnection connSql = new SqlConnection(Properties.Settings.Default.DBSettings);
            //SqlCommand cmdSql = connSql.CreateCommand();
            //cmdSql.Parameters.Add("@date", SqlDbType.VarChar).Value = dataBancaSella;
            //cmdSql.CommandText = "mifir_SELLA1";
            //connSql.Open();
            //query = cmdSql.ExecuteScalar().ToString();
            //connSql.Close();
            using (var connSql = new SqlConnection(Properties.Settings.Default.SqlConnection))
            {
                var cmdSql = new SqlCommand
                {
                    CommandText = "mifir_SELLA1",
                    CommandType = CommandType.StoredProcedure,
                    Connection = connSql
                };
                cmdSql.Parameters.Add("@date", SqlDbType.VarChar).Value = dataBancaSella;
                connSql.Open();
                query = cmdSql.ExecuteScalar().ToString();
                connSql.Close();
            }
            // Scarica dati da Guardian
            MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.mySqlConnection);
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = query;
            conn.Open();

            MySqlDataReader dataReader = cmd.ExecuteReader();           
            dtInput.Load(dataReader); // id,progr,sending_time,Dayofexec,OrdStatus,ISIN,cod_ope,ExecTime,QtyFilled,Price,CCY,netamount,divisore
            conn.Close();

            if (dtInput.Rows.Count == 0) return; // Esce se non ci sono record da guardian

            lblDatiBancaSella.Text = String.Format("Record Banca Sella processati: {0}", dtInput.Rows.Count);

            foreach (DataRow inputRow in dtInput.Rows)
            {
                DataRow dr = dtOutput.NewRow();

                // Mappatura campi dtInput in dtOutput
                dr["Report Status"] = "NEWT";                                                                   // col 1
                dr["Transaction Reference Number"] = "A"+inputRow["id"].ToString() + inputRow["progr"].ToString();  // col 2
                dr["Submitting Entity ID"] = "213800Y8S6ABNF5NCQ84";                                            // col 4
                dr["Executing Entity ID"]  = "213800Y8S6ABNF5NCQ84";                                            // col 5
                dr["Investment Firm Indicator"] = "TRUE";                                                       // col 6
                dr["Buyer ID Type"] = "L";                                                                      // col 7
                dr["Buyer ID"] = "549300I7OIUB41P86L19";                                                        // col 9
                if (inputRow["cod_ope"].ToString() == "B")
                {
                    dr["Buyer Decision Maker ID Type"] = "L";                                                   // col 14
                    dr["Buyer Decision Maker ID"] = "549300I7OIUB41P86L19";                                     // col 16
                }
                dr["Seller ID Type"] = "L";                                                                     // col 20
                dr["Seller ID"] = "549300I7OIUB41P86L19";                                                       // col 22
                if (inputRow["cod_ope"].ToString() == "S")
                {
                    dr["Seller Decision Maker ID Type"] = "L";                                                  // col 27
                    dr["Seller Decision Maker ID"] = "549300I7OIUB41P86L19";                                    // col 29
                }
                dr["Order Transmission Indicator"] = "FALSE";                                                   // col 33
                dr["Trading Date Time"] = inputRow["ExecTime"];                                                 // col 36
                dr["Trading Capacity"] = "AOTC";                                                                // col 37
                dr["Quantity"] = inputRow["QtyFilled"].ToString().Replace(",", ".");                            // col 38
                dr["Quantity Type"] = "UNIT";                                                                   // col 39
                dr["Quantity Currency"] = inputRow["CCY"];                                                      // col 40
                dr["Price"] = inputRow["Price"].ToString().Replace(",", ".");                                   // col 42
                dr["Price Type"] = "MntryValAmt";                                                               // col 43
                dr["Price Currency"] = inputRow["CCY"];                                                         // col 44
                dr["Net Amount"] = inputRow["netamount"].ToString().Replace(",",".");                           // col 45
                dr["Venue"] = "XOFF";                                                                           // col 46
                dr["Instrument ID Type"] = "FinInstrm.Id";                                                      // col 51
                dr["Instrument ID"] = inputRow["ISIN"];                                                         // col 52
                dr["Price Multiplier"] = inputRow["divisore"].ToString().Replace(",", ".");                     // col 58
                dr["Firm Execution ID Type"] = "N";                                                             // col 77
                dr["Firm Execution ID Sub Type"] = "NIDN";                                                      // col 78
                dr["Firm Execution ID"] = "CRNFNC90L60C532V";                                                   // col 79
                dr["Firm Execution Country of Branch"] = "IT";                                                  // col 80
                dr["SFT Indicator"] = "FALSE";                                                                  // col 85

                dtOutput.Rows.Add(dr);
            }

            if (dtOutput != null)
            {
                Session["outputTable"] = dtOutput;
                gvOuputExcel.DataSource = Session["outputTable"];
                gvOuputExcel.DataBind();
            }
        }

        private void SalvaInCSV(DataTable dt) // non più usata
        {
            //string excelFileName = "Olympia_Wealth_Management_Ltd_MiFIR_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
            //string attachment = String.Format("attachment; filename={0}", excelFileName);
            //Response.ClearContent();
            //Response.AddHeader("content-disposition", attachment);
            //Response.ContentType = "text/csv";

            //string[] columnNames = dt.Columns.Cast<DataColumn>().
            //                              Select(column => column.ColumnName).
            //                              ToArray();
            //Response.Write(string.Join(",", columnNames));
            //Response.Write("\n");
            //foreach (DataRow row in dt.Rows)
            //{
            //    string[] fields = row.ItemArray.Select(field => field.ToString()).
            //                                ToArray();
            //    for (int i = 0; i < fields.Length; i++)
            //    {

            //        if (fields[i].IndexOf(",") != -1) fields[i] = fields[i].Replace(",","."); // nei decimali sostituisce la , con il .
            //    }

            //    Response.Write(string.Join(",", fields));
            //    Response.Write("\n");
            //}
            //Response.End();

        }

        private void SalvaInExcel(DataTable dt) // non usato, sembra che MiFir non accetti il formato excel
        {
            //string excelFileName = "Olympia_Wealth_Management_Ltd_MiFIR_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            //string attachment = String.Format("attachment; filename={0}", excelFileName);
            //Response.ClearContent();
            //Response.AddHeader("content-disposition", attachment);
            //Response.ContentType = "application/vnd.ms-excel";
            //string tab = "";
            //foreach (DataColumn dc in dt.Columns)
            //{
            //    Response.Write(tab + dc.ColumnName);
            //    tab = "\t";
            //}
            //Response.Write("\n");
            //int i;
            //foreach (DataRow dr in dt.Rows)
            //{
            //    tab = "";
            //    for (i = 0; i < dt.Columns.Count; i++)
            //    {
            //        Response.Write(tab + dr[i].ToString());
            //        tab = "\t";
            //    }
            //    Response.Write("\n");
            //}
            //Response.End();
        }

        protected void gvDatiUBS_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != GridViewRowType.Data) return;

            // Evidenzia righe con PROC1 vuoto (sono da editare e assegnare B o S manualmente
            if (String.IsNullOrEmpty((string)e.GetValue("PROC1"))) e.Row.BackColor = Color.LightSalmon;
        }

        protected void btnProcessaDatiBancaSella_Click(object sender, EventArgs e)
        {
            // Processa output csv , elaborando i dati di UBS e di Banca Sella
            try
            {
                // Processa dati UBS

                lblError.Text = "";
                pageControl.ActiveTabIndex = 1;
                if (Session["DatiUBS"] == null)
                { 
                    lblError.Text = "CSV non rilevato!";
                    return;
                }
                // Crea colonne per Datatable di output dtOutputExcel
                dtOutputExcel = new DataTable();
                dtOutputExcel = CreateOutputDataTable(); // crea colonne

                // Popola righe Datatable di ouput 
                dtDatiUBS = (DataTable)Session["DatiUBS"];
                int incrKey = 1;
                foreach (DataRow inputRow in dtDatiUBS.Rows)
                {
                    DataRow dr = dtOutputExcel.NewRow();

                    // Mappatura campi dtInputCSV in dtOutputExcel
                    dr["Report Status"] = inputRow["TAG_01"];                                               // col 1
                    dr["Transaction Reference Number"] = Convert.ToString(incrKey) + inputRow["TAG_02"];    // col 2
                    dr["Submitting Entity ID"] = "213800Y8S6ABNF5NCQ84";                                    // col 4
                    dr["Executing Entity ID"] = "213800Y8S6ABNF5NCQ84";                                     // col 5
                    dr["Investment Firm Indicator"] = "TRUE";                                               // col 6
                    dr["Buyer ID Type"] = "L";                                                              // col 7
                    dr["Buyer ID"] = inputRow["UBSLEI"];                                                    // col 9
                    dr["Seller ID Type"] = "L";                                                             // col 20
                    dr["Seller ID"] = inputRow["UBSLEI"];                                                   // col 22
                    dr["Order Transmission Indicator"] = "FALSE";                                           // col 33
                    dr["Trading Date Time"] = inputRow["TAG_28"];                                           // col 36
                    dr["Trading Capacity"] = "AOTC";                                                        // col 37
                    dr["Quantity"] = inputRow["TAG_30"];                                                    // col 38
                    dr["Quantity Type"] = "UNIT";                                                           // col 39
                    dr["Quantity Currency"] = inputRow["TAG_31"];                                           // col 40
                    dr["Price"] = inputRow["TAG_33"];                                                       // col 42
                    dr["Price Type"] = "MntryValAmt";                                                       // col 43
                    dr["Price Currency"] = inputRow["TAG_34"];                                              // col 44
                    dr["Net Amount"] = inputRow["TAG_35"];                                                  // col 45
                    dr["Venue"] = "XOFF";                                                                   // col 46
                    dr["Instrument ID Type"] = "FinInstrm.Id";                                              // col 51
                    dr["Instrument ID"] = inputRow["TAG_41"];                                               // col 52
                    dr["Instrument Name"] = inputRow["TAG_42"];                                             // col 53
                    dr["Instrument Classification"] = inputRow["TAG_43"];                                   // col 54      
                    dr["Notional Currency 1"] = inputRow["TAG_44"];                                         // col 55
                    dr["Notional Currency 2"] = inputRow["TAG_45"];                                         // col 56
                    dr["Price Multiplier"] = inputRow["TAG_46"];                                            // col 58
                    dr["Firm Execution ID Type"] = "N";                                                     // col 77
                    dr["Firm Execution ID Sub Type"] = "NIDN";                                              // col 78
                    dr["Firm Execution ID"] = "CRNFNC90L60C532V";                                           // col 79
                    dr["Firm Execution Country of Branch"] = "IT";                                          // col 80
                    dr["SFT Indicator"] = "FALSE";                                                          // col 85

                    if (inputRow["PROC1"].ToString()=="B")
                    {
                        dr["Buyer Decision Maker ID Type"] = "L";                                           // col 14
                        dr["Buyer Decision Maker ID"] = "213800Y8S6ABNF5NCQ84";                             // col 16
                    }
                    if (inputRow["PROC1"].ToString() == "S")
                    {
                        dr["Seller Decision Maker ID Type"] = "L";                                           // col 27
                        dr["Seller Decision Maker ID"] = "213800Y8S6ABNF5NCQ84";                             // col 29
                    }
                    if (inputRow["TAG_01"].ToString() == "NEWT" && !String.IsNullOrEmpty(inputRow["PFLID"].ToString())) // aggiunge la riga se tag_01 = NEWT e PFLID è valorizzato
                    {
                        dtOutputExcel.Rows.Add(dr);
                        incrKey++;
                    }

                }

                if (dtOutputExcel != null) Session["outputTable"] = dtOutputExcel;

                lblDatiUBS.Text = String.Format("Record UBS processati: {0}", dtOutputExcel.Rows.Count);

                // Processa Dati Banca Sella
                Flusso_BancaSella(); // aggiunge al Session["outputTable"] flusso dati da Banca Sella prima di salvare tutto in formato .csv
                gvOuputExcel.DataSource = Session["outputTable"];
                gvOuputExcel.DataBind();

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
        
        protected void ASPxUploadControl1_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {           
            Session["DatiUBS"] = CaricaDatiUBSCsv(e.UploadedFile);
        }

        public DataTable CaricaDatiUBSCsv(UploadedFile uploadedFile)
        {
            // ref link: https://www.c-sharpcorner.com/blogs/read-csv-file-into-data-table1

            DataTable dtCsv = new DataTable();
            string Fulltext;
            if (uploadedFile.IsValid && IsPostBack) //if (FileUpload.HasFile && IsPostBack)
            {
                using (StreamReader sr = new StreamReader(uploadedFile.FileContent))
                {
                    while (!sr.EndOfStream)
                    {
                        Fulltext = sr.ReadToEnd().ToString(); //read full file text  
                        string[] rows = Fulltext.Split('\n'); //split full file text into rows  
                        for (int i = 0; i < rows.Count() - 1; i++)
                        {
                            string[] rowValues = rows[i].Split('|'); //split each row with | to get individual values  
                            {
                                if (i == 0)
                                {
                                    for (int j = 0; j < rowValues.Count(); j++)
                                    {
                                        dtCsv.Columns.Add(rowValues[j]); //add headers  
                                    }
                                }
                                else
                                {
                                    DataRow dr = dtCsv.NewRow();
                                    for (int k = 0; k < rowValues.Count(); k++)
                                    {
                                        dr[k] = rowValues[k].ToString().Replace(",",".");
                                    }
                                    dtCsv.Rows.Add(dr); //add other rows  
                                }
                            }
                        }
                    }
                }
            }
            return dtCsv;
        }

        protected void gvDatiUBS_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            ASPxGridView gridView = (ASPxGridView)sender;
            DataTable dataTable = (DataTable)Session["DatiUBS"];
            DataRow row = dataTable.Rows.Find(e.Keys[0]);
            row["PROC1"] = e.NewValues["PROC1"];
            gridView.CancelEdit();
            e.Cancel = true;
            Session["DatiUBS"] = dataTable;
        }

        protected void btnProcessaDatiUBS_Click(object sender, EventArgs e)
        {
            // Carica Dati UBS
            try
            {
                lblError.Text = "";

                // Carica csv UBS in Datatable e lo processa 
                dtDatiUBS = ProcessaInputDatiUBS();
                pageControl.ActiveTabIndex = 0;

            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        protected void gvOuputExcel_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != GridViewRowType.Data) return;

            // Rileva campo Buyer Decision Maker ID, per colorare le righe di Banca Sella
            object objBuyerMakerID = e.GetValue("Buyer ID");
            if (!String.IsNullOrEmpty(objBuyerMakerID.ToString()))
            {
                if (objBuyerMakerID.ToString() == "549300I7OIUB41P86L19") e.Row.BackColor = Color.LightBlue; // riga di BancaSella
                if (objBuyerMakerID.ToString() == "5299007QVIQ7IO64NX37") e.Row.BackColor = Color.LightGreen; // riga di UBS
                //else e.Row.BackColor = Color.LightGreen; // riga di UBS
            }
            //else e.Row.BackColor = Color.LightGreen; // riga di UBS
        }

    }
}