using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using ceTe.DynamicPDF;
using PDFGenerator.BusinessLayer;
using System.IO;
using PDFGenerator.BusinessLayer;
using PDFGenerator.BusinessLayer.DataSection;
using BusinessDataThreadModel = PDFGenerator.BusinessLayer.DataThreadModel;
using ceTe.DynamicPDF.Merger;
using Dundas.Charting.WebControl;
using ceTe.DynamicPDF.PageElements;
using ceTe.DynamicPDF.Text;
using System.Data;
using PDFGenerator.Presentation.TemplateGenerator;

using System.Threading;
using PDFGenerator.BusinessLayer.Utils;
using System.Linq;
using DataAccessLayer;
using NLog;
using System.Data.SqlClient;
using System.Dynamic;
using ceTe.DynamicPDF.Xmp;
using System.Xml.Linq;
using ceTe.DynamicPDF.IO;
using System.Security.Cryptography;

namespace PDFGenerator
{
    public class DocumentPDF
    {

        private string _tipologia;
        ArrayList _index;
        ArrayList _core;
        int _indexPage;
        int _corePage;
        int _currentPage;
        float _margineUP;
        float _pageHeight;
        float _margineDOWN;
        float _margineLEFT;
        float _margineRIGHT;
        float _writableYPot;
        float _indiceY;
        float _writableY;
        int _sectionSpace;
        int _numlastpage;
        // bool _navigatore;
        bool _glossario;
        //bool _copertina;
        bool _activeIndex;
        MergeDocument _documentoFinale;
        DataSetIndice _strutturaIndice;
        MemoryStream _imgGrafico;
        int _chapterNum;
        int _sectionNum;
        private Document _document;
        private ReportTipo _reportType;
        DataThread _dataThread;
        private OpenTypeFont _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic;
        private ImportedPage _page, _indice, _backPage;
        private float _writableYold;
        private byte[] _data;
        private string _banca;
        private string _notaPieDiPagina;
        /// <summary>
        /// indica se la nota a pi� di pagina � presente.
        /// </summary>
        private bool _flagnotaPieDiPagina;
        //private List<Nota> _note;
        private bool _saltoPagina;
        private string _AsteriscoVarProxato;
        private string _AsteriscoGradoCopertura;
        private int _numNotePiePaginaVarProxato = 0;

        private ListaNote _note = new ListaNote();
        private float _ynotapiedipagina = 740;

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private TemplateProvider _templateProvider;

        //MIFID2 20180523 Inserita nuova propriet� che tiene traccia dell'ultima sezione che la imposta nella writeSezione()
        // utile per la sua sezione successiva (es.: S179 - S180)

        public string LastSectionCheckIn { get; set; }

        //--MIFID2

        //MIFID2 20180529 Inserita nuova propriet� che tiene il conteggio delle aree monitorate (cio� delle aree che saranno stampate dalle sezioni S43 e S43BIS)

        public int AreasCount { get; set; }

        public DataTable Areas { get; set; }

        // Serve per memorizzare le posizioni in cui inserire le note per le sezioni S43 e S43BIS, in Monitoraggio
        public DataTable DocumentNotes { get; set; }

        //--MIFID2
        public DocumentPDF()
        { 
        
        }
        public DocumentPDF(DataThread dataThread, string tipoReport):this()
        {
            #region region
            _dataThread = dataThread;
            //BusinessLayer.Utils.TemplateProvider._dataThread = dataThread;
            //BusinessLayer.Utils.TemplateProvider.CF = dataThread.CodiceFiscale;
            TemplateProvider.CF = dataThread.CodiceFiscale;

            //if (!dataThread.Periodico)
            //{
            //    // LETTERE DI BENVENUTO
            //    TemplateProvider.idReportDiagnosi = dataThread.ReportsType.Find(f => f.Descrizione == "Diagnosi").IdModello;
            //}
            //else
            //{
            //    //TRIMESTRALE
            //    TemplateProvider.idReportDiagnosi = dataThread.ReportsType.Find(f => f.Descrizione == "Monitoraggio").IdModello;
            //}
            //logger.Info("DocumentPDF idReportDiagnosi: " + TemplateProvider.idReportDiagnosi);

            logger.Info("DocumentPDF Periodico: " + dataThread.Periodico);
            

            //
            _templateProvider = new TemplateProvider((int)dataThread.TipoContratto, dataThread.Rete, dataThread.Periodico);
            _index = new ArrayList();
            _core = new ArrayList();
            _indexPage = 0;
            _corePage = 0;
            _currentPage = 0;
            _margineUP = 160;
            _pageHeight = 841.9F;
            _margineDOWN = 105;
            _margineLEFT = 42;
            _margineRIGHT = 259;
            _writableYPot = 0;
            _sectionSpace = 30;  //30; // Spazio tra le sezioni da stampare
            _numlastpage = -1;

            _glossario = false;

            _activeIndex = false;
            _strutturaIndice = new DataSetIndice();
            _imgGrafico = new System.IO.MemoryStream();
            _documentoFinale = new MergeDocument();

            _chapterNum = 0;
            _sectionNum = 0;
            _document = new Document();
            _reportType = _dataThread.ReportsType.Find(delegate (ReportTipo r) { return r.Descrizione.ToUpper() == tipoReport; });
            _document.Title = _reportType.Descrizione;
            _document.CompressionLevel = 9;
            _AsteriscoVarProxato = "";
            _AsteriscoGradoCopertura = "";

            LastSectionCheckIn = "";

            AreasCount = 0;
            Areas = new DataTable();
            DocumentNotes = new DataTable();
            DocumentNotes.Columns.Add("Area", typeof(string));
            DocumentNotes.Columns.Add("Posizione", typeof(float));
            DocumentNotes.Columns.Add("Pagina", typeof(Int16));



            //--MIFID2

            try
            {
                bool isValid = ceTe.DynamicPDF.Document.AddLicense(CACHE.LICENZA_Dynamic_PDF);
            }
            catch (Exception ex)
            {
                logger.Errors(ex);
                throw;
            }
            // Create a standard security object 
            StandardSecurity security = new StandardSecurity();

            // Set the permissions on that security object 
            //security.AllowPrint = false;
            security.AllowCopy = false;
            security.AllowEdit = false;

            // Add the security object to the document 
            _document.Security = security;
            _document.PdfVersion = PdfVersion.v1_4;
            _document.PdfXVersion = PdfXVersion.PDF_X_3_2003;

            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            string relativePath = UtilityManager.getAppSetting("ICCprofile");
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);


            IccProfile iccProfile = new IccProfile(file);
            string configurationPath1 = UtilityManager.getAppSetting("ICCconfiguration");
            string configurationPath2 = UtilityManager.getAppSetting("ICCconfiguration1");
            string configurationPath3 = UtilityManager.getAppSetting("ICCconfiguration2");
            string configurationPath4 = UtilityManager.getAppSetting("ICCconfiguration3");
            OutputIntent outputIntent = new OutputIntent(configurationPath1, configurationPath2, configurationPath3, configurationPath4, iccProfile);
            _document.OutputIntents.Add(outputIntent); // Patryk Prepress
            _document.Trapped = Trapped.False; // Patryk Prepress
            _writableY = _margineUP;

            //Creo il PDF
            this.createFont();
            this.addPage();
            #endregion
        }

        private void SetTemplate(ImportedPage p)
        {
            /*** Fix Direct Banck 12/03/2023 - Pino ***/
            //p.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("REPORT " + _document.Title.ToUpper(), 38, 43, 250, 12, _verdanaBold, 11, _templateProvider.ChapterFontColor));//ceTe.DynamicPDF.CmykColor.Red
            if (!_dataThread.Periodico)
            {
                if (_dataThread.ReportsType.Find(f => f.Descrizione.ToUpper() == "DIAGNOSI").IdModello == 6)
                    p.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("REPORT DI BENVENUTO", 38, 43, 250, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Green));//ceTe.DynamicPDF.CmykColor.Red
                else
                    p.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("REPORT " + _document.Title.ToUpper(), 38, 43, 250, 12, _verdanaBold, 11, _templateProvider.ChapterFontColor));//ceTe.DynamicPDF.CmykColor.Red
            }
            else
                p.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("REPORT " + _document.Title.ToUpper(), 38, 43, 250, 12, _verdanaBold, 11, _templateProvider.ChapterFontColor));//ceTe.DynamicPDF.CmykColor.Red

            /******************************************/


            p.Elements.Add(new PageNumberingLabel("pagina %%SP%% di %%ST%%", 0, 820, 542, 12, _verdana, 7, ceTe.DynamicPDF.TextAlign.Right));
        }

        public void insertCliente()
        {
            this.setPageFooterNomeCliente(_page);
        }

        public ImportedPage getCurrentPage()
        {
            return _page;
        }

        //MIFID2 20180529 
        public ImportedPage getPageAt(int index)
        {
            return (ImportedPage)_core[index];
        }
        //--MIFID2

        public float getSectionSpace()
        {
            return _sectionSpace;
        }

        private void createFont()
        {
            // Create a TrueType font class.
            _verdana = Globals.OpenTypeFontVerdana;
            _verdanaBold = Globals.OpenTypeFontVerdanaB;
            _verdanaItalic = Globals.OpenTypeFontVerdanaZ;
            _verdanaBoldItalic = Globals.OpenTypeFontVerdanaZ;
        }



        /// <summary>
        /// Stampo le note aggiunte alla pagina (document).
        /// Stampo solamente quelle con posizionamento a "Pi�DiPagina" e Stato "DaStampare"
        /// 
        /// Questa funzione � richiamata dal metodo addPage. A differenza dell'altro overload di StampaNote,questo � richiamato quando non c'� salto pagina della tabella. 
        /// </summary>
        public void StampaNote()
        {
            // stampo le note a pi� di pagina prima di aggiungerne una nuova.

            //Ordinamento
            _note.Sort(delegate (Nota nota, Nota nota2) { return nota.NumeroAsterisco.CompareTo(nota2.NumeroAsterisco); });
            _note.Reverse();

            // distinct sul numero di asterischi.
            ListaNote newList = new ListaNote();

            foreach (Nota objNota in _note)
            {
                if (newList.Find(delegate (Nota nota) { return nota.NumeroAsterisco == objNota.NumeroAsterisco; }) == null)
                    newList.Insert(objNota);
            }
            _note = newList;


            foreach (Nota objNota in _note.FindAll(delegate (Nota t) { return t.Posizionamento == Nota.TipologiaPosizionamento.PieDiPagina && t.Stato == Nota.StatoNota.DaStampare; }))
            {
                // Per ora abbiamo solo note che sono o inferiori a 200 caratteri o di 254 (nota var proxato)
                // se la lunghezza delle note a pi� di pagina dovesse cambiare questa gestione va rivista.

                if (objNota.Testo.Length > 200)
                    _ynotapiedipagina -= 10;

                writeText(42, _ynotapiedipagina, objNota.Testo, 7, 512);

                objNota.Stato = Nota.StatoNota.Stampata; // Imposto la nota come gi� stampata

                if (objNota.Testo.Length < 200)
                    _ynotapiedipagina -= 12;
                else
                    _ynotapiedipagina -= 22;
            }
        }



        /// <summary>
        /// Stampo le note aggiunte alla pagina (document).
        /// Stampo solamente quelle con posizionamento a Pi�DiPagina 
        /// Stampo le note delle tabelle che stanno effettuando il saltopagina.
        /// 
        /// Qusta funzione � richiamata solo quando una tabella sta effettuando il "saltopagina" non imposto quindi lo Stato della Nota su "Stampata".
        /// </summary>
        /// <param name="idtabella"></param>
        public void StampaNote(string idtabella)
        {

            // stampo le note a pi� di pagina prima di aggiungerne una nuova.

            //Ordinamento
            _note.Sort(delegate (Nota nota, Nota nota2) { return nota.NumeroAsterisco.CompareTo(nota2.NumeroAsterisco); });
            _note.Reverse();

            // distinct sul numero di asterischi.
            ListaNote newList = new ListaNote();

            foreach (Nota objNota in _note)
            {
                if (newList.Find(delegate (Nota nota) { return nota.NumeroAsterisco == objNota.NumeroAsterisco; }) == null)
                    newList.Insert(objNota);
            }
            _note = newList;

            foreach (Nota objNota in _note.FindAll(delegate (Nota t) { return t.Posizionamento == Nota.TipologiaPosizionamento.PieDiPagina; }))
            {
                // Per ora abbiamo solo note che sono o inferiori a 200 caratteri o di 254 (nota var proxato)
                // se la lunghezza delle note a pi� di pagina dovesse cambiare questa gestione va rivista.

                if (objNota.Testo.Length > 200)
                    _ynotapiedipagina -= 10;

                writeText(42, _ynotapiedipagina, objNota.Testo, 7, 512);

                if (objNota.Testo.Length < 200)
                    _ynotapiedipagina -= 12;
                else
                    _ynotapiedipagina -= 22;

            }

        }

        public void AddDocumentNote(string area, float pos, int pag)
        {

            var dr = DocumentNotes.AsEnumerable().Where(x => x.Field<string>("Area").ToUpper().Equals(area.ToUpper()) && x.Field<float>("Posizione") == 0 && x.Field<Int16>("Pagina") == pag);

            int i = 0;
            foreach (var item in dr)
            {
                item["Posizione"] = pos;
                i++;
            }

            if (i == 0)
                this.DocumentNotes.Rows.Add(area, pos, pag);

        }


        public void WriteNote(string note, Boolean isSavingMap)
        {

            int minIndex = Convert.ToInt16(this.DocumentNotes.Compute("MIN([Pagina])", ""));
            int maxIndex = Convert.ToInt16(this.DocumentNotes.Compute("MAX([Pagina])", ""));

            /**************** "Modifica del dimensionamento della posizione per la nota statica richiesta 22/02/2021 - Pino" **********************/
            float bottomPos = 0;

            if (note.Length > 482)
                bottomPos = 700; //688; ////710;  originale
            else
                bottomPos = 710;
            /**************************************************************************************************************************************/
            float posNota = 500;  //710;
            if (isSavingMap)
            {
                bottomPos = 700;
                posNota = 700;
            }
            ImportedPage p;

            for (var i = minIndex; i <= maxIndex; i++)
            {
                p = this.getPageAt(i - 1);

                var dv = this.DocumentNotes.AsEnumerable().Where(d => d.Field<Int16>("Pagina") == i).AsDataView();

                if (dv.Count == 0 || dv.Count > 1)
                    posNota = bottomPos;
                else if (dv.Count == 1)
                    posNota = (float)dv.ToTable().Rows[0]["Posizione"] == 0 ? bottomPos : (float)dv.ToTable().Rows[0]["Posizione"] - 8;

                /**************** "Modifica del dimensionamento della posizione per la nota statica richiesta 22/02/2021 - Pino" **********************/
                //FormattedTextArea text = new FormattedTextArea(note, this.getMargineLeft(), posNota, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                FormattedTextArea text = new FormattedTextArea(note, this.getMargineLeft(), posNota, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 6, false);
                /**************************************************************************************************************************************/
                text.Height = text.GetRequiredHeight();
                text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;

                p.Elements.Add(text);
            }
            if (isSavingMap)
            {
                String pathImg = System.IO.Path.Combine(CACHE.pathGraf, "SavingMap.png");
                //String pathImg1 = WebConfigParameter.getParameter("APCPath");
                Image img = new Image(pathImg, this.getMargineLeft(), posNota + 38);
                //// Test per APC Andrea
                //Image img1 = new Image(pathImg1, this.getMargineLeft() + 150, posNota + 38, 0.035F);
                //FormattedTextArea textAPC = new FormattedTextArea("«APC» Investimenti finanziari", this.getMargineLeft() + 170, posNota + 40, 200, 10, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                //// 
                FormattedTextArea textSM = new FormattedTextArea("Servizio Saving Map attivo.", this.getMargineLeft() + 20, posNota + 40, 100, 10, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                p = this.getPageAt(maxIndex - 1);
                p.Elements.Add(img);
                p.Elements.Add(textSM);
                //p.Elements.Add(img1);
                //p.Elements.Add(textAPC);
            }

            this.DocumentNotes = new DataTable();
        }
        public void WriteNote2(string note, Boolean isSavingMap, Boolean isAPC103)
        {

            int minIndex = Convert.ToInt16(this.DocumentNotes.Compute("MIN([Pagina])", ""));
            int maxIndex = Convert.ToInt16(this.DocumentNotes.Compute("MAX([Pagina])", ""));

            /**************** "Modifica del dimensionamento della posizione per la nota statica richiesta 22/02/2021 - Pino" **********************/
            float bottomPos = 0;

            if (note.Length > 482)
                bottomPos = 700; //688; ////710;  originale
            else
                bottomPos = 710;
            /**************************************************************************************************************************************/
            float posNota = 500;  //710;
            if (isSavingMap)
            {
                bottomPos = 700;
                posNota = 700;
            }
            ImportedPage p;

            for (var i = minIndex; i <= maxIndex; i++)
            {
                p = this.getPageAt(i - 1);

                var dv = this.DocumentNotes.AsEnumerable().Where(d => d.Field<Int16>("Pagina") == i).AsDataView();

                if (dv.Count == 0 || dv.Count > 1)
                    posNota = bottomPos - 10;
                else if (dv.Count == 1)
                    posNota = (float)dv.ToTable().Rows[0]["Posizione"] == 0 ? bottomPos : (float)dv.ToTable().Rows[0]["Posizione"];

                /**************** "Modifica del dimensionamento della posizione per la nota statica richiesta 22/02/2021 - Pino" **********************/
                //FormattedTextArea text = new FormattedTextArea(note, this.getMargineLeft(), posNota, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                FormattedTextArea text = new FormattedTextArea(note, this.getMargineLeft(), posNota, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 6, false);
                /**************************************************************************************************************************************/
                text.Height = text.GetRequiredHeight();
                text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;

                p.Elements.Add(text);
            }
            if (isSavingMap)
            {
                String pathImg = System.IO.Path.Combine(CACHE.pathGraf, "SavingMap.png");
                //String pathImg1 = WebConfigParameter.getParameter("APCPath");
                Image img = new Image(pathImg, this.getMargineLeft(), posNota + 38);
                //// Test per APC Andrea
                //Image img1 = new Image(pathImg1, this.getMargineLeft() + 150, posNota + 38, 0.035F);
                //FormattedTextArea textAPC = new FormattedTextArea("«APC» Investimenti finanziari", this.getMargineLeft() + 170, posNota + 40, 200, 10, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                //// 
                FormattedTextArea textSM = new FormattedTextArea("Servizio Saving Map attivo.", this.getMargineLeft() + 20, posNota + 40, 100, 10, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                p = this.getPageAt(maxIndex - 1);
                p.Elements.Add(img);
                p.Elements.Add(textSM);
                //p.Elements.Add(img1);
                //p.Elements.Add(textAPC);
            }
            if (isAPC103 && isSavingMap)
            {
                String pathImg1 = WebConfigParameter.getParameter("APCPath");

                Image img1 = new Image(pathImg1, this.getMargineLeft() + 150, posNota + 38, 0.035F);
                FormattedTextArea textAPC = new FormattedTextArea("«APC» Investimenti finanziari", this.getMargineLeft() + 170, posNota + 40, 200, 10, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                p = this.getPageAt(maxIndex - 1);
                p.Elements.Add(img1);
                p.Elements.Add(textAPC);
            }
            if (isAPC103 && !isSavingMap)
            {
                String pathImg1 = WebConfigParameter.getParameter("APCPath");

                Image img1 = new Image(pathImg1, this.getMargineLeft() + 20, posNota + 38, 0.035F);
                FormattedTextArea textAPC = new FormattedTextArea("«APC» Investimenti finanziari", this.getMargineLeft() + 40, posNota + 40, 200, 10, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                p = this.getPageAt(maxIndex - 1);
                p.Elements.Add(img1);
                p.Elements.Add(textAPC);
            }
            this.DocumentNotes = new DataTable();
        }

        private void addGlossario()
        {
            int prof = (_dataThread.IsProfessionalClient) ? 1 : 0;
            bool adeguato = Convert.ToBoolean(_dataThread.clienteAdeguato(_dataThread.Rete, _dataThread.CodiceFiscale, _dataThread.Periodico));
            /************* Test frda tagliere vale solo per test****************/
            //adeguato = true;
            /**********************************************************************/

            TemplateGenerator tg = new TemplateGenerator();
            if (!_dataThread.Periodico)
            {
                if (_dataThread.ReportsType.Find(f => f.Descrizione.ToUpper() == "DIAGNOSI").IdModello == 6)
                {
                    tg.ColorHeaderDB = "green";
                }
            }
            // MIFID2 20180417 il glossario � generato dinamicamente, quindi non pu� essere pi� restituito come array di pagine, ma come lista
            //ImportedPage[] glox = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto, _dataThread.Periodico, _dataThread.Flagnqp, _dataThread.Flagprlrde, prof.ToString());
            // OVERRIDE getGlossario, viene passato il _dataThread

            /***** Fix - Aggiunto parametro in input per la gestione del glossario per FD 09/05/2023 - Pino *****/
            int _idModello = 0;
            if (_dataThread.ReportsType.Exists(f => f.IdModello == 6))
                _idModello = 6;

            List<ImportedPage> glox = tg.getGlossario(
                _dataThread, _idModello, prof.ToString(), adeguato
                );
            //List<ImportedPage> glox = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.CodiceFiscale, _dataThread.TipoContratto, _dataThread.Periodico, _dataThread.Flagnqp, _dataThread.Flagprlrde, prof.ToString(), adeguato);
            /****************************************************************************************************/
            //List<ImportedPage> glox = tg.getGlossario(new DocumentPDF(_dataThread, _dataThread.TipoReport), _dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto, _dataThread.Periodico, _dataThread.Flagnqp, _dataThread.Flagprlrde, prof.ToString());
            //--MIFID2

            try
            {
                foreach (ImportedPage p in glox)
                {
                    this.SetTemplate(p);
                    this.setPageFooter(p);
                    this.setPageFooterNomeCliente(p);
                    _document.Pages.Add(p);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Errore: " + ex.Message);
            }


            //PdfDocument pp1 = new PdfDocument(file);
            //ImportedPage pg1 = tg.getAvvertenze(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto);//= new ImportedPage(pp1.GetPage(1));

            //this.SetTemplate(pg1);
            //this.setPageFooter(pg1);
            //this.setPageFooterNomeCliente(pg1);
            //_document.Pages.Add(pg1);

            _index.Add(_indice);
            _indiceY = _margineUP + 30;
            _activeIndex = true;

            _indexPage++;
            _indiceY = _margineUP;
        }

        //private void addGlossarioOriginale()
        //{
        //    int prof = (_dataThread.IsProffesionalClient) ? 1 : 0;
        //    TemplateGenerator tg = new TemplateGenerator();
        //    ImportedPage[] glox = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto, _dataThread.Periodico, _dataThread.Flagnqp, _dataThread.Flagprlrde, prof.ToString());

        //    foreach (ImportedPage p in glox)
        //    {
        //        this.SetTemplate(p);
        //        this.setPageFooter(p);
        //        this.setPageFooterNomeCliente(p);
        //        _document.Pages.Add(p);
        //    }

        //    #region vecchio glossario
        //    //string pdfRelativePath = null;
        //    ////V Provvisorio in attesa di montare la nuova gestione del glossario anche per diagnosi
        //    //ImportedPage temp = null;

        //    //if (_dataThread.Rete.ToUpper() == "F")
        //    //    if(_dataThread.TipoReport.ToUpper() == "DIAGNOSI")
        //    //        pdfRelativePath = UtilityManager.getAppSetting("GlossarioBF");
        //    //    else {

        //    //        temp = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper());

        //    //    }
        //    //        //pdfRelativePath = UtilityManager.getAppSetting("GlossarioBF_Monitoraggio");
        //    //else
        //    //    if (_dataThread.TipoReport.ToUpper() == "DIAGNOSI")
        //    //        pdfRelativePath = UtilityManager.getAppSetting("GlossarioSP");
        //    //    else
        //    //    {

        //    //        temp = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper());
        //    //    }
        //    //        //pdfRelativePath = UtilityManager.getAppSetting("GlossarioSP_Monitoraggio");
        //    //System.Reflection.Assembly thisExe;
        //    //System.IO.Stream file = null;
        //    //if (pdfRelativePath != null) //GLOSSARIO DIAGNOSI Lo recupero dal template statico
        //    //{

        //    //    thisExe = System.Reflection.Assembly.GetExecutingAssembly();

        //    //    file = thisExe.GetManifestResourceStream(pdfRelativePath);

        //    //    //PdfDocument PPP = new PdfDocument("C:\\Templ_avvertenzeBF.pdf");
        //    //    PdfDocument pp = new PdfDocument(file);

        //    //    ImportedPage pg = null;
        //    //    for (int _indicePagina = 1; _indicePagina <= pp.Pages.Count; _indicePagina++)
        //    //    {
        //    //        pg = new ImportedPage(pp.GetPage(_indicePagina));
        //    //        this.SetTemplate(pg);
        //    //        this.setPageFooter(pg);
        //    //        this.setPageFooterNomeCliente(pg);

        //    //        _document.Pages.Add(pg);
        //    //    }
        //    //}
        //    //else //Glossario Monitoraggio generato dinamicamente
        //    //{
        //    //    ImportedPage pg = temp;

        //    //    this.SetTemplate(pg);
        //    //    this.setPageFooter(pg);
        //    //    this.setPageFooterNomeCliente(pg);
        //    //    _document.Pages.Add(pg);


        //    //}



        //    //thisExe = System.Reflection.Assembly.GetExecutingAssembly();

        //    //if (_dataThread.Rete == "F")
        //    //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeBF");
        //    //else
        //    //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeSP");

        //    //file = thisExe.GetManifestResourceStream(pdfRelativePath);

        //    #endregion


        //    //PdfDocument pp1 = new PdfDocument(file);
        //    ImportedPage pg1 = tg.getAvvertenze(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto);//= new ImportedPage(pp1.GetPage(1));

        //    this.SetTemplate(pg1);
        //    this.setPageFooter(pg1);
        //    this.setPageFooterNomeCliente(pg1);
        //    _document.Pages.Add(pg1);


        //    _index.Add(_indice);
        //    _indiceY = _margineUP + 30;
        //    _activeIndex = true;

        //    _indexPage++;
        //    _indiceY = _margineUP;



        //}

        //private void addNavigatore()
        //{
        //    string startDir = UtilityManager.getAppSetting("Path");
        //    string pdfRelativePath;

        //    if (_rete == "F")
        //        switch (_tipoReport.Trim())
        //        {
        //            case "DIAGNOSI":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFDiagnosi");
        //                break;
        //            case "PIANIFICAZIONE":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFPianificazione");
        //                break;
        //            case "PROPOSTA":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFProposta");
        //                break;
        //            case "MONITORAGGIO":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFMonitoraggio");
        //                break;
        //            default:
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFDiagnosi");
        //                break;
        //        }
        //    else
        //        switch (_tipoReport.Trim())
        //        {
        //            case "DIAGNOSI":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPDiagnosi");
        //                break;
        //            case "PIANIFICAZIONE":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPPianificazione");
        //                break;
        //            case "PROPOSTA":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPProposta");
        //                break;
        //            case "MONITORAGGIO":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPMonitoraggio");
        //                break;

        //            default:
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPDiagnosi");
        //                break;
        //        }

        //    PdfDocument pp = new PdfDocument(startDir + pdfRelativePath);

        //    for (int _indicePagina = 1; _indicePagina <= pp.Pages.Count; _indicePagina++)
        //    {
        //        ImportedPage pg = new ImportedPage(pp.GetPage(_indicePagina));
        //        //this.SetTemplate(pg);
        //        //this.setPageFooter(pg);
        //        //this.setPageFooterNomeCliente(pg);

        //        _index.Add(pg);
        //        _indexPage++;
        //    }
        //}

        /// <summary>
        /// Scrive nel Db lo streaming PDF come array di byte
        /// </summary>
        /// <param name="identificativo"></param>
        /// <returns>restituisce l'array di byte[] inserito nel db</returns>
        /// 


        public void deleteReportSuFileSystem(int idReport, string nomefile)
        {

            string targetFolder = getPdfForlder();

            string file = @targetFolder + idReport + "_" + nomefile + ".pdf";
            if (Directory.Exists(System.IO.Path.GetDirectoryName(file)))
            {
                File.Delete(file);
            }

        }

        public bool scriviSuFileSystem(int idReport)
        {
            string targetFolder = string.Empty;
            bool retValue = false;
            try
            {

                string pdf = string.Empty;
                targetFolder = CACHE.SavePDFtoDISK_Folder;

                switch (CACHE.SavePDFtoDISK)
                {
                    case 0:
                        // Salvataggio su DataBase ReportManager
                        // Parametro Attualmente Gestito nel metodo DocumentPDF.insertIntoDb()
                        retValue = true;
                        break;

                    case 1:
                        // Salvataggio su File SYstem
                        // Gestione test in locale e/o Generazione Campione
                        pdf = targetFolder + _dataThread.NomeFilePdf + ".pdf";
                        AddSer(_documentoFinale, _dataThread);
                        _documentoFinale.Draw(pdf);
                        retValue = true;
                        break;

                    case 2:
                        pdf = targetFolder + idReport + "_" + _dataThread.NomeFileReport + ".pdf";
                        AddSer(_documentoFinale, _dataThread);
                        _documentoFinale.Draw(pdf);
                        retValue = true;
                        break;

                    default:
                        break;
                }

                
            }
            catch (Exception ex)
            {
                logger.Errors(ex);
                logger.Debugs($"Errore PDFGenerator.DocumentPDF.scriviSuFileSystem IdReport={idReport}");
            }

            return retValue;
        }

        private void AddSer(ceTe.DynamicPDF.Document _documentoFinale, DataThread _dataThread)
        {
            try
            {
                _dataThread.TotalePagine = _documentoFinale.Pages.Count;
                BusinessDataThreadModel model = (BusinessDataThreadModel)_dataThread;
                string aut = ""; // Newtonsoft.Json.JsonConvert.SerializeObject(model);
                _documentoFinale.Author = CACHE.Author + Environment.NewLine + Environment.NewLine + aut;
            }
            catch { }
        }

        public string[] DeSer(string pdf)
        {
            string[] ret = null;

            try
            {
                PdfDocument p = new PdfDocument(pdf);
                string a = p.Author;
                a = a.Replace(CACHE.Author, "");
                a = a.Substring(1);
                a = a.Replace(Environment.NewLine, "");
                a = (new XDS(CACHE.PASSKEY)).Decrypt(a);
                ret = a.Split(';');
                p = null;
            }
            catch{}
            
            return ret;
        }

        public int insertIntoDB(DataThread Data)
        {
            Data.TipoReport = _reportType.TipoReport == TipologiaReport.DIAGNOSI ? "Diagnosi" : "Monitoraggio";
            List<SqlParameter> parameters = new List<SqlParameter>
            {
                new SqlParameter
                {
                    ParameterName = "CodiceContratto",
                    Value = Data.CodiceContratto
                },
                new SqlParameter
                {
                    ParameterName = "Rete",
                    Value = Data.Rete
                },
                new SqlParameter
                {
                    ParameterName = "CodiceFiscale",
                    Value = Data.CodiceFiscale
                },
                new SqlParameter
                {
                    ParameterName = "NomeCliente",
                    Value = Data.NomeCliente
                },
                new SqlParameter
                {
                    ParameterName = "CognomeCliente",
                    Value = Data.CognomeCliente
                },
                new SqlParameter
                {
                    ParameterName = "TipoReport",
                    Value = Data.TipoReport
                },
                new SqlParameter
                {
                    ParameterName = "img",
                    DbType= DbType.Binary,
                    Value = this.getData()
                },
                new SqlParameter
                {
                    ParameterName = "CodicePB",
                    Value = Data.Agente
                },
                new SqlParameter
                {
                    ParameterName = "NomePB",
                    Value = Data.NomeAgente
                },
                new SqlParameter
                {
                    ParameterName = "CognomePB",
                    Value = Data.CognomeAgente
                },
                new SqlParameter
                {
                    ParameterName = "NumeroPagine",
                    Value = _documentoFinale.Pages.Count
                }
            };

            using (SQLServer db = new SQLServer(Data.CodiceFiscale, Data.Rete, false))
            {
                return db.executeScalarInt(CACHE.QueryInserimento, parameters);
            }

        }

        /// <summary>
        /// Chiamata da GestorePDF per integrare righe mancanti in [SEIReport].[dbo].[C6ReportFisico]
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="Pagine"></param>
        /// <returns></returns>
        public int insertIntoDBTest(DataThread Data)
        {
            /*
                @CodiceContratto as varchar(11),
                @Rete as varchar(1),
                @CodiceFiscale as varchar(16),
                @NomeCliente as varchar(50),
                @CognomeCliente as varchar(50),
                @img as image = null,
                @CodicePB as varchar(6),
                @NomePB as varchar(50) = null,
                @CognomePB as varchar(50) = null,
                @NumeroPagine as int
            */
            byte[] pdfBytes;
            using (var memoryStream = new MemoryStream())
            {
                Data.Stream.CopyTo(memoryStream);
                pdfBytes = memoryStream.ToArray();
            }
            int num = totalepaginedapdf(pdfBytes);

            Data.TipoReport = "Diagnosi";
            List<SqlParameter> parameters = new List<SqlParameter>
            {
                new SqlParameter
                {
                    ParameterName = "CodiceContratto",
                    Value = Data.CodiceContratto
                },
                new SqlParameter
                {
                    ParameterName = "Rete",
                    Value = Data.Rete
                },
                new SqlParameter
                {
                    ParameterName = "CodiceFiscale",
                    Value = Data.CodiceFiscale
                },
                new SqlParameter
                {
                    ParameterName = "NomeCliente",
                    Value = Data.NomeCliente
                },
                new SqlParameter
                {
                    ParameterName = "CognomeCliente",
                    Value = Data.CognomeCliente
                },
                new SqlParameter
                {
                    ParameterName = "img",
                    DbType= DbType.Binary,
                    Value = Data.Stream
                },
                new SqlParameter
                {
                    ParameterName = "CodicePB",
                    Value = Data.Agente
                },
                new SqlParameter
                {
                    ParameterName = "NomePB",
                    Value = Data.NomeAgente
                },
                new SqlParameter
                {
                    ParameterName = "CognomePB",
                    Value = Data.CognomeAgente
                },
                new SqlParameter
                {
                    ParameterName = "NumeroPagine",
                    Value = num
                }
            };
            
            using (SQLServer db = new SQLServer(Data.CodiceFiscale, Data.Rete, false))
            {
                return db.executeScalarInt(CACHE.QueryInserimentoTest, parameters);
            }
            
            /*
            
            string testo = "";
            testo += Data.CodiceFiscale + "_" + Data.Rete + "=" + num.ToString();
            File.AppendAllLines(@"C:\REPO\LISTAGG.txt", new string[] { testo });
            return 1;
            */
        }

        private int totalepaginedapdf(byte[] data)
        {
            int ret = 0;
            PdfDocument pdfdoc = new PdfDocument(data);
            ret=pdfdoc.Pages.Count;
            pdfdoc = null;
            return ret;
        }

        public void inserisciCommercialeLettera()
        {
            byte[] pdf = this.getData();
            // Create two PDF document objects
            PdfDocument pdfA;
            //GestoreLettera letter = new GestoreLettera(_dataThread.DataAccess);
            GestoreLettera letter = new GestoreLettera();
            //dynamic datodapassare = new ExpandoObject();
            //datodapassare.DataThread = _dataThread;
            //letter.DatiDiPassaggio = datodapassare;

            letter.RestGestoreLettera();

            /**** Fix Direct Bank 28/03/2023 - Pino ***/
            if (!_dataThread.Periodico)
            {
                letter.idModello = _dataThread.ReportsType.Find(f => f.Descrizione == "Diagnosi").IdModello;
            }
            /******************************************/

            if (CACHE.Periodico && _dataThread.TipoContratto == TipoContratto.Private)
            {
                var pages = letter.componiLetteraCommerciale(_dataThread.CodiceFiscale, _dataThread.Rete, TipoLettera.LetteraCommerciale, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi, _dataThread.IsProfessionalClient);
                pages.Reverse();
                foreach (byte[] pdfPage in pages)
                {
                    pdfA = new PdfDocument(pdfPage);

                    PdfDocument pdfB = new PdfDocument(pdf);
                    //pdfA = new PdfDocument(LetteraBA.GetLetteraBA(_dataThread));
                    // Merge the two documents
                    _documentoFinale = MergeDocument.Merge(pdfA, pdfB);

                    // Save the PDF
                    _data = _documentoFinale.Draw();
                    pdf = this.getData();
                }
            }
        }

        public void inserisciLettera()
        {

            byte[] pdf = this.getData();
            // Create two PDF document objects
            PdfDocument pdfA;
            GestoreLettera letter = new GestoreLettera();
            //GestoreLettera letter = new GestoreLettera(_dataThread.DataAccess);

            //dynamic datodapassare = new ExpandoObject();
            //datodapassare.DataThread = _dataThread;
            //letter.DatiDiPassaggio = datodapassare;

            letter.RestGestoreLettera();

            /**** Fix Direct Bank 28/03/2023 - Pino ***/
            if (!_dataThread.Periodico)
            {
                // Per lettere di benvenuto
                letter.idModello = _dataThread.ReportsType.Find(f => f.Descrizione == "Diagnosi").IdModello;
            }
            else
            {
                // Per la trimestrale controllo se l'utente è FD
                if (_dataThread.ReportsType.Any(f => f.Descrizione.ToUpper() == "MONITORAGGIO"))
                    letter.idModello = _dataThread.ReportsType.Find(f => f.Descrizione.ToUpper() == "MONITORAGGIO").IdModello;
                else
                    letter.idModello = _dataThread.ReportsType.Find(f => f.Descrizione.ToUpper() == "DIAGNOSI").IdModello;
            }
            /******************************************/

            if (!_dataThread.Periodico)
            {

                if (_dataThread.AdesioneSuccessivaAvanzato || _dataThread.ContrattoOld)
                    pdfA = new PdfDocument(letter.componiLetteraBenvenuto(_dataThread.CodiceFiscale, _dataThread.Rete, TipoLettera.LetteraAccettazioneAttivazioneSeiPosticipata, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi, _dataThread.IsProfessionalClient));
                else
                    pdfA = new PdfDocument(letter.componiLetteraBenvenuto(_dataThread.CodiceFiscale, _dataThread.Rete, TipoLettera.LetteraAccettazioneConAttivazioneSei, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi, _dataThread.IsProfessionalClient));
            }
            else
            {
                if (_dataThread.TipoReport.ToUpper().Trim() == "DIAGNOSI")
                    pdfA = new PdfDocument(letter.componiLetteraAccompagnamento(_dataThread.CodiceFiscale, _dataThread.Rete, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi, _dataThread.IsProfessionalClient));
                else
                    pdfA = new PdfDocument(letter.componiLetteraAccompagnamento(_dataThread.CodiceFiscale, _dataThread.Rete, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Monitoraggio, _dataThread.IsProfessionalClient));

            }
            PdfDocument pdfB = new PdfDocument(pdf);
            //pdfA = new PdfDocument(LetteraBA.GetLetteraBA(_dataThread));
            // Merge the two documents


            /*** Fix per Fideuram Direct, per le lettere merge su entrambi i pdfA e pdfB contemplando la lettere di accompagnamento, per la trimestrale la lettrea non ci deve essere da requisiti 29/08/2023 - Pino ***/
            if (!_dataThread.Periodico)
            {
                // Lettere
                _documentoFinale = MergeDocument.Merge(pdfA, pdfB);
            }
            else
            {
                if (letter.idModello == 6)
                    _documentoFinale = new MergeDocument(pdfB);
                else
                    _documentoFinale = MergeDocument.Merge(pdfA, pdfB);
            }
            /*************************************************************************************************************************************************************************************************************/


            // Save the PDF
            _data = _documentoFinale.Draw();

        }

        public int getIdentityReport(string rete, string codicefiscale, string tipoReport)
        {
            List<SqlParameter> parameters = new List<SqlParameter>
            {
                new SqlParameter
                {
                    ParameterName="Rete",
                    Value=rete
                },
                new SqlParameter
                {
                    ParameterName="CodiceFiscale",
                    Value=codicefiscale
                },
                new SqlParameter
                {
                    ParameterName="TipoReport",
                    Value=tipoReport
                }
            };



            //List<Parametro> parametri = new List<Parametro>();
            //Parametro parametro = new Parametro();
            //parametro.ParameterName = "Rete";
            //parametro.DbType = DbType.AnsiStringFixedLength;
            //parametro.Value = rete;
            //parametri.Add(parametro);

            //parametro = new Parametro();
            //parametro.ParameterName = "CodiceFiscale";
            //parametro.DbType = DbType.String;
            //parametro.Value = codicefiscale;
            //parametri.Add(parametro);

            ////FC Gestione Parallelizzazione Processi
            //// idReport � gestito dalla SP inserimento Gestione_Pdf_Ftp

            //parametro = new Parametro();
            //parametro.ParameterName = "TipoReport";
            //parametro.DbType = DbType.String;
            //parametro.Value = tipoReport;
            //parametri.Add(parametro);

            using (SQLServer db = new SQLServer(codicefiscale, rete))
            {
                return db.executeScalarWT(CACHE.GetIdReport, parameters).ToInt32();
            }

            //try
            //{
            //    return Convert.ToInt32(_dataThread.DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, CACHE.GetIdReport, parametri));
            //}
            //catch (Exception ex)
            //{
            //    logger.Errors(ex);
            //    return -1;
            //}

        }

        private static string getPdfForlder()
        {
            string pdfForder = "";
            try
            {

                return UtilityManager.getAppSetting("pathFolder");
            }
            catch (Exception e)
            {
                logger.Errors(e);
                throw e;
            }

        }


        /// <summary>
        /// ok
        /// </summary>
        /// <returns></returns>
        private byte[] getData()
        {
            if (_data == null)
            {
                //if (_tipologia == "report")
                //{
                this.completeIndice();
                //}
                for (int i = 0; i < _indexPage; i++)
                {
                    _document.Pages.Add((ImportedPage)_index[i]);
                }

                for (int i = 0; i < _core.Count; i++)
                {
                    _document.Pages.Add((ImportedPage)_core[i]);
                }

                if (_glossario)
                {
                    this.addGlossario();
                }
                // MIFID2 20180410 Provo a creare nuova sezione Avvertenze e Glossario
                //this.addNewGlossario();

                _document.InitialPage = 1;

                //genero i byte
                _data = _document.Draw();
            }

            return _data;
        }

        //public void renderPDF()
        //{
        //    this.renderPDF(_document.Title + ".pdf");
        //}

        //public void renderPDF(string downloadAsFileName)
        //{

        //    byte[] data = this.getData();
        //    PdfDocument pdfDoc = new PdfDocument(data);

        //    MergeDocument mDoc = new MergeDocument(pdfDoc);

        //    mDoc.CompressionLevel = 9;

        //    if (downloadAsFileName == null)
        //        mDoc.DrawToWeb();
        //    else
        //        mDoc.DrawToWeb(downloadAsFileName);
        //}

        //public void renderPDFFromDB(int identificativo)
        //{
        //    this.renderPDFFromDB(identificativo, null);
        //}

        //public void renderPDFFromDB(int identificativo, string downloadAsFileName)
        //{
        //    PdfDocument pdfDoc = new PdfDocument(this.getDataFromDB(identificativo));
        //    MergeDocument mDoc = new MergeDocument(pdfDoc);
        //    mDoc.CompressionLevel = 9;
        //    if (downloadAsFileName == null)
        //        mDoc.DrawToWeb();
        //    else
        //        mDoc.DrawToWeb(downloadAsFileName);
        //}

        //private byte[] getDataFromDB(int identificativo)
        //{
        //    List<Parametro> listaParametri = new List<Parametro>();
        //    Parametro id = new Parametro();
        //    id.ParameterName = "id";
        //    id.DbType = DbType.Int32;
        //    id.Value = identificativo;
        //    listaParametri.Add(id);

        //    return (byte[])DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServer, "sp_readPDFImage_New", listaParametri);
        //}
        //==============================================================
        public float getMargineLeft()
        {
            return _margineLEFT;
        }
        //==============================================================
        private float getMargineRight()
        {
            return _margineRIGHT;
        }
        //==============================================================
        public float getLastPos()
        {
            if (_writableYPot != 0)
                this.setLastPos(_writableYPot);
            return _writableY;
        }

        public float getLastPos(string combo)
        {
            //if(_writableYPot != 0;
            //    this.setLastPos(_writableYPot);
            //_writableYPot = 0;
            return _writableY;
        }

        //==============================================================
        public void setLastPos(float y)
        {
            //aggiorna la posizione da cui si pu� scrivere
            if (_saltoPagina && _currentPage < _corePage)
            {
                _page = _backPage;
                _currentPage = _corePage;
                _writableY = _margineUP + _writableYPot + _sectionSpace;
            }
            else
            {
                if (_writableYPot > y && y > 0)
                    _writableY += (_writableYPot + _sectionSpace);
                else
                    _writableY += (y + _sectionSpace);
            }
            _writableYold = _writableY;
            _saltoPagina = false;
            _writableYPot = 0;
        }
        //==============================================================
        public void setPotenzialeLastPos(float y, bool salto)
        {
            //aggiorna la posizione da cui si pu� scrivere
            _writableYPot = (y);
            _saltoPagina = salto;
        }
        //==============================================================
        public void returnLastPage()
        {
            //ritorno alla penultima pagina. Utile per il disegno delle sezioni in modalit� combo
            _writableY = _writableYold;
            _backPage = _page;
            _currentPage--;
            _page = (ImportedPage)_core[_core.Count - 2];
        }
        //==============================================================
        public void creaIndice()
        {
            System.IO.Stream file = _templateProvider.TemplateReport;
            PdfDocument pp = new PdfDocument(file);
            _indice = new ImportedPage(pp.GetPage(1));
            _indice.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(37, 122, 330, 13, 0, _templateProvider.ChapterBackgroundColor)); //ceTe.DynamicPDF.CmykColor.Red
            _indice.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Indice", 50, 119, 100, 8, _verdanaBold, 15, ceTe.DynamicPDF.CmykColor.White));

            this.SetTemplate(_indice);
            this.setPageFooter(_indice);
            this.setPageFooterNomeCliente(_indice);
            _index.Add(_indice);
            _indiceY = _margineUP + 30;
            _activeIndex = true;
        }
        //==============================================================
        private void completeIndice()
        {
            _margineDOWN = 105;

            if (_activeIndex)
            {
                ImportedPage app = (ImportedPage)_index[_indexPage];
                //int indexCount = _indexPage + 1; //uno per le avvertenze sistemare
                //V 
                int indexCount = _indexPage;
                //
                //if (_strutturaIndice.VoceIndice.Rows.Count > 25)
                //    //Era 2
                //    indexCount += 2;
                //else
                indexCount += 1;

                _indexPage++;

                int FontSizeIndice = 10;//12
                int interline = 14;//20

                //completa _indice
                foreach (DataSetIndice.VoceIndiceRow newVoce in _strutturaIndice.VoceIndice)
                {
                    if (_indiceY > (_pageHeight - (_margineDOWN + 50)))
                    {
                        this.creaIndice();
                        _indexPage++;
                        app = (ImportedPage)_index[_indexPage - 1];
                    }

                    if (newVoce.Tipologia == "chapter")
                    {
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(newVoce.Titolo, 50, _indiceY, 500, 12, _verdanaBold));
                        app.Elements.Add(new PageNumberingLabel(Convert.ToString(newVoce.Pagina + indexCount), 0, _indiceY, 550, 12, _verdanaBold, FontSizeIndice, ceTe.DynamicPDF.TextAlign.Right));
                    }
                    else
                    {
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(newVoce.Titolo, 80, _indiceY, 500, 12, _verdana, FontSizeIndice - 1));//11
                        app.Elements.Add(new PageNumberingLabel(Convert.ToString(newVoce.Pagina + indexCount), 0, _indiceY, 550, 12, _verdana, FontSizeIndice, ceTe.DynamicPDF.TextAlign.Right));
                    }

                    _indiceY += interline;//20
                }

                if (_glossario)
                {
                    // MIFID2 20180406 Modificato il titolo del glossario
                    //app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Glossario", 50, _indiceY, 500, 12, _verdanaBold));
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Avvertenze e Glossario", 50, _indiceY + 10, 500, 12, _verdanaBold));
                    //--MIFID2
                    //app.Elements.Add(new PageNumberingLabel(Convert.ToString(_core.Count + indexCount + 2), 0, _indiceY, 550, 12, _verdanaBold, 12, ceTe.DynamicPDF.TextAlign.Right));
                    app.Elements.Add(new PageNumberingLabel(Convert.ToString(_core.Count + indexCount + 1), 0, _indiceY + 10, 550, 12, _verdanaBold, FontSizeIndice, ceTe.DynamicPDF.TextAlign.Right));
                }

            }
            //else
            //    addNavigatore();


            ///Aggiungo pagina delle AVVERTENZE
            ///V
            //string pdfRelativePath;

            //System.Reflection.Assembly thisExe;
            //thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            //if (_dataThread.Rete == "F")
            //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeBF");
            //else
            //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeSP");

            //System.IO.Stream file = thisExe.GetManifestResourceStream(pdfRelativePath);


            //PdfDocument pp = new PdfDocument(file);
            //_indice = new ImportedPage(pp.GetPage(1));

            //this.SetTemplate(_indice);
            //this.setPageFooter(_indice);
            //this.setPageFooterNomeCliente(_indice);
            //_index.Add(_indice);
            //_indiceY = _margineUP + 30;
            //_activeIndex = true;

            //_indexPage++;
            //_indiceY = _margineUP;
            //V
        }
        //==============================================================

        public void creaCopertina(string report, bool withName)
        {

            //string pdfRelativePath;
            FormatNum conv = new FormatNum();

            //System.Reflection.Assembly thisExe;
            //thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            //if (_dataThread.Rete == "F")
            //    pdfRelativePath = UtilityManager.getAppSetting("Copertina");
            //else
            //    pdfRelativePath = UtilityManager.getAppSetting("CopertinaSP");

            //System.IO.Stream file = thisExe.GetManifestResourceStream(pdfRelativePath);

            System.IO.Stream file = _templateProvider.TemplateCopertina;

            ImportedPage app;
            PdfDocument pp = new PdfDocument(file);

            app = new ImportedPage(pp.GetPage(1));

            /*** Fix Direct Banck 12/03/2023 - Pino ***/
            //app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(report.ToUpper(), 157, 231, 220, 8, _verdanaBold, 18, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.White));

            if (!_dataThread.Periodico)
            {
                if (_dataThread.ReportsType[0].IdModello == 6)
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report di Benvenuto", 70, 231, 300, 8, _verdanaBold, 18, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.White));
                else
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(report.ToUpper(), 157, 231, 220, 8, _verdanaBold, 18, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.White));
            }
            else
            {
                if (_dataThread.ReportsType.Exists(e => e.IdModello == 6))
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report di Monitoraggio", 70, 231, 300, 8, _verdanaBold, 18, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.White));
                else
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(report.ToUpper(), 157, 231, 220, 8, _verdanaBold, 18, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.White));
            }
            /******************************************/

            if (withName)
            {
                if (CACHE.Periodico)
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + _dataThread.DataFineTrimestreCorrente.ToLongDateString(), 88, 265, 300, 8, _verdana, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                else
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString(), 88, 265, 300, 8, _verdana, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));



                if (_dataThread.CodiceFiscale.Length == 11)
                {
                    //persona giuridica
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " " + conv.CapitalizeText(_dataThread.NomeCliente), 88, 280, 300, 8, _verdanaBold, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                }
                else
                {
                    if (_dataThread.CodiceFiscale.Contains("@"))
                    {
                        // Fiduciaria
                        string[] codiceMandato = _dataThread.CodiceFiscale.Split('@');
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " " + conv.CapitalizeText(_dataThread.NomeCliente.Replace("$", "") + " - " + codiceMandato[1].ToString()), 88, 280, 300, 8, _verdanaBold, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));

                    }
                    else
                    {
                        //persona fisica
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.NomeCliente) + " " + conv.CapitalizeText(_dataThread.CognomeCliente), 88, 280, 300, 8, _verdanaBold, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));

                    }
                }
            }
            else
                app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString(), 88, 265, 300, 8, _verdana, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            _index.Add(app);
            _indexPage++;
            //_copertina = true;
        }

        public void setPageTitolo(string label)
        {

            if (_writableY != _margineUP)
                this.addPage();

            //Adriano 20171109 per allargare l'area per un titolo molto lungo
            int rectangleWidth = 400;
            int textWidth = 400;

            if (label.Length > 46) //Andrea Modifica IWBank
            {
                rectangleWidth = 510; //475;
                textWidth = 500;
            }

            //_page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, 122, 400, 17, 0, _templateProvider.ChapterBackgroundColor)); //ceTe.DynamicPDF.CmykColor.Red
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, 122, rectangleWidth, 17, 0, _templateProvider.ChapterBackgroundColor)); //ceTe.DynamicPDF.CmykColor.Red

            //--Adriano

            if (_activeIndex)
            {
                _chapterNum++;
                _sectionNum = 1;
                updateIndice(label, "chapter");
                //Adriano 20171109 per allargare l'area per un titolo molto lungo
                //_page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, 120, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, 120, textWidth, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));

                //--Adriano
            }
            else
            {
                //if (_tipologia != "report")
                //_page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, 120, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));

                //Adriano 20171109 per allargare l'area per un titolo molto lungo
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, 120, textWidth, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));

                //--Adriano
                //else
                //{
                //    _chapterNum++;
                //    _sectionNum = 1;
                //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, 120, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //}
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="label"></param>
        /// <param name="eliminaspaziatura"></param>
        public void setPageTitolo(string label, bool eliminaspaziatura)
        {
            setPageTitolo(label);
            if (eliminaspaziatura)
                _writableY = 150;
        }


        public void setChapterTitolo(string label)
        {
            if ((_writableY + 100) > (_pageHeight - _margineDOWN))
                this.addPage();

            ///PER ALLINEARE IL TITOLO ALLA RIGA DELLA PAGINA
            if (_writableY == _margineUP)
                _writableY = 142;
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 400, 17, 0, _templateProvider.ChapterBackgroundColor)); //ceTe.DynamicPDF.CmykColor.Red
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 522, 0.4F, 0, _templateProvider.ChapterBackgroundColor)); //ceTe.DynamicPDF.CmykColor.Red

            if (_activeIndex)
            {
                _chapterNum++;
                _sectionNum = 1;
                updateIndice(label, "chapter");
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
            }
            else
            {
                //if (_tipologia != "report")
                //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //else
                //{
                _chapterNum++;
                _sectionNum = 1;
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //}
            }
            _writableY += 20;

        }


        /// <summary>
        /// E' il titolo della pagina scritto bianco su sfondo rosso.
        /// A differenza di setPageTitolo si posiziona a seconda della posizione del cursore.
        /// il parametro Height � lo spazio necessario al disegno del titolo capitolo piu la prima sezione.
        /// </summary>
        /// <param name="label"></param>
        /// <param name="Height"></param>
        public void setChapterTitolo(string label, float Height, bool eliminaspaziatura)
        {
            this.setChapterTitolo(label, Height);

            if (eliminaspaziatura)
                _writableY -= 10;
        }


        public void setChapterTitolo(string label, float Height)
        {
            if ((_writableY + Height + 50) > (_pageHeight - _margineDOWN))
                this.addPage();

            ///PER ALLINEARE IL TITOLO ALLA RIGA DELLA PAGINA
            if (_writableY == _margineUP)
                _writableY = 142;
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 400, 17, 0, _templateProvider.ChapterBackgroundColor));//ceTe.DynamicPDF.CmykColor.Red
            //_page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 522, 0.4F, 0, _templateProvider.ChapterBackgroundColor)); //ceTe.DynamicPDF.CmykColor.Red

            if (_activeIndex)
            {
                _chapterNum++;
                _sectionNum = 1;
                updateIndice(label, "chapter");
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
            }
            else
            {
                //if (_tipologia != "report")
                //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //else
                //{
                _chapterNum++;
                _sectionNum = 1;
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //}
            }
            _writableY += 20;
        }

        public void setChapterHeader(string label)
        {
            int m = (int)((float)label.Length / 135) + 2;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY - 10, 520, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), 9, false);
            text.Height = text.GetRequiredHeight();
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += text.Height + 10;
        }

        /// <summary>
        /// Stampa il testo del paragrafo e elimina lo spazio tra il titolo del capitolo e il testo che viene stampato.
        /// Usato solo per la S57
        /// </summary>
        /// <param name="label"></param>
        public void setChapterHeader(string label, bool eliminaspaziatura)
        {
            setChapterHeader(label);
            if (eliminaspaziatura)
                _writableY -= 10;
        }

        public void setChapterHeader(string label, float height)
        {
            if (label != string.Empty)
            {
                int m = (int)((float)label.Length / 135) + 2;
                if (this.checkMargin((m - 1) * 20 + height)) this.addPage();
                FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY - 10, 520, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), 9, false);
                text.Height = text.GetRequiredHeight();
                text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
                _page.Elements.Add(text);
                _writableY += text.Height + 10;
            }
        }
        //L
        public void setChapterHeader(string label, int x, int width, float font, string classeSpecificaDaFixare = null, string _TipoReport = null, string _paginaRimossa = null, string _ultimaSezione = null)
        {
            int baseGap = 10;
            //Aumento il valore per diminuire la posizione Y del testo
            switch (classeSpecificaDaFixare)
            {
                case "S151":
                    baseGap = 57;
                    break;
                case "S177":
                    baseGap = 40;
                    break;
                case "FD178":
                    baseGap = +15; //-5;
                    break;
                case "FD177":
                    baseGap = +40;
                    break;
                case "S170":
                    if (_TipoReport == "DIAGNOSI")
                    {
                        if (_paginaRimossa == "S")
                        {
                            if ((_ultimaSezione == "S184") || (_ultimaSezione == "S178") || (_ultimaSezione == "S179"))
                                baseGap = +20;
                            else
                                baseGap = +70;
                        }
                        else
                            baseGap = +65;
                    }
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(classeSpecificaDaFixare) && classeSpecificaDaFixare == "S177")
                if (!string.IsNullOrEmpty(_TipoReport) && _TipoReport.Equals(TipologiaReport.DIAGNOSI.ToString()))
                    baseGap = 25;

            int m = (int)((float)label.Length / 135) + 2;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + x, _writableY - baseGap, width, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), font, false);
            text.Height = text.GetRequiredHeight();
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);

            //Aggiusto l'altezza della S177 per recuperare spazio tra i testi
            if (!string.IsNullOrEmpty(classeSpecificaDaFixare) && (classeSpecificaDaFixare == "S177" || classeSpecificaDaFixare == "FD178"))
            {
                if (!string.IsNullOrEmpty(_TipoReport) && _TipoReport.Equals(TipologiaReport.DIAGNOSI.ToString()))
                    _writableY += text.Height + 15;
                else if (classeSpecificaDaFixare == "FD178")
                {
                    _writableY += text.Height + 50;
                }
                else
                    _writableY += text.Height - 10;
            }
            else
            {
                _writableY += text.Height + 10;
            }
        }

        public void setChapterHeader(string label, int x, int y, int width, float font)
        {
            int m = (int)((float)label.Length / 135) + 2;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + x, y, width, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), font, false);
            text.Height = text.GetRequiredHeight();
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += text.Height + 10;
        }

        private void setPageFooterNomeCliente(ImportedPage pp)
        {
            FormatNum conv = new FormatNum();
            ////LATO SX
            //if (_modalitaAnonima == 1)
            //{
            //if (_tipologia != "report")
            //    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Scheda prodotta " + DateTime.Now.ToLongDateString() + " sui dati di ", _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));
            //else

            if (CACHE.Periodico)
                pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + _dataThread.DataFineTrimestreCorrente.ToLongDateString() + " per ", _margineLEFT - 5, _pageHeight - _templateProvider.MarginDown + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));
            else
                pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString() + " per ", _margineLEFT - 5, _pageHeight - _templateProvider.MarginDown + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));

            if (_dataThread.CodiceFiscale.Length == 11)//persona giuridica
                pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " " + conv.CapitalizeText(_dataThread.NomeCliente), _margineLEFT - 5, _pageHeight - _templateProvider.MarginDown + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.CmykColor.Black));
            else
            {
                if (_dataThread.CodiceFiscale.Contains("@")) // Fiduciaria
                {
                    string[] codiceMandato = _dataThread.CodiceFiscale.Split('@');
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " - " + codiceMandato[1], _margineLEFT - 5, _pageHeight - _templateProvider.MarginDown + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.CmykColor.Black));

                }
                else //persona fisica
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.NomeCliente) + " " + conv.CapitalizeText(_dataThread.CognomeCliente), _margineLEFT - 5, _pageHeight - _templateProvider.MarginDown + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.CmykColor.Black));
            }

            //}
            //else
            //{
            //    if (_tipologia != "report")
            //        pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Scheda prodotta " + DateTime.Now.ToLongDateString(), _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));
            //    else
            //        pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString(), _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));

            //}
        }

        public void setNotaPieDiPagina(string label)
        {
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _pageHeight - _margineDOWN, 520, 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            text.Height = text.GetRequiredHeight();
            text.Y -= text.Height - 10;
            _page.Elements.Add(text);
            _margineDOWN += text.Height;
        }
        public void setNotaPieDiPagina(string label, string id)
        {
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _pageHeight - _margineDOWN, 520, 20, new FontFamily("pipp", _verdana), 7, false);
            text.ID = id;
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            text.Height = text.GetRequiredHeight();
            text.Y -= text.Height - 10;

            //se l'elemento � stato gia inserito nella pagina non lo inserisco.
            PageElement element = null;
            element = _page.Elements.GetPageElementByID(id);

            if (element == null)
                _page.Elements.Add(text);

            _margineDOWN += text.Height;
        }

        private void setPageFooter(ImportedPage pp)
        {
            FormatNum conv = new FormatNum();

            /**** Fix Direct Banck 13/03/2023 - Pino ***/
            ////LATO DX
            //pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Private Banker", _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 15, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            ////V 
            //string temp = ClsFunzioniGeneriche.FormattaIndirizzo(_dataThread.IndirizzoAgente);


            //pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((conv.CapitalizeText(_dataThread.NomeAgente) + " " + conv.CapitalizeText(_dataThread.CognomeAgente)).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            //pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((temp + " - " + _dataThread.CapAgente + " " + _dataThread.CittaAgente).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 35, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            //pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(("Tel " + _dataThread.TelefonoAgente).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 45, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));

            if (!_dataThread.Periodico)
            {
                if (_dataThread.ReportsType.Find(f => f.Descrizione.ToUpper() == "DIAGNOSI").IdModello != 6)
                {
                    //LATO DX
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Private Banker", _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 15, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                    //V 
                    string temp = ClsFunzioniGeneriche.FormattaIndirizzo(_dataThread.IndirizzoAgente);


                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((conv.CapitalizeText(_dataThread.NomeAgente) + " " + conv.CapitalizeText(_dataThread.CognomeAgente)).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((temp + " - " + _dataThread.CapAgente + " " + _dataThread.CittaAgente).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 35, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(("Tel " + _dataThread.TelefonoAgente).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 45, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                }
            }
            else
            {
                if (_dataThread.ReportsType.Exists(e => e.IdModello != 6))
                {
                    //LATO DX
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Private Banker", _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 15, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                    //V 
                    string temp = ClsFunzioniGeneriche.FormattaIndirizzo(_dataThread.IndirizzoAgente);


                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((conv.CapitalizeText(_dataThread.NomeAgente) + " " + conv.CapitalizeText(_dataThread.CognomeAgente)).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label((temp + " - " + _dataThread.CapAgente + " " + _dataThread.CittaAgente).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 35, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(("Tel " + _dataThread.TelefonoAgente).TrimEnd(), _templateProvider.MarginRight, _pageHeight - _templateProvider.MarginDown + 45, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                }
            }
            /*******************************************/
        }

        private void updateIndice(string label, string type)
        {
            DataSetIndice.VoceIndiceRow newVoce = _strutturaIndice.VoceIndice.NewVoceIndiceRow();

            //aggiorna _indice
            if (type == "chapter")
            {
                newVoce.Tipologia = "chapter";
                newVoce.Titolo = _chapterNum + ". " + label;
                newVoce.Pagina = _corePage;
            }
            else
            {
                newVoce.Tipologia = "Section";
                newVoce.Titolo = _chapterNum + "." + _sectionNum + " " + label;
                newVoce.Pagina = _corePage;
            }

            _strutturaIndice.VoceIndice.AddVoceIndiceRow(newVoce);
        }

        public void setSezHeader(string label)
        {
            int m = (int)((float)label.Length / 100) + 1;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY - 10, 520, m * 20, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), 9, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            text.Height = text.GetRequiredHeight();
            _page.Elements.Add(text);
            _writableY += text.Height + 10;
        }

        public void setSezFooter(string label, float y)
        {
            if (_writableYPot > y)
                y = _writableYPot;
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY + y, 520, m * 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += (m * 10);
        }

        public void setSezFooter(string label, float y, float spaceX)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + spaceX, _writableY + y, 520 - spaceX, m * 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += (m * 10);
        }

        public void setSezFooter(string label, float y, float spaceX, float font)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + spaceX, _writableY + y, 520 - spaceX, m * 20, new FontFamily("pipp", _verdana), font, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += (m * 10);
        }

        public void setHeaderSpace(int space)
        {
            _writableY += space;
        }
        //==============================================================
        public void setSezTitoloDiagnosi(string label, string classeSpecificaDaFixare = null)
        {
            if (this.checkMargin(50)) this.addPage();

            int baseGap = 15;
            //Aumento lo spazio per diminuire la distanza tra il titolo e l'inizio del paragrafo 
            switch (classeSpecificaDaFixare)
            {
                case "S151":
                    baseGap = 53;
                    break;
                case "S152":
                    baseGap = 65;
                    break;
                case "S177":
                    baseGap = 45;
                    break;
                case "S170":
                    baseGap = 60;
                    break;
                case "FD151":
                    baseGap = 33;
                    break;
                default:
                    break;
            }
            if (_reportType.TipoReport.ToString() == "DIAGNOSI" && classeSpecificaDaFixare == "S177") baseGap = 25;

            if (!string.IsNullOrWhiteSpace(label))
            {
                if (_activeIndex)
                {
                    updateIndice(label, "section");
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - baseGap, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }
                else
                {
                    //if (_tipologia != "report")
                    //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    //else
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - baseGap, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }

                //Aggiusto l'altezza delle classi per recuperare spazio tra i testi
                if (_reportType.TipoReport.ToString() == "DIAGNOSI" && classeSpecificaDaFixare == "S177")
                {
                    _writableY += 25;
                }
                else
                {
                    switch (classeSpecificaDaFixare)
                    {
                        case "S177":
                            _writableY += 10;
                            break;
                        case "S151":
                            _writableY += 25;
                            break;
                        case "FD151":
                            _writableY += 5;
                            break;
                        case "FD177":
                            _writableY += 50;
                            break;
                        case "FD178":
                            _writableY += 50;
                            break;
                        default:
                            _writableY += 25;
                            break;
                    }
                }

                //if (!string.IsNullOrEmpty(classeSpecificaDaFixare) && classeSpecificaDaFixare == "S177")
                //{
                //    _writableY += 10;
                //}
                //else
                //{
                //    _writableY += 25;
                //}

            }
        }
        public void setSezTitolo(string label)
        {
            if (this.checkMargin(50)) this.addPage();

            if (label != " " && label != "")
            {
                if (_activeIndex)
                {
                    updateIndice(label, "section");
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }
                else
                {
                    //if (_tipologia != "report")
                    //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    //else
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }

                //_writableY += 25;
                _writableY += 15;
            }
        }
        public void setSezTitoloCustom(string label)
        {
            if (this.checkMargin(50)) this.addPage();

            if (label != " " && label != "")
            {
                if (_activeIndex)
                {
                    updateIndice(label, "section");
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 35, 530, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }
                else
                {
                    //if (_tipologia != "report")
                    //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    //else
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }

                //_writableY += 25;
                _writableY += 15;
            }
        }

        /// <summary>
        /// Scrive il titolo della sezione senza aggiungere l'indicizzazione.
        /// usato nella 102
        /// </summary>
        /// <param name="label"></param>
        public void setSezTitoloWithoutNumber(string label)
        {
            if (this.checkMargin(50))
                this.addPage();

            if (label != " " && label != "")
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 10, ceTe.DynamicPDF.CmykColor.Black));
            _writableY += 15;
        }

        /// <summary>
        /// Scrive il titolo del paragrafo in modalit� indicizzata.
        /// Elimina la spaziatura di 25 pixel tra il titolo e il testo successivo e lascia uno spazio di 10 pixel.
        /// </summary>
        /// <param name="label"></param>
        public void setSezTitolo(string label, bool eliminaspaziatura)
        {
            this.setSezTitolo(label);
            if (eliminaspaziatura)
                _writableY -= 15;

        }

        public void setSezTitolo(string label, float Height)
        {
            if ((_writableY + Height + 20) > (_pageHeight - _margineDOWN))
                this.addPage();

            this.setSezTitolo(label);
        }
        //==============================================================
        public void setTitolo(string label, float Height)
        {
            if (label != string.Empty)
            {
                if ((_writableY + Height + 20) > (_pageHeight - _margineDOWN))
                    this.addPage();
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT - 5, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                _writableY += 25;
            }
        }
        //==============================================================

        /// <summary>
        /// Scrive il titolo del paragrafo in modalit� non indicizzata. 
        /// Aggiunge 25 pixel di spazio sulla Y.
        /// </summary>
        /// <param name="label"></param>
        public void setTitolo(string label)
        {
            if (this.checkMargin(60)) this.addPage();
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT - 5, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
            _writableY += 25;
        }


        /// <summary>
        /// Scrive sulla pagina il testo passato in input.
        /// Il tipo di carattere usato � quello del testo introduttivo delle sezioni.
        /// Dimensione del carattere prefissata a 7
        /// </summary>
        /// <param name="label">testo da scrivere</param>
        /// <param name="y">y su cui verr� scritto il testo</param>
        /// <param name="spaceX">larghezza della label su cui verr� scritto il testo.</param>
        public void writeText(string label, float y, float spaceX)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + spaceX, y, 520 - spaceX, m * 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
        }

        public void writeText(float x, float y, string label, float size, float larghezzalabel, ceTe.DynamicPDF.TextAlign align)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, x, y, larghezzalabel, m * 20, new FontFamily("pipp", _verdana), size, false);
            text.Style.Paragraph.Align = align;
            _page.Elements.Add(text);
        }


        /// <summary>
        /// Scrive sulla pagina il testo passato in input.
        /// Il tipo di carattere usato � quello del testo introduttivo delle sezioni.
        /// Larghezza della label su cui verr� scritto il testo fissato a 200
        /// </summary>
        /// <param name="x">x</param>
        /// <param name="y">y</param>
        /// <param name="label">testo da scrivere</param>
        /// <param name="size">dimensione del testo</param>
        public void writeText(float x, float y, string label, float size)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, x, y, 200, m * 20, new FontFamily("pipp", _verdana), size, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
        }

        /// <summary>
        /// Scrive sulla pagina il testo passato in input.
        /// Il tipo di carattere usato � quello del testo introduttivo delle sezioni.
        /// Larghezza della label su cui verr� scritto il testo fissato a 200
        /// </summary>
        /// <param name="x">x</param>
        /// <param name="y">y</param>
        /// <param name="label">testo da scrivere</param>
        /// <param name="size">dimensione del testo</param>
        /// <param name="larghezzalabel">larghezza della label su cui viene scritto il testo.</param>
        public void writeText(float x, float y, string label, float size, float larghezzalabel)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, x, y, larghezzalabel, m * 20, new FontFamily("pipp", _verdana), size, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
        }

        public void InsertGraficoS96(Chart grafico, float x, float y)
        {
            try
            {
                _imgGrafico = new System.IO.MemoryStream();
                //Preserve the orginal width and height for the Chart

                float w = (float)(grafico.Width.Value);
                float h = (float)grafico.Height.Value;

                //Set the sutiable chart resoltion -- default is 96 DPI
                grafico.ImageResolution = 300;
                //save the chart as image
                grafico.Save(_imgGrafico, ChartImageFormat.Png);
                Image img = new Image(_imgGrafico, x, y, 1);
                //set the orginal width and height to the chart image
                img.Width = w;
                img.Height = h;
                _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try
                {
                    logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }


        public void InsertGraficoS169(Chart grafico, float x, float y)
        {
            try
            {
                _imgGrafico = new System.IO.MemoryStream();
                //Preserve the orginal width and height for the Chart

                float w = (float)(grafico.Width.Value);
                float h = (float)grafico.Height.Value;

                //Set the sutiable chart resoltion -- default is 96 DPI
                grafico.ImageResolution = 300;
                //save the chart as image
                grafico.Save(_imgGrafico, ChartImageFormat.Png);
                Image img = new Image(_imgGrafico, x, y, 1);
                //set the orginal width and height to the chart image
                img.Width = w;
                img.Height = h;
                _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try
                {
                    logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }

        public void InsertGraficoS132(Chart grafico, float x, float y)
        {
            try
            {
                _imgGrafico = new System.IO.MemoryStream();
                //Preserve the orginal width and height for the Chart

                float w = (float)(grafico.Width.Value);
                float h = (float)grafico.Height.Value;

                //Set the sutiable chart resoltion -- default is 96 DPI
                grafico.ImageResolution = 300;
                //save the chart as image
                grafico.Save(_imgGrafico, ChartImageFormat.Png);
                Image img = new Image(_imgGrafico, x, y, 1);
                //set the orginal width and height to the chart image
                img.Width = w;
                img.Height = h;
                _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try
                {
                    logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }


        public void InsertGrafico(Chart grafico, float x, float y, int resolution)
        {
            try
            {

                Image img = null;
                //Preserve the orginal width and height for the Chart
                float w = (float)(grafico.Width.Value);
                float h = (float)grafico.Height.Value;
                //Set the sutiable chart resoltion -- default is 96 DPI
                grafico.ImageResolution = resolution;
                using (System.IO.Stream _imgGrafico_ = new System.IO.MemoryStream())
                {
                    //save the chart as image
                    grafico.Save(_imgGrafico_, ChartImageFormat.Png);
                    //grafico.Save(@"C:\Ftp\a"+Guid.NewGuid().ToString()+".png", ChartImageFormat.Png);
                    //Thread.Sleep(100);                   
                    img = new Image(_imgGrafico_, x, y, 1);
                    img.Width = w;
                    img.Height = h;
                }
                //set the orginal width and height to the chart image
                _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try
                {
                    logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }

        public System.Drawing.Bitmap CropImage(System.Drawing.Bitmap b, System.Drawing.Rectangle r)
        {
            System.Drawing.Bitmap nb = new System.Drawing.Bitmap(r.Width, r.Height);
            nb.SetResolution(b.HorizontalResolution, b.VerticalResolution);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(nb);
            g.DrawImage(b, -r.X, -r.Y);
            return nb;
        }

        public void InsertGrafico(Chart grafico, float x, float y, int resolution, float bottomCutPercentage)
        {
            try
            {
                //S85
                Image img = null;
                //Preserve the orginal width and height for the Chart
                float w = (float)(grafico.Width.Value);
                float h = (float)grafico.Height.Value;
                //Set the sutiable chart resoltion -- default is 96 DPI
                grafico.ImageResolution = resolution;
                if (!Directory.Exists(@"C:\Temp\Trimestrale"))
                    Directory.CreateDirectory(@"C:\Temp\Trimestrale");


                string filename1 = Guid.NewGuid().ToString() + ".png";
                string filename2 = Guid.NewGuid().ToString() + ".png";
                string path1 = @"C:\Temp\Trimestrale\" + filename1;
                string path2 = @"C:\Temp\Trimestrale\" + filename2;

                while (File.Exists(path1))
                {
                    filename1 = Guid.NewGuid().ToString() + ".png";
                    path1 = @"C:\Temp\Trimestrale\" + filename1;
                }

                while (File.Exists(path2))
                {
                    filename2 = Guid.NewGuid().ToString() + ".png";
                    path2 = @"C:\Temp\Trimestrale\" + filename2;
                }

                try { logger.Info("S85" + path1 + path2); } catch (Exception ex) { logger.Error("S85 " + ex.Message); }

                grafico.Save(path1, ChartImageFormat.Png);
                var tmpImg = System.Drawing.Image.FromFile(path1);
                tmpImg = CropImage((System.Drawing.Bitmap)tmpImg, new System.Drawing.Rectangle(0, 0, (int)tmpImg.Width, (int)(tmpImg.Height - (bottomCutPercentage * tmpImg.Height / 100))));
                tmpImg.Save(path2);

                img = new Image(path2, x, y, 1);
                img.Width = w;
                img.Height = h - (h * bottomCutPercentage / 100);
                _page.Elements.Add(img);

                try
                {
                    File.Delete(path1);
                    logger.Info(path1);
                }
                catch (Exception ex)
                {
                    logger.Info(ex.Message);
                }

                try
                {
                    File.Delete(path2);
                    logger.Info(path2);
                }
                catch (Exception ex)
                {
                    logger.Info("InsertGrafico: " + ex.Message);
                }
                //using (System.IO.Stream _imgGrafico_ = new System.IO.MemoryStream())
                //{
                //    //save the chart as image
                //    grafico.Save(_imgGrafico_, ChartImageFormat.Png);
                //    //grafico.Save(@"C:\Ftp\a"+Guid.NewGuid().ToString()+".png", ChartImageFormat.Png);
                //    //Thread.Sleep(100);                   
                //    img = new Image(_imgGrafico_, x, y, 1);
                //    img.Width = w;
                //    img.Height = h;
                //}
                //set the orginal width and height to the chart image

            }
            catch (Exception ex)
            {
                try
                {
                    logger.Error(String.Concat(ex.Message + ((ex.InnerException != null) ? ex.InnerException.Message : ""), " ", grafico.ToString()));
                }
                catch
                {
                    logger.Error(ex.Message);
                }
            }
            finally
            {
                grafico.Dispose();
            }

        }

        public void InsertGrafico(Chart grafico, float x, float y)
        {
            _imgGrafico = new System.IO.MemoryStream();
            grafico.Save(_imgGrafico, ChartImageFormat.Png);
            Image img = new Image(_imgGrafico, x, y, 1);
            //img.SetDpi(300);
            _page.Elements.Add(img);
        }

        public void Grilia(int R)
        {


            float X = 0;
            float Y = -3;

            string str = " 0" + new string('-', 300);

            for (int i = 0; i < 100; i++)
            {
                str = " " + (Y + 3) + new string('-', 300);
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(str, X, getLastPos() + Y, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                Y += 2;
                str = " " + new string('-', 300);
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(str, X, getLastPos() + Y, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                Y += 2;
            }
            X -= 1;
            for (int i = 0; i < 100; i++)
            {
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("|" + X.ToString(), getMargineLeft() + X, getLastPos() + R, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                X += 5;
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("|", getMargineLeft() + X, getLastPos() + R + 3, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                X += 5;
            }

        }
        public void InsertTable(PageElement elem)
        {
            _page.Elements.Add(elem);
        }



        public void changePage(int x, float y)
        {
            //disegna freccia pi� scritta.
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua alla pagina successiva", x - 75, _pageHeight - _margineDOWN - 6, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);

            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, x + _margineLEFT, _pageHeight - _margineDOWN - 5, 0.2F));
            this.addPage();
        }

        /// <summary>
        /// Disegna la frecce e il testo "continua alla pagina successiva" di rimando del salto pagina delle tabelle.
        /// X e Y sono gia definite.
        /// X=435,Y=719.
        /// </summary>
        public void changePage()
        {
            int y = 730;

            if (_notaPieDiPagina != null && _notaPieDiPagina.Length > 0)
                y -= 23;
            //disegna freccia pi� scritta.
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua alla pagina successiva", 450, y, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, 435, y - 1, 0.2F));
            this.addPage();
        }



        /// <summary>
        /// Disegna la frecce e il testo "continua alla pagina successiva" di rimando del salto pagina delle tabelle.
        /// Disegna le note con posizionamento "Pi�DiPagina" aggiunte alla pagina(document).
        /// X fissata a 435, la Y � variabile a seconda delle Note presenti a pi� di pagina. (Decremento di 15 pixel per ogni nota presente o di 30 a seconda della lunghezza della nota.)
        /// Utilizzato solo dalla classe Tabella.
        /// Non sono all'ultima pagina della tabella ma sto ancora facendo il saltopagina.
        /// </summary>       
        public void changePage(string idtabella)
        {
            int y = 739;

            //_note.RemoveAll(delegate(Nota t) { return t.IdTabellaAssociata != idtabella; }); // rimuovo le note non appartenenti alla tabella che sto stampando.

            // in caso di presenza di note a pi� di pagina decremento la y su cui stampo la label di cambio pagina.           
            foreach (Nota objNota in _note.FindAll(delegate (Nota t) { return t.Posizionamento == Nota.TipologiaPosizionamento.PieDiPagina; }))
            {
                if (objNota.Testo.Length < 200)
                    y -= 15;
                else
                    y -= 30;
            }


            //disegna freccia pi� scritta.
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua alla pagina successiva", 450, y, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, 435, y - 1, 0.2F));


            // aggiungo la pagina
            this.addPage(idtabella, false); // se passa sicuramente la tabella sta facendo il saltopagina 

        }

        /// <summary>
        /// //Aggiunge "continua dalla pagina precedente" sulla pagina successiva
        /// </summary>
        /// <param name="x"></param>
        public void nextPage(float x)
        {
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua dalla pagina precedente", x + 10, _margineUP - 31, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);

            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, x - 5, _margineUP - 33, 0.2F));
            _writableY += 5;
        }
        //==============================================================
        /// <summary>
        /// Aggiunge una nuova pagina al documento
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public void addPage()
        {
            StampaNote(); // stampo tutte le note aggiunte al documento prima di aggiungere una nuova pagina 

            _margineDOWN = 105;
            _note.Clear(); // azzero la collezione delle note.
            _ynotapiedipagina = 740;

            if (_corePage == _currentPage)
            {

                this.setFilePath();
                this.SetTemplate(_page);
                this.setPageFooter(_page);
                //if (_nomeCliente)
                this.setPageFooterNomeCliente(_page);
                //this.setDisclaimer(page);
                _corePage++;
                _currentPage = _corePage;
                _writableYold = _writableY;
                _writableY = _margineUP;
            }
            else
            {
                _page = _backPage;
                _currentPage = _corePage;
                _writableY = _margineUP;
            }

            if (!_saltoPagina)
                _writableYPot = 0;

        }



        /// <summary>
        /// Aggiunge una nuova pagina al documento.
        /// Utilizzato solo quando si sta stampando una tabella e questa ha il saltopagina.
        /// Questa funzione � richiamata solo dalla funzione "changePage" ovvero solo quando la tabella sta effettuando il saltopagina.
        /// </summary>
        /// <param name="idtabella"></param>
        /// <param name="eliminaNote"></param>
        private void addPage(string idtabella, bool eliminaNote)
        {
            StampaNote(idtabella);

            _ynotapiedipagina = 740;

            #region Aggiungo la pagina al documento

            _margineDOWN = 105;

            if (_corePage == _currentPage)
            {

                this.setFilePath();
                this.SetTemplate(_page);
                this.setPageFooter(_page);
                this.setPageFooterNomeCliente(_page);
                //this.setDisclaimer(page);
                _corePage++;
                _currentPage = _corePage;
                _writableYold = _writableY;
                _writableY = _margineUP;
            }
            else
            {
                _page = _backPage;
                _currentPage = _corePage;
                _writableY = _margineUP;

            }
            if (!_saltoPagina)
                _writableYPot = 0;


            #endregion

            // in questo caso le note associate alla tabella (che sta facendo il saltopagina) solo quelle con posizionamento a Pi�DiPagina 
            // e vanno riportate anche nella nuova pagina.
            // Rimuovo tutte le note perche sono state gi� stampate e lascio quelle associate alla tabella che fa il saltopagina.
            if (eliminaNote)
                _note.Clear();
            else
                _note.RemoveAll(delegate (Nota obj) { return (obj.IdTabellaAssociata != idtabella); });

        }

        public void RemoveLastPage(int index)
        {
            _core.RemoveAt(index);
            //int c = _index.Count;
            //int v = _indexPage;
        }

        /// <summary>
        /// OK
        /// </summary>
        /// <param name="_page"></param>
        private void setFilePath()
        {
            logger.Debug("SetFilePath.CodiceFiscale=" + _dataThread.CodiceFiscale + "_Rete=" + _dataThread.Rete);


            string relativePath = "";
            //if (_tipologia != "report")
            //{

            //System.Reflection.Assembly thisExe;
            //thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            //if (_dataThread.Rete == "F")
            //{
            //    //FC 26062015 Aggionamento nuova Ragione Sociale
            //    //_banca = "Banca Fideuram";
            //    _banca = "Fideuram";
            //    relativePath = UtilityManager.getAppSetting("TemplateReport");
            //}
            //else
            //{
            //    _banca = "Sanpaolo Invest";
            //    relativePath = UtilityManager.getAppSetting("TemplateReportSP");
            //}

            //System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);



            System.IO.Stream file = _templateProvider.TemplateReport;
            //}
            //else
            //{
            //    if (_rete == "F")
            //    {
            //        _banca = "Banca Fideuram";
            //        relativePath = UtilityManager.getAppSetting("TemplateReport");
            //    }
            //    else
            //    {
            //        _banca = "Sanpaolo Invest";
            //        relativePath = UtilityManager.getAppSetting("TemplateReportSP");
            //    }
            //}

            PdfDocument pp = new PdfDocument(file);
            _page = new ImportedPage(pp.GetPage(1));
            if (!(_page == null)) _core.Add(_page);
        }
        //==============================================================

        //==============================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="heightSection"></param>
        /// <returns></returns>
        public Boolean checkMargin(float heightSection)
        {
            //controlla se la sezione può essere scritta nella pagina corrente
            return ((_writableY + heightSection) >= (_pageHeight - _margineDOWN));
        }

        /// <summary>
        /// Verifica se a partire dalla posizione y passata in input, l'altezza heightSection entra
        /// nella pagina corrente.
        /// </summary>
        /// <param name="y"></param>
        /// <param name="heightSection"></param>
        /// <returns></returns>
        public Boolean checkMargin(float y, float heightSection)
        {
            //controlla se la sezione pu� essere scritta nella pagina corrente
            return ((y + heightSection) >= (_pageHeight - _margineDOWN));
        }
        public int getWritableRow(float heightRow, bool header)
        {
            float heightSection = 0;
            if (header) heightSection += heightRow;
            int cont = 0;

            while ((_writableY + cont * heightRow + heightSection) < (_pageHeight - _margineDOWN))
            {
                cont++;
            }
            //controlla se la sezione pu� essere scritta nella pagina corrente
            return cont - 1;
        }


        public int NumLastPage
        {
            get
            {
                return _numlastpage;
            }
            set
            {
                _numlastpage = value;
            }
        }
        /// <summary>
        /// Indica se la nota a pi� di pagina � presente.
        /// </summary>
        public bool FlagNotaPieDiPagina
        {
            get
            {
                return _flagnotaPieDiPagina;
            }
            set
            {
                _flagnotaPieDiPagina = value;
            }
        }



        public int CurrentPage
        {
            get
            {
                return _currentPage;
            }
            set
            {
                _currentPage = value;
            }
        }

        public string AsteriscoVarProxati
        {
            get
            {
                return _AsteriscoVarProxato;
            }
            set
            {
                _AsteriscoVarProxato = value;
            }
        }

        public string AsteriscoGradoCopertura
        {
            get
            {
                return _AsteriscoGradoCopertura;
            }
            set
            {
                _AsteriscoGradoCopertura = value;
            }
        }


        public int NumNotePiePaginaVarProxato
        {
            get
            {
                return _numNotePiePaginaVarProxato;
            }
            set
            {
                _numNotePiePaginaVarProxato = value;
            }
        }

        /// <summary>
        /// Imposta o ottiene la lista di note presenti nel documento.
        /// </summary>
        public ListaNote Note
        {
            get { return _note; }
            set { _note = value; }
        }


        public string TipologiaDocumento
        {
            get
            {
                return _tipologia;
            }
            set
            {
                _tipologia = value;
            }
        }

        public string Banca
        {
            get
            {
                return _banca;
            }
            set
            {
                _banca = value;
            }
        }

        public int NumPage
        {
            get
            {
                return _documentoFinale.Pages.Count;
            }
        }
        //public bool Navigatore
        //{
        //    get
        //    {
        //        return _navigatore;
        //    }
        //    set
        //    {
        //        _navigatore = value;
        //    }
        //}

        //public string TipoReport
        //{
        //    get
        //    {
        //        return _tipoReport;
        //    }
        //    set
        //    {
        //        _tipoReport = value;
        //    }
        //}

        public bool Glossario
        {
            get
            {
                return _glossario;
            }
            set
            {
                _glossario = value;
            }
        }

        //public int Modalit�Anonima
        //{
        //    get
        //    {
        //        return _modalitaAnonima;
        //    }
        //    set
        //    {
        //        _modalitaAnonima = value;
        //    }
        //}

        public string NotaPieDiPagina
        {
            get
            {
                return _notaPieDiPagina;
            }
            set
            {
                _notaPieDiPagina = value;
            }
        }
    }

    

    public enum TipoNota
    {
        VarProxato,
        GradoCopertura
    }


    /// <summary>
    /// Rappresentazione dell'oggetto nota.
    /// </summary>
    public class Nota
    {
        /// <summary>
        /// Lista della tipologia delle possibili note da aggiungere al documento.
        /// </summary>
        public enum TipologiaNota
        {
            NonImpostato,
            GradoCopertura,
            VarProxato,
            RendimentoSottoscrizione_Maggiore_1_Anno,
            RendimentoSottoscrizione_Minore_1_Anno,
            RendimentoSottoscrizione_Maggiore_E_Minore_1Anno
        }

        /// <summary>
        /// Lista delle tipologie di posizionamento dell'oggetto nota.
        /// </summary>
        public enum TipologiaPosizionamento
        {
            NonImpostato,
            PieDiPagina,
            PieDiSezione
        }

        /// <summary>
        /// Lista del tipo di stato della Nota. Indica se la Nota � da stampare o se � stata stampata.
        /// </summary>
        public enum StatoNota
        {
            DaStampare,
            Stampata

        }


        private TipologiaNota _tiponota;
        private TipologiaPosizionamento _posizionamento;
        private StatoNota _stato;

        private string _testo = string.Empty;
        private int _numeroasterisco = 0;
        private string _idtabellaassociata;





        /// <summary>
        /// Testo
        /// </summary>
        public string Testo
        {
            get { return _testo; }
            set { _testo = value; }
        }

        /// <summary>
        /// Imposta o ottiente il posizionamento dell'oggetto Nota
        /// </summary>
        public TipologiaPosizionamento Posizionamento
        {
            get { return _posizionamento; }
            set { _posizionamento = value; }
        }


        /// <summary>        
        /// Imposta o ottiente il numero di asterischi.
        /// Ogni Asterisco che viene aggiunto alla collezione di Nota attraverso il metodo Add, viene incrementato automaticamente di 1
        /// </summary>
        public int NumeroAsterisco
        {
            get { return _numeroasterisco; }
            set { _numeroasterisco = value; }
        }


        /// <summary>
        /// Imposta o ottiene la tipologia della Nota
        /// </summary>
        public TipologiaNota TipoNota
        {
            get { return _tiponota; }
            set { _tiponota = value; }
        }

        /// <summary>
        /// Id della tabella associata alla nota.
        /// </summary>
        public string IdTabellaAssociata
        {
            get { return _idtabellaassociata; }
            set { _idtabellaassociata = value; }
        }

        /// <summary>
        /// Stato della Nota.
        /// </summary>
        public StatoNota Stato
        {
            get { return _stato; }
            set { _stato = value; }
        }


        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="tiponota"></param>    
        /// <param name="idtabellaassociata"></param>
        public Nota(TipologiaNota tiponota, string idtabellaassociata)
        {
            _tiponota = tiponota;
            _idtabellaassociata = idtabellaassociata;
            _stato = StatoNota.DaStampare;
        }



        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="tiponota"></param>
        /// <param name="idtabellaassociata"></param>
        /// <param name="testo"></param>
        public Nota(TipologiaNota tiponota, string idtabellaassociata, string testo)
            : this(tiponota, idtabellaassociata)
        {
            _testo = testo;

        }


        /// <summary>
        /// Ritorna la rappresentazione in stringa del numero di asterisci impostato nella propriet� NumeroAsterisco.
        /// </summary>
        public new string ToString()
        {
            string strReturn = string.Empty;

            for (int i = 0; i < _numeroasterisco; i++)
                strReturn += "*";

            return strReturn;

        }

    }

    /// <summary>
    /// Collezione dell'oggetto Nota.
    /// </summary>
    public class ListaNote : List<Nota>
    {
        /// <summary>
        /// Aggiunge un oggetto Nota alla collezione Note e incrementa la propriet� NumeroAsterisco dell'oggetto Nota.
        /// </summary>
        /// <param name="item"></param>
        public new void Add(Nota item)
        {
            Nota objFound = base.Find(delegate (Nota t) { return t.TipoNota == item.TipoNota; });

            if (objFound == null)
            {
                item.NumeroAsterisco = recuperaNumeroAsterisco();
                item.Testo = "(" + item.ToString() + ") " + item.Testo;

                if (item.TipoNota == Nota.TipologiaNota.GradoCopertura)
                    item.Posizionamento = Nota.TipologiaPosizionamento.PieDiSezione;
                else
                    item.Posizionamento = Nota.TipologiaPosizionamento.PieDiPagina;
            }
            else
            {
                item.NumeroAsterisco = objFound.NumeroAsterisco;
                item.Testo = objFound.Testo;
                item.Posizionamento = objFound.Posizionamento;

            }

            base.Add(item);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        public void Insert(Nota item)
        {
            base.Add(item);
        }


        /// <summary>
        /// Recupera il numero di asterischi pi� basso disponibile tra quelli gia inseriti nella lista di note.
        /// </summary>
        /// <returns></returns>
        private int recuperaNumeroAsterisco()
        {
            int result = 1;

            foreach (Nota nota in this)
            {
                if (this.Exists(delegate (Nota t) { return t.NumeroAsterisco == result; }))
                    result++;
            }

            return result;

        }


        /// <summary>
        /// Ricerca all'interno della collezione di Note, l'oggetto avente la TipologiaAsterisco passata in input.
        /// </summary>
        /// <param name="tipoAsterico"></param>
        public Nota Find(Nota.TipologiaNota tipoNota)
        {
            if (base.Count > 0)
                return base.Find(delegate (Nota t) { return t.TipoNota == tipoNota; });
            else
                return new Nota(Nota.TipologiaNota.NonImpostato, null);
        }


        /// <summary>
        /// Ricerca all'interno della collezione di Note, 
        /// l'oggetto avente la TipologiaNota passata in input, e l'id del
        /// </summary>
        /// <param name="tipoAsterico">tipo di nota da ricercare</param>
        /// <param name="IdTabellaAssociata">id della tabellaassociata alla nota da ricercare</param>
        /// <returns></returns>
        public Nota Find(Nota.TipologiaNota tipoNota, string IdTabellaAssociata)
        {
            if (base.Count > 0)
            {
                Nota nota = base.Find(delegate (Nota t) { return t.TipoNota == tipoNota && t.IdTabellaAssociata == IdTabellaAssociata; });
                if (nota != null)
                    return nota;
                else
                    return new Nota(Nota.TipologiaNota.NonImpostato, null);
            }
            else
                return new Nota(Nota.TipologiaNota.NonImpostato, null);
        }


    }

}