using System;
using System.Data;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using CookComputing.XmlRpc;
using System.Net;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using PrometeiaMessage.bancafideuram.nac.posizionecliente;

public interface IPrometeia : IXmlRpcProxy
{
    [XmlRpcMethod("XMLRPCManager.analizzaRichiesta")]
    string AnalizzaRichiesta(string messaggio);
}

/// <summary>
/// Classe wrapper per memorizzare i codici delle varie asset
/// </summary>
internal class AssetClass
{
    public string Descrizione;
    public string ISIN;
    public string MAF;
    public string Adeguatezza;
    public string MacroAsset;
}

public class Prometeia
{
    private static string codiceAgente;
    private static string codiceRete;
    private static string codiceFiscale;
    private static string codiceApplicazione;
    private static int versioneDBSimpb;
    private static int chiaveclientepb;
    private static int? chiavenucleo;
    private static Dictionary<string, List<AssetClass>> DettaglioAsset;

    /// <summary>
    /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
    /// </summary>
    /// <param name="characters">Unicode Byte Array to be converted to String</param>
    /// <returns>String converted from Unicode Byte Array</returns>
    private static String UTF8ByteArrayToString(Byte[] characters)
    {

        //UTF8Encoding encoding = new UTF8Encoding();
        Encoding encoding = Encoding.GetEncoding(1252); //Encoding.GetEncoding(28591);
        String constructedString = encoding.GetString(characters);
        return (constructedString);

    }

    /// <summary>
    /// Converts the String to UTF8 Byte array and is used in De serialization
    /// </summary>
    /// <param name="pXmlString"></param>
    /// <returns></returns>
    private static Byte[] StringToUTF8ByteArray(String pXmlString)
    {

        Encoding encoding = Encoding.GetEncoding(1252);
        Byte[] byteArray = encoding.GetBytes(pXmlString);
        return byteArray;

    }

    private static messaggioType DeserializeMessage(String msgString)
    {

        XmlSerializer xs = new XmlSerializer(typeof(messaggioType));
        MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(msgString));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.GetEncoding(1252));
        return (messaggioType)xs.Deserialize(memoryStream);

    }

    /// <summary>
    /// Method to convert a custom Object to XML string
    /// </summary>
    /// <param name="pObject">Object that is to be serialized to XML</param>
    /// <returns>XML string</returns>
    public static String SerializeMessage(messaggioType pObject)
    {
        String XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(messaggioType));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.GetEncoding(1252));

        xs.Serialize(xmlTextWriter, pObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }

    public static messaggioType CreaRichiesta(params object[] list)
    {
        messaggioType retMessageObj = null;

        try
        {
            messaggioType mt = new messaggioType();
            DataTable dtOutput = new DataTable();
            DettaglioAsset = Prometeia.initializeTabellaAsset();

            switch (list[0].ToString())
            {
                case "RICHIESTAVARPORTAFOGLIO":
                    if (list[1].ToString() == "S21")
                        mt = CreaRichiestaVaRPortafoglioSezione21((DataTable)list[2], (DataTable)list[3]);

                    else if (list[1].ToString() == "S23")
                        if (list.Length < 5)
                            mt = CreaRichiestaVaRPortafoglioSezione23((DataTable)list[2], (DataTable)list[3]);
                        else
                            mt = CreaRichiestaVaRPortafoglioSezione23((DataTable)list[2], (DataTable)list[5]);

                    else if (list[1].ToString() == "S56")
                        if (list.Length < 5)
                            mt = CreaRichiestaVaRPortafoglioSezione56((DataTable)list[2], (DataTable)list[3]);
                        else
                            mt = CreaRichiestaVaRPortafoglioSezione56_BisCC((DataTable)list[2], (DataTable)list[3], (DataTable)list[4]);

                    else if (list[1].ToString() == "TESTPROMETEIA")
                        mt = CreaRichiestaVaRPortafoglio((DataTable)list[2]);

                    else if (list[1].ToString() == "PATRIMONIOCOMPLESSIVO")
                        mt = CreaRichiestaPatrimonioComplessivo((DataTable)list[2], (DataTable)list[3], (DataTable)list[4], (DataTable)list[5]);

                    else if (list[1].ToString() == "S19" || list[1].ToString() == "S19BIS")
                        mt = CreaRichiestaVaRPortafoglioSezione19((DataTable)list[2]);

                    else if (list[1].ToString() == "S48PERTIPOPRODOTTO")
                        mt = CreaRichiestaVaRPortafoglioSezioneS48PerTipoProdotto((DataTable)list[2]);

                    else if (list[1].ToString() == "S48PERINTERMEDIARIO")
                        mt = CreaRichiestaVaRPortafoglioSezioneS48PerIntermediario((DataTable)list[2]);

                    else if (list[1].ToString() == "S63")
                        // La sezione 63 chiama comunque la sezione 21
                        mt = CreaRichiestaVaRPortafoglioSezione21((DataTable)list[2], (DataTable)list[3]);

                    else if (list[1].ToString() == "S44")
                        // LIST[2]: DTPROMETEIA, LIST[3]: CONTRATTO SINTESI
                        mt = CreaRichiestaVaRPortafoglioSezioneS44((DataTable)list[2], (DataTable)list[3]);

                    else if (list[1].ToString() == "S46")
                        // LIST[2]: DTPROMETEIA, LIST[3]: CONTRATTO SINTESI
                        mt = CreaRichiestaVaRPortafoglioSezioneS46((DataTable)list[2], (DataTable)list[3]);

                    else if (list[1].ToString() == "S50")
                        // LIST[2]: DTPROMETEIA, LIST[3]: CONTRATTO SINTESI
                        mt = CreaRichiestaVaRPortafoglioSezioneS50((DataTable)list[2]);

                    else if (list[1].ToString() == "S70")
                        // LIST[2]: DTPROMETEIA, LIST[3]: CONTRATTO SINTESI
                        mt = CreaRichiestaVaRPortafoglioSezione70((DataTable)list[2], (DataTable)list[3]);

                    else if (list[1].ToString() == "S73")
                        // LIST[2]: DTPROMETEIA, LIST[3]: CONTRATTO SINTESI
                        mt = CreaRichiestaVaRPortafoglioSezione73((DataTable)list[2], (DataTable)list[3]);

                    else if (list[1].ToString() == "S102")
                        mt = CreaRichiestaVaRPortafoglioSezioneS102((DataTable)list[2]);

                    else if (list[1].ToString() == "S120")
                        mt = CreaRichiestaVaRPortafoglioSezioneS120((DataTable)list[2]);

                    break;

                case "RICHIESTAPORTAFOGLIOMODELLO":
                    mt = CreaRichiestaPortafoglioModello((DataTable)list[1], (DataTable)list[2], (DataRow)list[3]);
                    break;

                case "RICHIESTAVARMERCATI":
                    mt = CreaRichiestaVaRMercatiFinanziari();
                    break;

                case "RICHIESTAVARMACROASSET":
                    mt = CreaRichiestaVaRMacroAsset();
                    break;

                case "RICHIESTAVARPORTAFOGLIOASSET":
                    mt = CreaRichiestaVaRPortafoglioAsset((DataTable)list[1], (DataTable)list[2]);
                    break;

                default:
                    break;
            }

            #region Chiamata Prometeia
            string ms = SerializeMessage(mt);

            IPrometeia proxy = XmlRpcProxyGen.Create<IPrometeia>();
            proxy.Url = ConfigurationManager.AppSettings["XMLRPCURL"].ToString();

            //da laboratorio:
            string _proxy;
            if (ConfigurationManager.AppSettings["PROXYXMLRPC"] != null)
                _proxy = ConfigurationManager.AppSettings["PROXYXMLRPC"].ToString();
            else
                _proxy = "";

            if (_proxy.Trim() != "")
            {
                //proxy.Proxy = new WebProxy(_proxy); //non disponibile per problemi sistemistici

                // Questa impostazione � utilizzata solo internamente ad HP.
                // E' un rimedio al fatto che http://paa.prometeia.it non � pi� raggiungibile per problemi sistemistici.
                // Non essendo piu disponibile utilizzo http://134.44.28.136:9882 aggiungendo delle eccezioni ai settaggi del proxy da utilizzare.
                // Se dovesse di nuovo essere disponibile � suff scommetare "//non disponibile per problemi sistemistici" ed eliminare il codice sottostante
                List<string> bypasslist = new List<string>();
                bypasslist.Add(@"localhost");
                bypasslist.Add(@"127.0.0.1");
                bypasslist.Add(@"134.44.28.136");

                WebProxy proxyLocale = new WebProxy(_proxy);
                proxyLocale.BypassList = bypasslist.ToArray();
                proxy.Proxy = proxyLocale;

            }

            //Encoding iso = Encoding.GetEncoding(28591);
            Encoding iso = Encoding.GetEncoding(1252);
            proxy.XmlEncoding = iso;

            string retMessage = proxy.AnalizzaRichiesta(ms.TrimStart().TrimEnd());

            retMessageObj = DeserializeMessage(retMessage);


            SetVarpConCoperturaZero(retMessageObj);
            #endregion
        }
        catch (Exception except)
        {
            throw new Exception(except.Message + ". Source: " + except.Source, except.InnerException);
        }

        return retMessageObj;
    }

    private static messaggioType CreaRichiestaVaRPortafoglio(DataTable dtRichiesta)
    {
        #region Variabili costruzione oggetto MessageType
        DataTable dtDistinctNeedArea;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptf;
        saldoType saldo;
        ProdottiKeyType pkt;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumn = new string[1];
            paramColumn[0] = ConfigurationManager.AppSettings["DISTINCTCOLUMN"].ToString();
            dtDistinctNeedArea = dtRichiesta.DefaultView.ToTable(true, paramColumn);
            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwdistinctNeedArea = "";
            string rwNeedArea = "";
            string rwAsulString = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rwdistinct in dtDistinctNeedArea.Rows)
            {
                ptf = new ptfType();
                ptf.descrizione = rwdistinct["NEEDAREA"].ToString();

                foreach (DataRow rw in dtRichiesta.Rows)
                {
                    rwdistinctNeedArea = rwdistinct["NEEDAREA"].ToString().Trim().ToUpper();
                    rwNeedArea = rw["NEEDAREA"].ToString().Trim().ToUpper();
                    rwAsulString = rw["TIPOPRODOTTO"].ToString().Trim().ToUpper();

                    if (rwdistinctNeedArea.Equals(rwNeedArea))
                    {
                        if (tipoProdottoAsul.Equals(rwAsulString))//K Skandia
                        {
                            #region SALDO ASUL

                            #region Chiamata la WSGLOBALPOSITION
                            PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                            _chiaveCliente.codiceAgente = codiceAgente;
                            _chiaveCliente.codicefiscale = codiceFiscale;
                            _chiaveCliente.codiceRete = codiceRete;
                            _chiaveCliente.potenzialeClienteNAC = true;

                            PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                            _infoCliente.codiceApplicazione = codiceApplicazione;
                            _infoCliente.codiceRete = codiceRete;
                            _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;
                            string codiceContratto = rw["CONTRATTO"].ToString().Trim();

                            GlobalPositionWS gpWS = new GlobalPositionWS();

                            DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);
                            #endregion

                            foreach (DataRow rwAsul in dtAsul.Rows)
                            {
                                saldo = new saldoType();
                                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());

                                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                    saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());

                                saldo.valoreCtvSpecified = true;

                                pkt = new ProdottiKeyType();

                                //CODICEADEGUATEZZA
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                                //if (rw["CODICEISIN"] != DBNull.Value)
                                //    pkt.codiceIsin = rw["CODICEISIN"].ToString();

                                //if (rw["CODICEMAF"] != DBNull.Value)
                                //    pkt.codiceMaf = rw["CODICEMAF"].ToString();


                                saldo.chiave = pkt;
                                ptf.AddSaldo(saldo);
                            }
                            #endregion
                        }
                        else
                        {
                            #region SALDO NON ASUL
                            saldo = new saldoType();
                            if (rw["VALORE"] != DBNull.Value)
                                saldo.valore = Convert.ToDouble(rw["VALORE"].ToString());

                            if (rw["CONTROVALORE"] != DBNull.Value)
                                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());

                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();

                            //K Skandia
                            if (rwAsulString.Equals(tipoProdottoAsu2))
                            {
                                //CODICEADEGUATEZZA
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";
                            }
                            else
                            {
                                if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (rw["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";

                                if (rw["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (rw["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";
                            }
                            saldo.chiave = pkt;
                            ptf.AddSaldo(saldo);
                            #endregion
                        }
                    }
                }
                ptf.AddChildSaldoToAggregate();
                richiestaVarPortafoglio.Add(ptf);
            }
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglio", ex.InnerException);
        }
        return mt;

    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione56(DataTable dtRichiesta, DataTable dtContrattiSintesiPerCliente)
    {
        #region Variabili costruzione oggetto MessageType
        DataTable dtDistinctNeedArea;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptf;
        saldoType saldo;
        ProdottiKeyType pkt;
        Aggregato aggregato;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumn = new string[1];
            paramColumn[0] = ConfigurationManager.AppSettings["DISTINCTCOLUMN"].ToString();
            dtDistinctNeedArea = dtRichiesta.DefaultView.ToTable(true, paramColumn);
            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwdistinctNeedArea = "";
            string rwNeedArea = "";
            string rwAsulString = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEPATRIMONIOBF";

            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesiPerCliente);

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rwdistinct in dtDistinctNeedArea.Rows)
            {
                // Creo un aggregato
                aggregato = new Aggregato();
                ptf = new ptfType();
                ptf.descrizione = rwdistinct["NEEDAREA"].ToString();

                foreach (DataRow rw in dtRichiesta.Rows)
                {
                    rwdistinctNeedArea = rwdistinct["NEEDAREA"].ToString().Trim().ToUpper();
                    rwNeedArea = rw["NEEDAREA"].ToString().Trim().ToUpper();

                    #region Recupero il valore del contratto dai dati restituiti dal ws GlobalPosition metodo GetContrattoSintesiPerCliente
                    //DataRow[] rwContrattoSintesiPerCliente = FindContrattoSintesiPerCliente(rw, dtContrattiSintesiPerCliente);
                    // Definisce i prodotti ASUL
                    //if (rwContrattoSintesiPerCliente.Length > 0)
                    //    rwAsulString = rwContrattoSintesiPerCliente[0]["TIPOPRODOTTO"].ToString().Trim().ToUpper();
                    //else
                    //    rwAsulString = rw["TIPOPRODOTTO"].ToString();
                    if (rw["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)rw["TIPOPRODOTTOSINTESI"] == "")
                        rwAsulString = rw["TIPOPRODOTTO"].ToString();
                    else
                        rwAsulString = rw["TIPOPRODOTTOSINTESI"].ToString();
                    #endregion

                    if (rwdistinctNeedArea.Equals(rwNeedArea))
                    {
                        if (tipoProdottoAsul.Equals(rwAsulString)) //K Skandia
                        {
                            #region SALDO ASUL

                            #region Chiamata la WSGLOBALPOSITION
                            PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                            _chiaveCliente.codiceAgente = codiceAgente;
                            _chiaveCliente.codicefiscale = codiceFiscale;
                            _chiaveCliente.codiceRete = codiceRete;
                            _chiaveCliente.potenzialeClienteNAC = true;

                            PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                            _infoCliente.codiceApplicazione = codiceApplicazione;
                            _infoCliente.codiceRete = codiceRete;
                            _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;
                            string codiceContratto = rw["CONTRATTO"].ToString().Trim();

                            GlobalPositionWS gpWS = new GlobalPositionWS();

                            DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);
                            #endregion

                            foreach (DataRow rwAsul in dtAsul.Rows)
                            {
                                saldo = new saldoType();
                                // One week

                                //if (rwContrattoSintesiPerCliente[0]["VALORE"] != DBNull.Value)
                                //if (rw["VALORESINTESI"] == DBNull.Value || (double)rw["VALORESINTESI"] == 0)
                                //    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                //else
                                //    saldo.valore = Convert.ToDouble(rw["VALORESINTESI"].ToString());


                                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                {
                                    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                    saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                }

                                saldo.valoreCtvSpecified = true;

                                pkt = new ProdottiKeyType();

                                //CODICEADEGUATEZZA
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                                //if (rw["CODICEISIN"] != DBNull.Value)
                                //    pkt.codiceIsin = rw["CODICEISIN"].ToString();

                                //if (rw["CODICEMAF"] != DBNull.Value)
                                //    pkt.codiceMaf = rw["CODICEMAF"].ToString();


                                saldo.chiave = pkt;
                                ptf.AddSaldo(saldo);
                            }
                            #endregion
                        }
                        else
                        {
                            #region SALDO NON ASUL
                            saldo = new saldoType();
                            // One week

                            if (rw["VALORESINTESI"] == DBNull.Value || (double)rw["VALORESINTESI"] == 0)
                                saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                            else
                                saldo.valore = Convert.ToDouble(rw["VALORESINTESI"].ToString());


                            if (rw["CONTROVALORE"] != DBNull.Value)
                                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());

                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();
                            //K Skandia
                            if (rwAsulString.Equals(tipoProdottoAsu2))
                            {
                                //CODICEADEGUATEZZA
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                            }
                            else
                            {
                                if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (rw["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";

                                if (rw["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (rw["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";
                            }
                            saldo.chiave = pkt;
                            ptf.AddSaldo(saldo);
                            #endregion
                        }
                    }
                }
                ptf.AddChildSaldoToAggregate();
                aggregato.Add(ptf);
                aggregato.AddCollectionAggregateToAggregate();
                ptf.AddChildToAggregate();
                ptfTotale.AddAggregato(ptf);
                ptfTotale.AddChildToAggregate();
            }
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaVaRPortafoglioSezione56", ex.InnerException);
        }
        return mt;

    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione56_BisCC(DataTable dtRichiesta, DataTable dtContrattiSintesi, DataTable dtCC)
    {
        #region Variabili costruzione oggetto MessageType
        DataTable dtDistinctNeedArea;

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;

        ptfType ptf = new ptfType();
        saldoType saldo = new saldoType();
        ProdottiKeyType pkt = new ProdottiKeyType();
        Aggregato aggregato = new Aggregato();

        ptfType ptfTotaleBF = new ptfType();        // Totale BF = Totale Risorse Finanziarie + ContoCorrente al Netto Franchigia
        ptfType ptfTotaleRisorseFinanziarie = new ptfType();          // Totale Risorse Finanziarie
        ptfType ptfContoCorrenteBF = new ptfType();  // ContoCorrente presso BF al Netto Franchigia

        saldoType saldoCC = new saldoType();        // Saldo CC al Netto Franchigia
        ProdottiKeyType pktCC = new ProdottiKeyType();
        #endregion


        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType

            ptfTotaleBF.descrizione = "TOTALEPATRIMONIOBF";
            ptfTotaleRisorseFinanziarie.descrizione = "TOTALERISORSEFINANZARIE";
            ptfContoCorrenteBF.descrizione = "CONTOCORRENTEBF";

            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;



            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwdistinctNeedArea = "";
            string rwNeedArea = "";
            string rwAsulString = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;

            //string expression;
            //expression = "flagCasa = 1";

            //DataRow[] foundRows;
            //foundRows = dtCC.Select(expression);

            //if (foundRows.Length > 0)
            //{
            //    #region SALDO CC
            //    saldoCC.nome = "CCNettoFranchigia";

            //    pktCC.codiceAdeguatezza = "EUR";
            //    pktCC.codiceInterno = "EUR";
            //    pktCC.codiceIsin = "EUR";
            //    pktCC.codiceMaf = "EUR";
            //    pktCC.codiceSottoprodotto = "EUR";

            //    saldoCC.chiave = pktCC;

            //    if (foundRows[0][2] != DBNull.Value)
            //    {
            //        saldoCC.valore = Convert.ToDouble(foundRows[0][2].ToString());
            //        saldoCC.valoreCtv = Convert.ToDouble(foundRows[0][2].ToString());
            //        saldoCC.valoreCtvSpecified = true;

            //    }

            //    ptfContoCorrenteBF.AddSaldo(saldoCC);
            //    ptfContoCorrenteBF.AddChildSaldoToAggregate();

            //    ptfTotaleBF.AddAggregato(ptfContoCorrenteBF);
            //    #endregion
            //}

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVENUCLEO"))
                chiavenucleo = int.Parse(dtRichiesta.ExtendedProperties["CHIAVENUCLEO"].ToString());


            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesi);

            #region CREAZIONE OGGETTO MESSAGE

            #region Aggiungo il dettaglio dei CC positivi all'area Liquidit�

            if (dtCC.Rows.Count > 0)
            {
                if (dtCC.Select("flagcasa=1").Length > 0)
                {
                    decimal valoreCC = Convert.ToDecimal(dtCC.Select("flagcasa=1")[0][2]);
                    if (dtRichiesta.Select("needarea='Liq' and tipoprodotto='CC'").Length == 0)
                        dtRichiesta.Rows.Add("Liq", "CC", "", "EUR", "EUR", "EUR", "EUR", valoreCC, valoreCC, "EUR");
                }
            }

            #endregion

            #region Elimino linea self positiva (quella negativa � esclusa a livello stored)

            DataRow[] drSelfPositiva = dtRichiesta.Select(" CODICEISIN  IN ('EURO00000009','EURO10000007')"); // Cod Isin che identifica la linea self positiva

            foreach (DataRow row in drSelfPositiva)
            {
                dtRichiesta.Rows.Remove(row);
            }

            #endregion

            // DataView ordinato per NEEDAREA 
            string[] paramColumn = new string[1];
            paramColumn[0] = ConfigurationManager.AppSettings["DISTINCTCOLUMN"].ToString();
            dtDistinctNeedArea = dtRichiesta.DefaultView.ToTable(true, paramColumn);

            foreach (DataRow rwdistinct in dtDistinctNeedArea.Rows)
            {
                // Creo un aggregato
                aggregato = new Aggregato();
                ptf = new ptfType();
                ptf.descrizione = rwdistinct["NEEDAREA"].ToString();

                foreach (DataRow rw in dtRichiesta.Rows)
                {
                    rwdistinctNeedArea = rwdistinct["NEEDAREA"].ToString().Trim().ToUpper();
                    rwNeedArea = rw["NEEDAREA"].ToString().Trim().ToUpper();

                    #region Recupero il valore del contratto dai dati restituiti dal ws GlobalPosition metodo GetContrattoSintesiPerCliente
                    //DataRow[] rwContrattoSintesiPerCliente = FindContrattoSintesiPerCliente(rw, dtContrattiSintesiPerCliente);
                    // Definisce i prodotti ASUL
                    //if (rwContrattoSintesiPerCliente.Length > 0)
                    //    rwAsulString = rwContrattoSintesiPerCliente[0]["TIPOPRODOTTO"].ToString().Trim().ToUpper();
                    //else
                    //    rwAsulString = rw["TIPOPRODOTTO"].ToString();
                    if (rw["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)rw["TIPOPRODOTTOSINTESI"] == "")
                        rwAsulString = rw["TIPOPRODOTTO"].ToString();
                    else
                        rwAsulString = rw["TIPOPRODOTTOSINTESI"].ToString();
                    #endregion
                    //K Skandia
                    if (rwdistinctNeedArea.Equals(rwNeedArea))
                    {
                        if (tipoProdottoAsul.Equals(rwAsulString))
                        {
                            string codiceContratto = rw["CONTRATTO"].ToString().Trim();
                            int? chiaveclientepbNucleo = chiavenucleo.HasValue ? Convert.ToInt32(rw["CHIAVECLIENTEPB"]) : (int?)null;

                            #region SALDO ASUL

                            #region Chiamata la WSGLOBALPOSITION

                            PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                            _chiaveCliente.codiceAgente = codiceAgente;
                            _chiaveCliente.codicefiscale = codiceFiscale;
                            _chiaveCliente.codiceRete = codiceRete;
                            _chiaveCliente.potenzialeClienteNAC = true;

                            PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                            _infoCliente.codiceApplicazione = codiceApplicazione;
                            _infoCliente.codiceRete = codiceRete;
                            _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;


                            GlobalPositionWS gpWS = new GlobalPositionWS();
                            DataTable dtAsul;

                            // Se � valorizzato chiavenucleo richiedo la GetContrattoUnitLinkedSaldo per la chiaveclientepb cui il contratto � associato
                            if (chiavenucleo.HasValue)
                                dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepbNucleo.Value);
                            else
                                dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);

                            #endregion

                            foreach (DataRow rwAsul in dtAsul.Rows)
                            {
                                saldo = new saldoType();

                                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                {
                                    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                    saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                }

                                saldo.valoreCtvSpecified = true;

                                pkt = new ProdottiKeyType();

                                //CODICEADEGUATEZZA
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                                //if (rw["CODICEISIN"] != DBNull.Value)
                                //    pkt.codiceIsin = rw["CODICEISIN"].ToString();

                                //if (rw["CODICEMAF"] != DBNull.Value)
                                //    pkt.codiceMaf = rw["CODICEMAF"].ToString();


                                saldo.chiave = pkt;
                                ptf.AddSaldo(saldo);
                            }
                            #endregion
                        }
                        else
                        {
                            #region SALDO NON ASUL
                            saldo = new saldoType();
                            // One week

                            if (rw["VALORESINTESI"] == DBNull.Value || (double)rw["VALORESINTESI"] == 0)
                                saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                            else
                                saldo.valore = Convert.ToDouble(rw["VALORESINTESI"].ToString());


                            if (rw["CONTROVALORE"] != DBNull.Value)
                                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());

                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();

                            //K Skandia
                            if (rwAsulString.Equals(tipoProdottoAsu2))
                            {
                                //CODICEADEGUATEZZA
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";
                            }
                            else
                            {
                                if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (rw["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";

                                if (rw["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (rw["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";
                            }
                            saldo.chiave = pkt;
                            ptf.AddSaldo(saldo);
                            #endregion
                        }
                    }
                }
                ptf.AddChildSaldoToAggregate();

                aggregato.Add(ptf);
                aggregato.AddCollectionAggregateToAggregate();
                ptf.AddChildToAggregate();

                ptfTotaleRisorseFinanziarie.AddAggregato(ptf);
                ptfTotaleRisorseFinanziarie.AddChildToAggregate();

            }

            ptfTotaleBF.AddChildSaldoToAggregate();
            ptfTotaleBF.AddAggregato(ptfTotaleRisorseFinanziarie);


            ptfTotaleBF.AddChildToAggregate();

            richiestaVarPortafoglio.Add(ptfTotaleBF);
            richiestaVarPortafoglio.AddChildToAggregate();


            #endregion

            #endregion

            #endregion

            #endregion

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaVaRPortafoglioSezione56_BisCC", ex.InnerException);
        }


        return mt;


    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione21(DataTable dtRichiesta, DataTable dtContrattiSintesiPerCliente)
    {
        #region Variabili costruzione oggetto MessageType
        DataTable dtDistinctNeedArea;
        DataTable dtDistinctNomeProgetto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptf = null;
        ptfType ptfNonAsul = null;
        ptfType ptfAsul = null;
        saldoType saldo;
        ProdottiKeyType pkt;
        Aggregato aggregatoAsul = null;
        Aggregato aggregato;
        Aggregato aggregatoNonAsul;
        Aggregato aggregatoInv;
        #endregion

        #region Filtro sui CC inferiori alla franchigia
        DataView dtvw = new DataView(dtRichiesta);
        dtvw.RowFilter = " not (Tipoprodotto = 'CC' and controvalore < 10000) ";
        dtRichiesta = dtvw.ToTable();
        #endregion

        #region Elimino linea self positiva (quella negativa � esclusa a livello stored)

        DataRow[] drSelfPositiva = dtRichiesta.Select(" CODICEISIN  IN ('EURO00000009','EURO10000007')"); // Cod Isin che identifica la linea self positiva

        foreach (DataRow row in drSelfPositiva)
        {
            dtRichiesta.Rows.Remove(row);
        }

        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumn = new string[1];
            paramColumn[0] = ConfigurationManager.AppSettings["DISTINCTCOLUMN"].ToString();
            dtDistinctNeedArea = dtRichiesta.DefaultView.ToTable(true, paramColumn);


            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwAsulString = "";
            codiceAgente = "";
            codiceRete = "";
            codiceFiscale = "";
            codiceApplicazione = "";
            versioneDBSimpb = 0;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            String needAreaInv = ConfigurationManager.AppSettings["NEEDAREAINV"].ToString();

            // Eleboro il datatable richiesta
            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesiPerCliente);

            List<DataViewSezione21> ListDataView = MakeDataSetSezione21(dtDistinctNeedArea, dtRichiesta);

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALE";

            ptfType ptfInvestimento;


            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataViewSezione21 dvNeedAree in ListDataView)
            {
                // Creo un aggregatoAsul
                aggregato = new Aggregato();
                ptf = new ptfType();
                ptf.descrizione = dvNeedAree.Descrizione;

                if (dvNeedAree.Descrizione.ToUpper().Trim() == needAreaInv.ToUpper().Trim())
                {
                    // INVESTIMENTO
                    // DataView ordinato per NEEDAREA 
                    string[] paramColumnNomeProgetto = new string[1];
                    paramColumnNomeProgetto[0] = ConfigurationManager.AppSettings["DISTINCTCOLUMNNNOMEPROGETTO"].ToString();
                    dtDistinctNomeProgetto = dvNeedAree.ToTable(true, paramColumnNomeProgetto);

                    foreach (DataRow drNomeProgetto in dtDistinctNomeProgetto.Rows)
                    {
                        ptfInvestimento = new ptfType();
                        aggregatoInv = new Aggregato();

                        if (drNomeProgetto["NOME_PROGETTO"].ToString() != "")
                            ptfInvestimento.descrizione = drNomeProgetto["NOME_PROGETTO"].ToString();
                        else
                            ptfInvestimento.descrizione = "Progetto Investimento";


                        foreach (DataRowView rw in dvNeedAree)
                        {
                            if (ptfInvestimento.descrizione.ToUpper().Trim() == rw["NOME_PROGETTO"].ToString().ToUpper().Trim())
                            {
                                //rwAsulString = rw["TIPOPRODOTTO"].ToString().Trim().ToUpper();

                                if (rw["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)rw["TIPOPRODOTTOSINTESI"] == "")
                                    rwAsulString = rw["TIPOPRODOTTO"].ToString().Trim().ToUpper();
                                else
                                    rwAsulString = rw["TIPOPRODOTTOSINTESI"].ToString().Trim().ToUpper();

                                CreaAggregatoSezione21(ptfInvestimento, rwAsulString, tipoProdottoAsul, rw, chiaveclientepb);

                                aggregatoInv.Add(ptfInvestimento);
                            }
                        }
                        aggregatoInv.AddCollectionAggregateToAggregate();
                        ptfInvestimento.AddChildToAggregate();
                        ptf.AddAggregato(ptfInvestimento);
                        ptf.AddChildToAggregate();
                    }

                }
                else
                {
                    foreach (DataRowView rw in dvNeedAree)
                    {
                        //rwAsulString = rw["TIPOPRODOTTO"].ToString().Trim().ToUpper();

                        if (rw["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)rw["TIPOPRODOTTOSINTESI"] == "")
                            rwAsulString = rw["TIPOPRODOTTO"].ToString().Trim().ToUpper();
                        else
                            rwAsulString = rw["TIPOPRODOTTOSINTESI"].ToString().Trim().ToUpper();

                        CreaAggregatoSezione21(ptf, rwAsulString, tipoProdottoAsul, rw, chiaveclientepb);
                    }
                }

                aggregato.Add(ptf);
                aggregato.AddCollectionAggregateToAggregate();
                ptf.AddChildToAggregate();

                ptfTotale.AddAggregato(ptf);
                ptfTotale.AddChildToAggregate();
            }
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaVaRPortafoglioSezione21", ex.InnerException);
        }

        return mt;

    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione23(DataTable dtRichiesta, DataTable dtCC)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        DataTable dtDistinctIntermediario = new DataTable();
        dtDistinctIntermediario.Columns.Add("Intermediario", typeof(string));

        DataTable dtDistinctContoCorrente = new DataTable();
        dtDistinctContoCorrente.Columns.Add("Intermediario", typeof(string));

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptf;
        saldoType saldo;
        ProdottiKeyType pkt;
        Aggregato aggregato;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA             
            dtDistinctIntermediario = dtRichiesta.DefaultView.ToTable(true, "needArea");
            dtDistinctIntermediario.Columns[0].ColumnName = "Intermediario";

            if (dtCC != null)
            {
                dtDistinctContoCorrente = dtCC.DefaultView.ToTable(true, "IDIntermediario");
                dtDistinctContoCorrente.Columns[0].ColumnName = "Intermediario";
            }

            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwdistinctNeedArea = "";
            string rwNeedArea = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEALTRIISTITUTI";

            #region CREAZIONE OGGETTO MESSAGE

            dtDistinctIntermediario.Merge(dtDistinctContoCorrente);
            dtDistinctIntermediario = dtDistinctIntermediario.DefaultView.ToTable(true, "Intermediario");

            foreach (DataRow rwdistinct in dtDistinctIntermediario.Rows)
            {
                if (rwdistinct["Intermediario"].ToString().Length > 0)
                {
                    // Creo un aggregato
                    aggregato = new Aggregato();
                    ptf = new ptfType();
                    ptf.descrizione = rwdistinct["Intermediario"].ToString();

                    if (dtCC != null)
                        foreach (DataRow rw in dtCC.Rows)
                        {
                            rwdistinctNeedArea = rwdistinct["Intermediario"].ToString().Trim().ToUpper();
                            rwNeedArea = rw[1].ToString().Trim().ToUpper();

                            if ((rwdistinctNeedArea.Equals(rwNeedArea)) & int.Parse(rw[0].ToString()) == 0)
                            {
                                #region SALDO CC
                                saldo = new saldoType();
                                saldo.nome = "CCNettoFranchigia";

                                pkt = new ProdottiKeyType();

                                pkt.codiceAdeguatezza = "EUR";
                                pkt.codiceInterno = "EUR";
                                pkt.codiceIsin = "EUR";
                                pkt.codiceMaf = "EUR";
                                pkt.codiceSottoprodotto = "EUR";

                                saldo.chiave = pkt;

                                if (rw[2] != DBNull.Value)
                                {
                                    saldo.valore = Convert.ToDouble(rw[2].ToString());
                                    saldo.valoreCtv = Convert.ToDouble(rw[2].ToString());
                                    saldo.valoreCtvSpecified = true;
                                }
                                ptf.AddSaldo(saldo);
                                #endregion
                            }

                        }

                    foreach (DataRow rw in dtRichiesta.Rows)
                    {
                        rwdistinctNeedArea = rwdistinct["Intermediario"].ToString().Trim().ToUpper();
                        rwNeedArea = rw["NeedArea"].ToString().Trim().ToUpper();

                        if (rwdistinctNeedArea.Equals(rwNeedArea))
                        {
                            #region SALDO NON ASUL
                            saldo = new saldoType();
                            if (rw["VALORE"] != DBNull.Value)
                                saldo.valore = Convert.ToDouble(rw["VALORE"].ToString());

                            if (rw["CONTROVALORE"] != DBNull.Value)
                                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());

                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();

                            if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                            else
                                pkt.codiceAdeguatezza = "";

                            if (rw["CODICEISIN"] != DBNull.Value)
                                pkt.codiceIsin = rw["CODICEISIN"].ToString();
                            else
                                pkt.codiceIsin = "";

                            if (rw["CODICEMAF"] != DBNull.Value)
                                pkt.codiceMaf = rw["CODICEMAF"].ToString();
                            else
                                pkt.codiceMaf = "";

                            // CODICESOTTOPRODOTTO
                            if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                            else
                                pkt.codiceSottoprodotto = "";

                            // CODICEINTERNO
                            if (rw["CODICEINTERNO"] != DBNull.Value)
                                pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                            else
                                pkt.codiceInterno = "";

                            saldo.chiave = pkt;
                            ptf.AddSaldo(saldo);
                            #endregion
                        }


                    }
                    ptf.AddChildSaldoToAggregate();
                    aggregato.Add(ptf);
                    aggregato.AddCollectionAggregateToAggregate();
                    ptf.AddChildToAggregate();
                    ptfTotale.AddAggregato(ptf);
                    ptfTotale.AddChildToAggregate();
                    //richiestaVarPortafoglio.Add(ptf);

                    richiestaVarPortafoglio.Add(ptfTotale);
                    richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezione23", ex.InnerException);
        }
        return mt;

    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione70(DataTable dtRichiesta, DataTable dtContrattiSintesiPerCliente)
    {
        #region Variabili costruzione oggetto MessageType
        DataTable dtDistinctNeedArea;
        DataTable dtDistinctProgetto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        saldoType saldo;
        ProdottiKeyType pkt;
        double ctvOperazione = 0;

        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;
            double ctvAsul = 0;
            double ctvAsulCalcolato = 0;

            // DataView ordinato per NEEDAREA 
            // Distinct needarea
            string[] paramColumn = new string[1];
            paramColumn[0] = ConfigurationManager.AppSettings["DISTINCTCOLUMN"].ToString();
            dtDistinctNeedArea = dtRichiesta.DefaultView.ToTable(true, paramColumn);

            // Distinct Progetto
            string[] paramColumnprogetto = new string[2];
            paramColumnprogetto[0] = "needarea";
            paramColumnprogetto[1] = "nome_progetto";

            dtDistinctProgetto = dtRichiesta.DefaultView.ToTable(true, paramColumnprogetto);
            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwAsulString = "";
            codiceAgente = "";
            codiceRete = "";
            codiceFiscale = "";
            codiceApplicazione = "";
            versioneDBSimpb = 0;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            String needAreaInv = ConfigurationManager.AppSettings["NEEDAREAINV"].ToString();

            // Eleboro il datatable richiesta
            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesiPerCliente);


            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALE";


            ptfType ptfLivelloNeedArea;
            ptfType ptfLivelloProgetto;
            ptfType ptfLivelloProdotto;

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rwdistinct in dtDistinctNeedArea.Rows)
            {
                // Creo un aggregatoAsul
                // Creo un aggregato
                #region Livello Need Area
                ptfLivelloNeedArea = new ptfType();
                ptfLivelloNeedArea.descrizione = rwdistinct["needarea"].ToString();

                if (rwdistinct["needarea"].ToString().ToUpper() == "INV")
                {
                    // Livello Aggregato Need Area
                    #region Investimento
                    foreach (DataRow rwdistinctprogetto in dtDistinctProgetto.Rows)
                    {
                        #region Livello Progetto
                        if (rwdistinct["needarea"].ToString().ToUpper() == rwdistinctprogetto["needarea"].ToString().ToUpper())
                        {
                            ptfLivelloProgetto = new ptfType();
                            ptfLivelloProgetto.descrizione = rwdistinctprogetto["nome_progetto"].ToString();

                            foreach (DataRow drprodotto in dtRichiesta.Rows)
                            {
                                #region Livello Aggregato Prodotto
                                if (rwdistinct["needarea"].ToString() == drprodotto["needarea"].ToString() &&
                                    rwdistinctprogetto["nome_progetto"].ToString() == drprodotto["nome_progetto"].ToString())
                                {

                                    if (drprodotto["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)drprodotto["TIPOPRODOTTOSINTESI"] == "")
                                        rwAsulString = drprodotto["TIPOPRODOTTO"].ToString();
                                    else
                                        rwAsulString = drprodotto["TIPOPRODOTTOSINTESI"].ToString();

                                    #region Aggregato di Prodotto
                                    ptfLivelloProdotto = new ptfType();
                                    ptfLivelloProdotto.descrizione = drprodotto["ID"].ToString();
                                    #endregion

                                    double controvalore_proposta = Convert.ToDouble(drprodotto["controvalore_proposta"]);
                                    double controvalore_attuale = Convert.ToDouble(drprodotto["controvalore_attuale"]);
                                    double rapporto = Convert.ToDouble(drprodotto["rapporto"]);
                                    double investi_nominale = 0;
                                    double disinvesti_nominale = 0;

                                    double investi = 0;
                                    double disinvesti = 0;

                                    double apporti_o_disinvestimenti = 0;

                                    if (drprodotto["investi_nominale"] != DBNull.Value)
                                        investi_nominale = Convert.ToDouble(drprodotto["investi_nominale"]);

                                    if (drprodotto["disinvesti_nominale"] != DBNull.Value)
                                        disinvesti_nominale = Convert.ToDouble(drprodotto["disinvesti_nominale"]);

                                    if (drprodotto["investi"] != DBNull.Value)
                                        investi = Convert.ToDouble(drprodotto["investi"]);

                                    if (drprodotto["disinvesti"] != DBNull.Value)
                                        disinvesti = Convert.ToDouble(drprodotto["disinvesti"]);

                                    investi_nominale = Math.Abs(investi_nominale);
                                    disinvesti_nominale = Math.Abs(disinvesti_nominale);

                                    investi = Math.Abs(investi);
                                    disinvesti = Math.Abs(disinvesti);


                                    if (drprodotto["apporti_o_disinvestimenti"] != DBNull.Value)
                                        apporti_o_disinvestimenti = Convert.ToDouble(drprodotto["apporti_o_disinvestimenti"]);

                                    double ptfIniziale = controvalore_attuale;
                                    double ptfFinale = controvalore_proposta;

                                    bool IsANewPosition = Convert.ToBoolean(drprodotto["isanewposition"]);

                                    bool flagStatoSalvaProposta = false;
                                    if (drprodotto["flag_salvataggio_manuale"] != DBNull.Value)
                                        flagStatoSalvaProposta = Convert.ToBoolean(drprodotto["flag_salvataggio_manuale"]);

                                    double valoreNominaleContrattoSintesi = 0;
                                    double valoreCtvContrattoSintesi = 0;

                                    if (drprodotto["VALORESINTESI"] != DBNull.Value)
                                        valoreNominaleContrattoSintesi = Convert.ToDouble(drprodotto["VALORESINTESI"]);

                                    if (drprodotto["CTVSINTESI"] != DBNull.Value)
                                        valoreCtvContrattoSintesi = Convert.ToDouble(drprodotto["CTVSINTESI"]);

                                    if (!IsANewPosition)
                                    {
                                        // Prodotto in contratto sintesi e presente in  pianificazione 
                                        // K Skandia
                                        if (tipoProdottoAsul.Equals(rwAsulString))
                                        {
                                            #region SALDO ASUL
                                            #region Prodotti FAO/FAP
                                            string codiceInterno = string.Empty;

                                            if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                                codiceInterno = drprodotto["CODICEINTERNO"].ToString().Trim();

                                            if ((investi > 0 || disinvesti > 0) && IsFAOFAP(codiceInterno))
                                            {
                                                #region Chiamata la WSPOSIZIONECLIENTE

                                                PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente();
                                                _chiaveCliente.codiceAgente = codiceAgente;
                                                _chiaveCliente.codiceFiscale = codiceFiscale;
                                                _chiaveCliente.codiceMandato = string.Empty;

                                                PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient();
                                                _infoCliente.CodiceApplicazione = codiceApplicazione;
                                                _infoCliente.CodiceRete = codiceRete;
                                                _infoCliente.VersioneDatabaseSIMPB = versioneDBSimpb;

                                                string codiceContratto = drprodotto["CONTRATTO"].ToString().Trim();

                                                DataTable dtFAOFAP = DettagliAssicurativi(drprodotto, _chiaveCliente, codiceContratto, codiceInterno, _infoCliente, chiaveclientepb);

                                                #endregion

                                                foreach (DataRow rwFAOFAP in dtFAOFAP.Rows)
                                                {
                                                    saldo = new saldoType();

                                                    saldo.valore = (double)rwFAOFAP["IMPORTOINIZIALE"] + (double)rwFAOFAP["DELTA"];
                                                    saldo.valoreCtv = (double)rwFAOFAP["IMPORTOINIZIALE"] + (double)rwFAOFAP["DELTA"];

                                                    saldo.valoreCtvSpecified = true;

                                                    pkt = new ProdottiKeyType();

                                                    //CODICEADEGUATEZZA
                                                    if (rwFAOFAP["ISINFITTIZIO"] != DBNull.Value)
                                                        pkt.codiceAdeguatezza = rwFAOFAP["ISINFITTIZIO"].ToString();
                                                    else
                                                        pkt.codiceAdeguatezza = "";

                                                    //CODICESOTTOPRODOTTO
                                                    if (rwFAOFAP["ISINFITTIZIO"] != DBNull.Value)
                                                        pkt.codiceSottoprodotto = rwFAOFAP["ISINFITTIZIO"].ToString();
                                                    else
                                                        pkt.codiceSottoprodotto = "";

                                                    saldo.chiave = pkt;
                                                    ptfLivelloProdotto.AddSaldo(saldo);
                                                }
                                            }
                                            #endregion
                                            else
                                            {
                                                #region Chiamata la WSGLOBALPOSITION

                                                PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                                                _chiaveCliente.codiceAgente = codiceAgente;
                                                _chiaveCliente.codicefiscale = codiceFiscale;
                                                _chiaveCliente.codiceRete = codiceRete;
                                                _chiaveCliente.potenzialeClienteNAC = true;

                                                PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                                                _infoCliente.codiceApplicazione = codiceApplicazione;
                                                _infoCliente.codiceRete = codiceRete;
                                                _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;
                                                string codiceContratto = drprodotto["CONTRATTO"].ToString().Trim();

                                                GlobalPositionWS gpWS = new GlobalPositionWS();
                                                DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);

                                                #endregion

                                                foreach (DataRow rwAsul in dtAsul.Rows)
                                                {
                                                    saldo = new saldoType();

                                                    if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                                    {
                                                        ctvAsul = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());

                                                        ctvAsulCalcolato = Convert.ToDouble(ctvAsul * rapporto);
                                                        ctvAsulCalcolato = System.Math.Round(ctvAsulCalcolato, 2, MidpointRounding.ToEven);

                                                        saldo.valore = Convert.ToDouble(ctvAsulCalcolato);
                                                        saldo.valoreCtv = Convert.ToDouble(ctvAsulCalcolato);
                                                    }

                                                    saldo.valoreCtvSpecified = true;

                                                    pkt = new ProdottiKeyType();

                                                    //CODICEADEGUATEZZA
                                                    if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                                        pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                                    else
                                                        pkt.codiceAdeguatezza = "";

                                                    //CODICESOTTOPRODOTTO
                                                    if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                                        pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                                    else
                                                        pkt.codiceSottoprodotto = "";

                                                    //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                                    //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                                                    //if (drprodotto["CODICEISIN"] != DBNull.Value)
                                                    //    pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();

                                                    //if (drprodotto["CODICEMAF"] != DBNull.Value)
                                                    //    pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();


                                                    saldo.chiave = pkt;
                                                    ptfLivelloProdotto.AddSaldo(saldo);
                                                }
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            #region SALDO NON ASUL
                                            saldo = new saldoType();

                                            saldo.valore = valoreNominaleContrattoSintesi;

                                            #region Flag Stato Salvataggio Proposta
                                            if (flagStatoSalvaProposta)
                                            {
                                                // flagStatoSalvaProposta = 1
                                                ctvOperazione = Math.Abs(apporti_o_disinvestimenti);
                                                if (ctvOperazione > 0)
                                                {
                                                    // Rimodulazione del valore del saldo
                                                    //original_quote = valoreNominaleContrattoSintesi;
                                                    if (ptfFinale != valoreCtvContrattoSintesi)
                                                    {
                                                        // TODO: verificafe se arrotondare *****************************************
                                                        if (ptfIniziale != 0)
                                                        {
                                                            saldo.valore = (ptfFinale * valoreNominaleContrattoSintesi) / ptfIniziale;
                                                            saldo.valore = Math.Round(saldo.valore, 2, MidpointRounding.ToEven);
                                                        }
                                                        else
                                                            saldo.valore = 0;

                                                    }
                                                    if (investi_nominale > 0 || disinvesti_nominale > 0)
                                                    {
                                                        // Verificare se basta controllare il valore di investi/disinvesti senza controllare la 
                                                        // tipologia del prodotto come invece avviene sul SEI (Tipologie prodotti: COVWAR, WARRANT, OBBLIGAZIONI - OB, CERTIF)
                                                        // E SPERIAMO DI NO
                                                        saldo.valore = valoreNominaleContrattoSintesi + investi_nominale - disinvesti_nominale;
                                                    }
                                                }
                                            }

                                            saldo.valoreCtv = ptfFinale;

                                            #endregion

                                            saldo.valoreCtvSpecified = true;

                                            pkt = new ProdottiKeyType();
                                            //K Skandia
                                            if (rwAsulString.Equals(tipoProdottoAsu2))
                                            {
                                                //CODICEADEGUATEZZA
                                                if (drprodotto["ISIN_ASU2"] != DBNull.Value)
                                                    pkt.codiceAdeguatezza = drprodotto["ISIN_ASU2"].ToString();
                                                else
                                                    pkt.codiceAdeguatezza = "";

                                                //CODICESOTTOPRODOTTO
                                                if (drprodotto["ISIN_ASU2"] != DBNull.Value)
                                                    pkt.codiceSottoprodotto = drprodotto["ISIN_ASU2"].ToString();
                                                else
                                                    pkt.codiceSottoprodotto = "";

                                            }
                                            else
                                            {
                                                if (drprodotto["CODICEADEGUATEZZA"] != DBNull.Value)
                                                    pkt.codiceAdeguatezza = drprodotto["CODICEADEGUATEZZA"].ToString();
                                                else
                                                    pkt.codiceAdeguatezza = "";

                                                if (drprodotto["CODICEISIN"] != DBNull.Value)
                                                    pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();
                                                else
                                                    pkt.codiceIsin = "";

                                                if (drprodotto["CODICEMAF"] != DBNull.Value)
                                                    pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();
                                                else
                                                    pkt.codiceMaf = "";

                                                if (drprodotto["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                                    pkt.codiceSottoprodotto = drprodotto["CODICESOTTOPRODOTTO"].ToString();
                                                else
                                                    pkt.codiceSottoprodotto = "";

                                                if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                                    pkt.codiceInterno = drprodotto["CODICEINTERNO"].ToString();
                                                else
                                                    pkt.codiceInterno = "";
                                            }
                                            saldo.chiave = pkt;
                                            ptfLivelloProdotto.AddSaldo(saldo);
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        #region Gestione Contratto nuovo
                                        saldo = new saldoType();
                                        saldo.valore = ptfFinale;

                                        if (investi_nominale > 0 || disinvesti_nominale > 0)
                                        {
                                            // Verificare se basta controllare il valore di investi/disinvesti senza controllare la 
                                            // tipologia del prodotto come invece avviene sul SEI (Tipologie prodotti: COVWAR, WARRANT, OBBLIGAZIONI - OB, CERTIF)
                                            // E SPERIAMO DI NO
                                            saldo.valore = investi_nominale - disinvesti_nominale;
                                        }

                                        saldo.valoreCtv = ptfFinale;

                                        #region Saldo Chiave
                                        saldo.valoreCtvSpecified = true;
                                        pkt = new ProdottiKeyType();

                                        #region Codice adeguatezza presente
                                        if (drprodotto["CODICEADEGUATEZZA"] != DBNull.Value)
                                            pkt.codiceAdeguatezza = drprodotto["CODICEADEGUATEZZA"].ToString();
                                        #endregion
                                        #region Codice adeguatezza non presente
                                        else
                                            pkt.codiceAdeguatezza = "";
                                        #endregion

                                        if (drprodotto["CODICEISIN"] != DBNull.Value)
                                            pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();
                                        else
                                            pkt.codiceIsin = "";

                                        if (drprodotto["CODICEMAF"] != DBNull.Value)
                                            pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();
                                        else
                                            pkt.codiceMaf = "";

                                        if (drprodotto["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                            pkt.codiceSottoprodotto = drprodotto["CODICESOTTOPRODOTTO"].ToString();
                                        else
                                            pkt.codiceSottoprodotto = "";

                                        if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                            pkt.codiceInterno = drprodotto["CODICEINTERNO"].ToString();
                                        else
                                            pkt.codiceInterno = "";

                                        saldo.chiave = pkt;
                                        ptfLivelloProdotto.AddSaldo(saldo);
                                        #endregion
                                        #endregion
                                    }
                                    ptfLivelloProdotto.AddChildSaldoToAggregate();
                                    ptfLivelloProgetto.AddAggregato(ptfLivelloProdotto);

                                }
                                #endregion
                            }
                            ptfLivelloProgetto.AddChildToAggregate();
                            ptfLivelloNeedArea.AddAggregato(ptfLivelloProgetto);
                        }
                        #endregion
                    }

                    ptfLivelloNeedArea.AddChildToAggregate();
                    ptfTotale.AddAggregato(ptfLivelloNeedArea);
                    #endregion
                }
                else
                {
                    #region NON Investimento
                    foreach (DataRow drprodotto in dtRichiesta.Rows)
                    {
                        #region Livello Aggregato Prodotto
                        if (rwdistinct["needarea"].ToString() == drprodotto["needarea"].ToString())
                        {

                            if (drprodotto["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)drprodotto["TIPOPRODOTTOSINTESI"] == "")
                                rwAsulString = drprodotto["TIPOPRODOTTO"].ToString();
                            else
                                rwAsulString = drprodotto["TIPOPRODOTTOSINTESI"].ToString();

                            #region Aggregato di Prodotto
                            ptfLivelloProdotto = new ptfType();
                            ptfLivelloProdotto.descrizione = drprodotto["ID"].ToString();

                            double controvalore_proposta = Convert.ToDouble(drprodotto["controvalore_proposta"]);
                            double controvalore_attuale = Convert.ToDouble(drprodotto["controvalore_attuale"]);
                            double rapporto = Convert.ToDouble(drprodotto["rapporto"]);
                            double investi_nominale = 0;
                            double disinvesti_nominale = 0;
                            double apporti_o_disinvestimenti = 0;

                            if (drprodotto["investi_nominale"] != DBNull.Value)
                                investi_nominale = Convert.ToDouble(drprodotto["investi_nominale"]);

                            if (drprodotto["disinvesti_nominale"] != DBNull.Value)
                                disinvesti_nominale = Convert.ToDouble(drprodotto["disinvesti_nominale"]);

                            if (drprodotto["apporti_o_disinvestimenti"] != DBNull.Value)
                                apporti_o_disinvestimenti = Convert.ToDouble(drprodotto["apporti_o_disinvestimenti"]);

                            double ptfIniziale = controvalore_attuale;
                            double ptfFinale = controvalore_proposta;
                            double ctvAsulTotale = 0;

                            bool IsANewPosition = Convert.ToBoolean(drprodotto["isanewposition"]);

                            double valoreNominaleContrattoSintesi = 0;
                            double valoreCtvContrattoSintesi = 0;

                            if (drprodotto["VALORESINTESI"] != DBNull.Value)
                                valoreNominaleContrattoSintesi = Convert.ToDouble(drprodotto["VALORESINTESI"]);

                            if (drprodotto["CTVSINTESI"] != DBNull.Value)
                                valoreCtvContrattoSintesi = Convert.ToDouble(drprodotto["CTVSINTESI"]);

                            #endregion

                            if (!IsANewPosition)
                            {
                                // Prodotto in contratto sintesi
                                if (tipoProdottoAsul.Equals(rwAsulString))
                                {
                                    #region SALDO ASUL
                                    #region Prodotti FAO/FAP
                                    string codiceInterno = string.Empty;

                                    if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                        codiceInterno = drprodotto["CODICEINTERNO"].ToString().Trim();

                                    if ((investi_nominale != 0 || disinvesti_nominale != 0) && IsFAOFAP(codiceInterno))
                                    {
                                        #region Chiamata la WSPOSIZIONECLIENTE
                                        PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente();
                                        _chiaveCliente.codiceAgente = codiceAgente;
                                        _chiaveCliente.codiceFiscale = codiceFiscale;
                                        _chiaveCliente.codiceMandato = string.Empty;

                                        PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient();
                                        _infoCliente.CodiceApplicazione = codiceApplicazione;
                                        _infoCliente.CodiceRete = codiceRete;
                                        _infoCliente.VersioneDatabaseSIMPB = versioneDBSimpb;
                                        string codiceContratto = drprodotto["CONTRATTO"].ToString().Trim();

                                        DataTable dtFAOFAP = DettagliAssicurativi(drprodotto, _chiaveCliente, codiceContratto, codiceInterno, _infoCliente, chiaveclientepb);

                                        #endregion
                                        foreach (DataRow rwFAOFAP in dtFAOFAP.Rows)
                                        {
                                            saldo = new saldoType();

                                            saldo.valore = (double)rwFAOFAP["IMPORTOINIZIALE"] + (double)rwFAOFAP["DELTA"];
                                            saldo.valoreCtv = (double)rwFAOFAP["IMPORTOINIZIALE"] + (double)rwFAOFAP["DELTA"];

                                            saldo.valoreCtvSpecified = true;

                                            pkt = new ProdottiKeyType();

                                            //CODICEADEGUATEZZA
                                            if (rwFAOFAP["ISINFITTIZIO"] != DBNull.Value)
                                                pkt.codiceAdeguatezza = rwFAOFAP["ISINFITTIZIO"].ToString();
                                            else
                                                pkt.codiceAdeguatezza = "";

                                            //CODICESOTTOPRODOTTO
                                            if (rwFAOFAP["ISINFITTIZIO"] != DBNull.Value)
                                                pkt.codiceSottoprodotto = rwFAOFAP["ISINFITTIZIO"].ToString();
                                            else
                                                pkt.codiceSottoprodotto = "";

                                            saldo.chiave = pkt;
                                            ptfLivelloProdotto.AddSaldo(saldo);
                                        }
                                    }
                                    #endregion
                                    else
                                    {
                                        #region Chiamata la WSGLOBALPOSITION
                                        PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                                        _chiaveCliente.codiceAgente = codiceAgente;
                                        _chiaveCliente.codicefiscale = codiceFiscale;
                                        _chiaveCliente.codiceRete = codiceRete;
                                        _chiaveCliente.potenzialeClienteNAC = true;

                                        PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                                        _infoCliente.codiceApplicazione = codiceApplicazione;
                                        _infoCliente.codiceRete = codiceRete;
                                        _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;
                                        string codiceContratto = drprodotto["CONTRATTO"].ToString().Trim();

                                        GlobalPositionWS gpWS = new GlobalPositionWS();

                                        DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);

                                        //
                                        object SumCtvAsulTotale = dtAsul.Compute("Sum(CONTROVALORE)", "");

                                        if (SumCtvAsulTotale != null)
                                            ctvAsulTotale = Convert.ToDouble(SumCtvAsulTotale);

                                        double factor = 0;
                                        if (ctvAsulTotale == 0)
                                            factor = ptfFinale / dtAsul.Rows.Count;
                                        else
                                            factor = ptfFinale / ctvAsulTotale;


                                        #endregion

                                        foreach (DataRow rwAsul in dtAsul.Rows)
                                        {
                                            saldo = new saldoType();

                                            if (ctvAsulTotale == 0)
                                            {
                                                saldo.valore = factor;
                                                saldo.valoreCtv = factor;
                                            }
                                            else
                                            {
                                                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                                {
                                                    ctvAsul = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                                    ctvAsulCalcolato = ctvAsul * factor;
                                                    saldo.valore = ctvAsulCalcolato;
                                                    saldo.valoreCtv = ctvAsulCalcolato;

                                                    // come era prima
                                                    //saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                                    //saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                                }
                                            }
                                            saldo.valoreCtvSpecified = true;

                                            pkt = new ProdottiKeyType();

                                            //CODICEADEGUATEZZA
                                            if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                                pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                            else
                                                pkt.codiceAdeguatezza = "";

                                            //CODICESOTTOPRODOTTO
                                            if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                                pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                            else
                                                pkt.codiceSottoprodotto = "";

                                            //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                            //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                                            //if (drprodotto["CODICEISIN"] != DBNull.Value)
                                            //    pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();

                                            //if (drprodotto["CODICEMAF"] != DBNull.Value)
                                            //    pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();


                                            saldo.chiave = pkt;
                                            ptfLivelloProdotto.AddSaldo(saldo);
                                        }
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region SALDO NON ASUL
                                    saldo = new saldoType();

                                    //if (controvalore_attuale == 0) {
                                    //    // Nuovo Prodotto
                                    //    saldo.valore = controvalore_proposta;
                                    //    saldo.valoreCtv = controvalore_proposta;

                                    //}
                                    //else if (controvalore_proposta == 0) {
                                    //    saldo.valore = 0;
                                    //    saldo.valoreCtv = 0;

                                    //}
                                    //else {
                                    //    saldo.valore = System.Math.Round((valoreNominaleContrattoSintesi * rapporto), 2, MidpointRounding.ToEven);
                                    //    saldo.valoreCtv = controvalore_proposta;
                                    //}

                                    saldo.valore = valoreNominaleContrattoSintesi;

                                    ctvOperazione = Math.Abs(apporti_o_disinvestimenti);
                                    if (ctvOperazione > 0)
                                    {
                                        // Rimodulazione del valore del saldo
                                        //original_quote = valoreNominaleContrattoSintesi;

                                        if (ptfFinale != valoreCtvContrattoSintesi)
                                        {
                                            // TODO: verificafe se arrotondare *****************************************
                                            saldo.valore = (ptfFinale * valoreNominaleContrattoSintesi) / ptfIniziale;
                                            saldo.valore = Math.Round(saldo.valore, 2, MidpointRounding.ToEven);
                                        }
                                        if (investi_nominale > 0 || disinvesti_nominale > 0)
                                        {
                                            // Verificare se basta controllare il valore di investi/disinvesti senza controllare la 
                                            // tipologia del prodotto come invece avviene sul SEI (Tipologie prodotti: COVWAR, WARRANT, OBBLIGAZIONI - OB, CERTIF)
                                            // E SPERIAMO DI NO
                                            saldo.valore = valoreNominaleContrattoSintesi + investi_nominale - disinvesti_nominale;
                                        }
                                    }
                                    saldo.valoreCtv = ptfFinale;

                                    saldo.valoreCtvSpecified = true;

                                    pkt = new ProdottiKeyType();

                                    if (rwAsulString.Equals(tipoProdottoAsu2))
                                    {
                                        //CODICEADEGUATEZZA
                                        if (drprodotto["ISIN_ASU2"] != DBNull.Value)
                                            pkt.codiceAdeguatezza = drprodotto["ISIN_ASU2"].ToString();
                                        else
                                            pkt.codiceAdeguatezza = "";

                                        //CODICESOTTOPRODOTTO
                                        if (drprodotto["ISIN_ASU2"] != DBNull.Value)
                                            pkt.codiceSottoprodotto = drprodotto["ISIN_ASU2"].ToString();
                                        else
                                            pkt.codiceSottoprodotto = "";

                                    }
                                    else
                                    {

                                        if (drprodotto["CODICEADEGUATEZZA"] != DBNull.Value)
                                            pkt.codiceAdeguatezza = drprodotto["CODICEADEGUATEZZA"].ToString();
                                        else
                                            pkt.codiceAdeguatezza = "";

                                        if (drprodotto["CODICEISIN"] != DBNull.Value)
                                            pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();
                                        else
                                            pkt.codiceIsin = "";

                                        if (drprodotto["CODICEMAF"] != DBNull.Value)
                                            pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();
                                        else
                                            pkt.codiceMaf = "";

                                        if (drprodotto["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                            pkt.codiceSottoprodotto = drprodotto["CODICESOTTOPRODOTTO"].ToString();
                                        else
                                            pkt.codiceSottoprodotto = "";

                                        if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                            pkt.codiceInterno = drprodotto["CODICEINTERNO"].ToString();
                                        else
                                            pkt.codiceInterno = "";
                                    }
                                    saldo.chiave = pkt;
                                    ptfLivelloProdotto.AddSaldo(saldo);
                                    #endregion
                                }
                            }
                            else
                            {
                                #region Gestione Contratto nuovo
                                saldo = new saldoType();
                                saldo.valore = ptfFinale;

                                if (investi_nominale > 0 || disinvesti_nominale > 0)
                                {
                                    // Verificare se basta controllare il valore di investi/disinvesti senza controllare la 
                                    // tipologia del prodotto come invece avviene sul SEI (Tipologie prodotti: COVWAR, WARRANT, OBBLIGAZIONI - OB, CERTIF)
                                    // E SPERIAMO DI NO
                                    saldo.valore = investi_nominale - disinvesti_nominale;
                                }

                                saldo.valoreCtv = ptfFinale;
                                #region Saldo Chiave
                                saldo.valoreCtvSpecified = true;
                                pkt = new ProdottiKeyType();
                                #endregion

                                #region Codice adeguatezza presente
                                if (drprodotto["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = drprodotto["CODICEADEGUATEZZA"].ToString();
                                #endregion
                                #region Codice adeguatezza non presente
                                else
                                    pkt.codiceAdeguatezza = "";
                                #endregion

                                #region Codici non trovati in catalogo
                                if (drprodotto["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (drprodotto["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";

                                if (drprodotto["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = drprodotto["CODICESOTTOPRODOTTO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = drprodotto["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";
                                #endregion
                                saldo.chiave = pkt;
                                ptfLivelloProdotto.AddSaldo(saldo);
                                #endregion
                            }
                            ptfLivelloProdotto.AddChildSaldoToAggregate();
                            ptfLivelloNeedArea.AddAggregato(ptfLivelloProdotto);

                        }
                        #endregion
                    }
                    #endregion

                    ptfLivelloNeedArea.AddChildToAggregate();
                    ptfTotale.AddAggregato(ptfLivelloNeedArea);
                }

                ptfTotale.AddChildToAggregate();
                #endregion
            }

            #endregion

            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();


            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaVaRPortafoglioSezione70", ex.InnerException);
        }

        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione73(DataTable dtRichiesta, DataTable dtContrattiSintesiPerCliente)
    {
        #region Variabili costruzione oggetto MessageType
        DataTable dtDistinctNeedArea;
        DataTable dtDistinctProgetto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        saldoType saldo;
        ProdottiKeyType pkt;
        double ctvOperazione = 0;

        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwAsulString = "";
            codiceAgente = "";
            codiceRete = "";
            codiceFiscale = "";
            codiceApplicazione = "";
            versioneDBSimpb = 0;
            double ctvAsul = 0;
            double ctvAsulCalcolato = 0;
            double saldoValore = 0;
            double saldoValoreCtv = 0;



            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            String needAreaInv = ConfigurationManager.AppSettings["NEEDAREAINV"].ToString();

            // Eleboro il datatable richiesta
            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesiPerCliente);


            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALE";


            ptfType ptfLivelloProdotto;

            #region CREAZIONE OGGETTO MESSAGE


            foreach (DataRow drprodotto in dtRichiesta.Rows)
            {
                // 26/01/2010 d.lisena
                // controllo se il contratto � stato gi� liquidato. 
                // (Se il contratto non � presente nella Contratto Sintesi significa che � stato liquidato.)

                string codiceContratto = drprodotto["CONTRATTO"].ToString().Trim();
                bool calcolaAggregatoClientiPotenziali = false;
                DataRow[] rowFound = new DataRow[0];

                if (dtContrattiSintesiPerCliente != null)
                    rowFound = dtContrattiSintesiPerCliente.Select("codiceContratto='" + codiceContratto + "'");
                else
                    calcolaAggregatoClientiPotenziali = true; // il dtContrattiSintesiPerCliente � null solo quando il cliente � un cliente potenziale. In questo caso calcolo comunque l'aggregato senza tener conto se il contratto � stato gi� liquidato. 

                bool IsANewPosition = Convert.ToBoolean(drprodotto["isanewposition"]);

                if ((rowFound.Length > 0 || IsANewPosition) || calcolaAggregatoClientiPotenziali)
                {
                    #region Livello Aggregato Prodotto

                    if (drprodotto["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)drprodotto["TIPOPRODOTTOSINTESI"] == "")
                        rwAsulString = drprodotto["TIPOPRODOTTO"].ToString();
                    else
                        rwAsulString = drprodotto["TIPOPRODOTTOSINTESI"].ToString();

                    #region Aggregato di Prodotto
                    ptfLivelloProdotto = new ptfType();
                    ptfLivelloProdotto.descrizione = drprodotto["ID"].ToString();
                    #endregion

                    #region Variabili per proposta
                    double controvalore_proposta = Convert.ToDouble(drprodotto["controvalore_proposta"]);
                    double controvalore_attuale = Convert.ToDouble(drprodotto["controvalore_attuale"]);
                    double rapporto = Convert.ToDouble(drprodotto["rapporto"]);
                    double investi_nominale = 0;
                    double disinvesti_nominale = 0;
                    double investi = 0;
                    double disinvesti = 0;

                    double apporti_o_disinvestimenti = 0;


                    if (drprodotto["investi_nominale"] != DBNull.Value)
                        investi_nominale = Convert.ToDouble(drprodotto["investi_nominale"]);

                    if (drprodotto["disinvesti_nominale"] != DBNull.Value)
                        disinvesti_nominale = Convert.ToDouble(drprodotto["disinvesti_nominale"]);

                    if (drprodotto["investi"] != DBNull.Value)
                        investi = Convert.ToDouble(drprodotto["investi"]);

                    if (drprodotto["disinvesti"] != DBNull.Value)
                        disinvesti = Convert.ToDouble(drprodotto["disinvesti"]);

                    investi_nominale = Math.Abs(investi_nominale);
                    disinvesti_nominale = Math.Abs(disinvesti_nominale);

                    investi = Math.Abs(investi);
                    disinvesti = Math.Abs(disinvesti);


                    if (drprodotto["apporti_o_disinvestimenti"] != DBNull.Value)
                        apporti_o_disinvestimenti = Convert.ToDouble(drprodotto["apporti_o_disinvestimenti"]);

                    double ptfIniziale = controvalore_attuale;
                    double ptfFinale = controvalore_proposta;
                    double ctvAsulTotale = 0;




                    bool flagStatoSalvaProposta = false;
                    if (drprodotto["flag_salvataggio_manuale"] != DBNull.Value)
                        flagStatoSalvaProposta = Convert.ToBoolean(drprodotto["flag_salvataggio_manuale"]);

                    double valoreNominaleContrattoSintesi = 0;
                    double valoreCtvContrattoSintesi = 0;

                    if (drprodotto["VALORESINTESI"] != DBNull.Value)
                        valoreNominaleContrattoSintesi = Convert.ToDouble(drprodotto["VALORESINTESI"]);

                    if (drprodotto["CTVSINTESI"] != DBNull.Value)
                        valoreCtvContrattoSintesi = Convert.ToDouble(drprodotto["CTVSINTESI"]);

                    #endregion

                    #region Nuova gestione
                    saldo = new saldoType();

                    if (!IsANewPosition)
                    {
                        // Nuova posizione: NO
                        #region Posizione esistente in contratto sintesi
                        //K Skandia
                        if (tipoProdottoAsul.Equals(rwAsulString))
                        {
                            #region Prodotti ASUL
                            #region Prodotti FAO/FAP, con movimentazione
                            string codiceInterno = string.Empty;

                            if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                codiceInterno = drprodotto["CODICEINTERNO"].ToString().Trim();

                            if ((investi > 0 || disinvesti > 0) && IsFAOFAP(codiceInterno))
                            {
                                #region Chiamata la WSPOSIZIONECLIENTE

                                PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente();
                                _chiaveCliente.codiceAgente = codiceAgente;
                                _chiaveCliente.codiceFiscale = codiceFiscale;
                                _chiaveCliente.codiceMandato = string.Empty;

                                PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient();
                                _infoCliente.CodiceApplicazione = codiceApplicazione;
                                _infoCliente.CodiceRete = codiceRete;
                                _infoCliente.VersioneDatabaseSIMPB = versioneDBSimpb;

                                DataTable dtFAOFAP = DettagliAssicurativi(drprodotto, _chiaveCliente, codiceContratto, codiceInterno, _infoCliente, chiaveclientepb);

                                #endregion
                                foreach (DataRow rwFAOFAP in dtFAOFAP.Rows)
                                {
                                    saldo = new saldoType();

                                    saldo.valore = (double)rwFAOFAP["IMPORTOINIZIALE"] + (double)rwFAOFAP["DELTA"];
                                    saldo.valoreCtv = (double)rwFAOFAP["IMPORTOINIZIALE"] + (double)rwFAOFAP["DELTA"];

                                    saldo.valoreCtvSpecified = true;

                                    pkt = new ProdottiKeyType();

                                    //CODICEADEGUATEZZA
                                    if (rwFAOFAP["ISINFITTIZIO"] != DBNull.Value)
                                        pkt.codiceAdeguatezza = rwFAOFAP["ISINFITTIZIO"].ToString();
                                    else
                                        pkt.codiceAdeguatezza = "";

                                    //CODICESOTTOPRODOTTO
                                    if (rwFAOFAP["ISINFITTIZIO"] != DBNull.Value)
                                        pkt.codiceSottoprodotto = rwFAOFAP["ISINFITTIZIO"].ToString();
                                    else
                                        pkt.codiceSottoprodotto = "";

                                    saldo.chiave = pkt;
                                    ptfLivelloProdotto.AddSaldo(saldo);
                                }
                            }
                            #endregion
                            else
                            {
                                #region Chiamata la WSGLOBALPOSITION
                                PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                                _chiaveCliente.codiceAgente = codiceAgente;
                                _chiaveCliente.codicefiscale = codiceFiscale;
                                _chiaveCliente.codiceRete = codiceRete;
                                _chiaveCliente.potenzialeClienteNAC = true;

                                PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                                _infoCliente.codiceApplicazione = codiceApplicazione;
                                _infoCliente.codiceRete = codiceRete;
                                _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;


                                GlobalPositionWS gpWS = new GlobalPositionWS();

                                DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);

                                object SumCtvAsulTotale = dtAsul.Compute("Sum(CONTROVALORE)", "");

                                if (SumCtvAsulTotale != null)
                                    ctvAsulTotale = Convert.ToDouble(SumCtvAsulTotale);

                                double factor = 0;

                                if (ctvAsulTotale == 0)
                                {
                                    factor = ptfFinale / dtAsul.Rows.Count;
                                }
                                else
                                {
                                    factor = ptfFinale / ctvAsulTotale;
                                }

                                #endregion
                                foreach (DataRow rwAsul in dtAsul.Rows)
                                {
                                    saldo = new saldoType();


                                    if (ctvAsulTotale == 0)
                                    {
                                        saldo.valore = factor;
                                        saldo.valoreCtv = factor;
                                    }
                                    else
                                    {
                                        if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                        {

                                            ctvAsul = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());

                                            ctvAsulCalcolato = ctvAsul * factor;

                                            saldo.valore = ctvAsulCalcolato;
                                            saldo.valoreCtv = ctvAsulCalcolato;
                                        }
                                    }

                                    saldo.valoreCtvSpecified = true;

                                    pkt = new ProdottiKeyType();

                                    //CODICEADEGUATEZZA
                                    if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                        pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                    else
                                        pkt.codiceAdeguatezza = "";

                                    //CODICESOTTOPRODOTTO
                                    if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                        pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                    else
                                        pkt.codiceSottoprodotto = "";



                                    saldo.chiave = pkt;
                                    ptfLivelloProdotto.AddSaldo(saldo);
                                }

                            }
                            #endregion
                        }
                        else
                        {
                            #region Prodotti NO ASUL
                            saldo.valore = valoreNominaleContrattoSintesi;

                            #region Flag Stato Salvataggio Proposta
                            if (flagStatoSalvaProposta)
                            {
                                // flagStatoSalvaProposta = 1
                                ctvOperazione = Math.Abs(apporti_o_disinvestimenti);
                                if (ctvOperazione > 0)
                                {
                                    // Rimodulazione del valore del saldo
                                    //original_quote = valoreNominaleContrattoSintesi;
                                    if (ptfFinale != valoreCtvContrattoSintesi)
                                    {
                                        // TODO: verificafe se arrotondare *****************************************
                                        if (ptfIniziale != 0)
                                        {
                                            saldo.valore = (ptfFinale * valoreNominaleContrattoSintesi) / ptfIniziale;
                                            saldo.valore = Math.Round(saldo.valore, 2, MidpointRounding.ToEven);
                                        }
                                        else
                                            saldo.valore = 0;

                                    }
                                    if (investi_nominale > 0 || disinvesti_nominale > 0)
                                    {
                                        // Verificare se basta controllare il valore di investi/disinvesti senza controllare la 
                                        // tipologia del prodotto come invece avviene sul SEI (Tipologie prodotti: COVWAR, WARRANT, OBBLIGAZIONI - OB, CERTIF)
                                        // E SPERIAMO DI NO
                                        saldo.valore = valoreNominaleContrattoSintesi + investi_nominale - disinvesti_nominale;
                                    }
                                }

                            }

                            saldo.valoreCtv = ptfFinale;

                            #endregion

                            #region Saldo Chiave
                            saldo.valoreCtvSpecified = true;
                            pkt = new ProdottiKeyType();
                            //K Skandia
                            if (rwAsulString.Equals(tipoProdottoAsu2))
                            {
                                //CODICEADEGUATEZZA
                                if (drprodotto["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = drprodotto["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (drprodotto["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = drprodotto["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                            }
                            else
                            {
                                if (drprodotto["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = drprodotto["CODICEADEGUATEZZA"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (drprodotto["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (drprodotto["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";

                                if (drprodotto["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = drprodotto["CODICESOTTOPRODOTTO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = drprodotto["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";
                            }
                            saldo.chiave = pkt;
                            ptfLivelloProdotto.AddSaldo(saldo);
                            #endregion
                            #endregion
                        }
                        #endregion
                    }
                    else
                    {
                        // Nuova posizione: SI
                        #region New Position
                        saldo.valore = ptfFinale;

                        if (investi_nominale > 0 || disinvesti_nominale > 0)
                        {
                            // Verificare se basta controllare il valore di investi/disinvesti senza controllare la 
                            // tipologia del prodotto come invece avviene sul SEI (Tipologie prodotti: COVWAR, WARRANT, OBBLIGAZIONI - OB, CERTIF)
                            // E SPERIAMO DI NO
                            saldo.valore = investi_nominale - disinvesti_nominale;
                        }

                        saldo.valoreCtv = ptfFinale;

                        #region Saldo Chiave
                        saldo.valoreCtvSpecified = true;
                        pkt = new ProdottiKeyType();

                        if (drprodotto["CODICEADEGUATEZZA"] != DBNull.Value)
                            pkt.codiceAdeguatezza = drprodotto["CODICEADEGUATEZZA"].ToString();
                        else
                            pkt.codiceAdeguatezza = "";

                        if (drprodotto["CODICEISIN"] != DBNull.Value)
                            pkt.codiceIsin = drprodotto["CODICEISIN"].ToString();
                        else
                            pkt.codiceIsin = "";

                        if (drprodotto["CODICEMAF"] != DBNull.Value)
                            pkt.codiceMaf = drprodotto["CODICEMAF"].ToString();
                        else
                            pkt.codiceMaf = "";

                        if (drprodotto["CODICESOTTOPRODOTTO"] != DBNull.Value)
                            pkt.codiceSottoprodotto = drprodotto["CODICESOTTOPRODOTTO"].ToString();
                        else
                            pkt.codiceSottoprodotto = "";

                        if (drprodotto["CODICEINTERNO"] != DBNull.Value)
                            pkt.codiceInterno = drprodotto["CODICEINTERNO"].ToString();
                        else
                            pkt.codiceInterno = "";

                        saldo.chiave = pkt;
                        ptfLivelloProdotto.AddSaldo(saldo);
                        #endregion

                        #endregion

                    }
                    #endregion

                    ptfLivelloProdotto.AddChildSaldoToAggregate();
                    ptfTotale.AddAggregato(ptfLivelloProdotto);
                    #endregion
                }
            }
            #endregion

            ptfTotale.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();


            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaVaRPortafoglioSezione73", ex.InnerException);
        }

        return mt;

    }

    /// <summary>
    /// Struttura dati per memorizzare i codici delle asset class
    /// </summary>
    /// <returns>un dictonary con le liste delle Asset class (OB = Obbligazionario, AZ = Azionario</returns>
    private static Dictionary<string, List<AssetClass>> initializeTabellaAsset()
    {
        Dictionary<string, List<AssetClass>> result = new Dictionary<string, List<AssetClass>>();
        List<AssetClass> listaAsset = new List<AssetClass>();

        DataTable dtMappatura_MacroAsset_Asset = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaEvoluta, "REP_MacroAsset_Asset", null);

        DataTable distinctMacroAsset = dtMappatura_MacroAsset_Asset.DefaultView.ToTable(true, "Codice_MacroAsset");

        foreach (DataRow row in dtMappatura_MacroAsset_Asset.Rows)
        {
            listaAsset.Add(new AssetClass
            {
                Descrizione = row["AssetClassName_Report"].ToString(),
                ISIN = row["Codice_Isin"].ToString(),
                MAF = row["Codice_Maf"].ToString(),
                Adeguatezza = row["Codice_Adeguatezza"] == DBNull.Value ? string.Empty : row["Codice_Adeguatezza"].ToString(),
                MacroAsset = row["Codice_MacroAsset"].ToString()
            });
        }

        foreach (DataRow macro in distinctMacroAsset.Rows)
            result.Add(macro["Codice_MacroAsset"].ToString(), listaAsset.FindAll(a => a.MacroAsset.Equals(macro["Codice_MacroAsset"].ToString())));

        return result;
    }

    private static AssetClass findAssetClass(string codeAsset)
    {
        List<AssetClass> listaAsset = null;
        try
        {
            listaAsset = DettaglioAsset[codeAsset.Substring(0, 2)];
        }
        catch (KeyNotFoundException k)
        {

        }
        AssetClass asset = null;
        if (listaAsset != null)
            foreach (AssetClass a in listaAsset)
                if (a.ISIN == codeAsset)
                    asset = a;
        return asset;
    }

    /// <summary>
    /// Recupera le classi di rischio per emittente.
    /// </summary>
    private static DataTable LoadTabellaRischioCreditoEmit()
    {
        //DataTable dt_riskclass = DataAccess.ExecuteDataTableSqlStatement(DBProvider.Oracle, "SELECT OID$ as COD, CLASSE as DESCR, MAXVAL, MINVAL, CODICE FROM RISKEMIT", null);
        //HttpContext.Current.Cache.Insert("RiskClassEmit", dt_riskclass, null, DateTime.UtcNow.AddMinutes(5), TimeSpan.Zero);
        //return dt_riskclass;       

        return DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaEvoluta, "REP_CLASSIRISCHIOCREDITOPEREMITTENTI", null);
    }

    /// <summary>
    /// Recupera il dettaglio della classe rischio.
    /// </summary>
    /// <returns></returns>
    private static DataTable LoadTabellaRischioCredito()
    {
        //DataTable dt_riskclass = DataAccess.ExecuteDataTableSqlStatement(DBProvider.Oracle, "select cod, descr , maxval, minval  from riskclas", null);
        //HttpContext.Current.Cache.Insert("RiskClass", dt_riskclass, null, DateTime.UtcNow.AddMinutes(5), TimeSpan.Zero);
        //return dt_riskclass;
        return DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaEvoluta, "REP_CLASSIRISCHIOCREDITO", null);
    }

    /// <summary>
    /// Ritorna una stringa concatenata di classi di rischio della lista di ptf passati in input.
    /// Le classi di Rischio Non Definite (n.a. e n.c.) sono ritornate solo se non sono presenti le di Rischio Definite.
    /// </summary>
    /// <param name="ptfList"></param>
    /// <returns></returns>
    public static string getClassiRischioEmit(List<ptfType> ptfList)
    {
        string returnString = string.Empty;

        Dictionary<int, string> classiRischioNonDefinite = new Dictionary<int, string>();
        SortedDictionary<int, string> classiRischioDefinite = new SortedDictionary<int, string>();

        double valoreMassimo;
        double valoreMinimo;

        DataTable tb_RiskClass = (DataTable)HttpContext.Current.Cache["RiskClassEmit"];

        if (tb_RiskClass == null)
            tb_RiskClass = LoadTabellaRischioCreditoEmit();

        #region Recupero una lista di Classi rischio di credito

        foreach (ptfType ptf in ptfList)
        {
            //Controllo se la copertura � uguale a 0
            if (ptf.stat.copertura == null)
            {
                if (!classiRischioNonDefinite.ContainsKey(-1))
                    classiRischioNonDefinite.Add(-1, "n.c.");
            }
            else
            {
                if (ptf.stat.copertura == 0)
                {
                    if (!classiRischioNonDefinite.ContainsKey(-1))
                        classiRischioNonDefinite.Add(-1, "n.c.");
                }
                else
                {
                    if (ptf.misureRischio.isAttivoRC == 0)
                    {
                        if (!classiRischioNonDefinite.ContainsKey(-2))
                            classiRischioNonDefinite.Add(-2, "n.a.");
                    }
                    else
                    {
                        //Confronto il rischio credito con la tabella RISKCLAS per ottenere la classe di rischio
                        foreach (DataRow rw in tb_RiskClass.Rows)
                        {
                            valoreMassimo = double.Parse(rw["MAXVAL"].ToString());
                            valoreMinimo = double.Parse(rw["MINVAL"].ToString());

                            if (((ptf.misureRischio.rischioCredito) >= valoreMinimo) & ((ptf.misureRischio.rischioCredito) <= valoreMassimo))
                            {
                                if (!classiRischioDefinite.ContainsKey(Convert.ToInt32(rw["CODICE"])))
                                    classiRischioDefinite.Add(Convert.ToInt32(rw["CODICE"]), rw["DESCR"].ToString());
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region Rielaborazione della stringa di ritorno delle classiRischioDefinite

        // Aggiungo le classiRischioDefinite
        if (classiRischioDefinite.Count > 0)
        {
            if (classiRischioDefinite.Count > 1)
            {
                // Rielaborazione della stringa di ritorno delle classiRischioDefinite               
                returnString = "Rischio ";
                foreach (KeyValuePair<int, string> item in classiRischioDefinite)
                {
                    returnString += item.Key + "-";
                }

                if (returnString.EndsWith("-"))
                    returnString = returnString.Substring(0, returnString.Length - 1);

                returnString += "/10";
            }
            else
            {
                foreach (KeyValuePair<int, string> item in classiRischioDefinite)
                {
                    returnString = item.Value;
                }
            }
        }

        // Aggiungo le classiRischioNonDefinite
        if (classiRischioNonDefinite.Count > 0)
        {
            if (classiRischioDefinite.Count == 0)
            {
                //returnString += "-";

                foreach (KeyValuePair<int, string> item in classiRischioNonDefinite)
                {
                    returnString += item.Value + "-";
                }

                if (returnString.EndsWith("-"))
                    returnString = returnString.Substring(0, returnString.Length - 1);
            }
        }

        #endregion

        return returnString;
    }

    /// <summary>
    /// Ritorna una lista di interi che rappresentano la lsita di codici di classe di rischio del ptf passato in input.
    /// Ritorna -2 per rischio credito = "n.a." oppure -1 per rischio credito uguale "n.c".
    /// Le classi di Rischio Non Definite (n.a. e n.c.) sono ritornate solo se non sono presenti le di Rischio Definite.
    /// </summary>
    /// <param name="pft"></param>
    /// <returns></returns>
    public static List<decimal> getCodiciClassiRischioEmit(List<ptfType> ptfList)
    {
        List<decimal> returnCodiciClassiRischio = new List<decimal>();

        Dictionary<int, string> classiRischioNonDefinite = new Dictionary<int, string>();
        SortedDictionary<int, string> classiRischioDefinite = new SortedDictionary<int, string>();

        double valoreMassimo;
        double valoreMinimo;

        DataTable tb_RiskClass = (DataTable)HttpContext.Current.Cache["RiskClassEmit"];

        if (tb_RiskClass == null)
            tb_RiskClass = LoadTabellaRischioCreditoEmit();

        #region Recupero una lista di Classi rischio di credito

        foreach (ptfType ptf in ptfList)
        {
            //Controllo se la copertura � uguale a 0
            if (ptf.stat.copertura == null)
            {
                if (!classiRischioNonDefinite.ContainsKey(-1))
                    classiRischioNonDefinite.Add(-1, "n.c.");
            }
            else
            {
                if (ptf.stat.copertura == 0)
                {
                    if (!classiRischioNonDefinite.ContainsKey(-1))
                        classiRischioNonDefinite.Add(-1, "n.c.");
                }
                else
                {
                    if (ptf.misureRischio.isAttivoRC == 0)
                    {
                        if (!classiRischioNonDefinite.ContainsKey(-2))
                            classiRischioNonDefinite.Add(-2, "n.a.");
                    }
                    else
                    {
                        //Confronto il rischio credito con la tabella RISKCLAS per ottenere la classe di rischio
                        foreach (DataRow rw in tb_RiskClass.Rows)
                        {
                            valoreMassimo = double.Parse(rw["MAXVAL"].ToString());
                            valoreMinimo = double.Parse(rw["MINVAL"].ToString());

                            if (((ptf.misureRischio.rischioCredito) >= valoreMinimo) & ((ptf.misureRischio.rischioCredito) <= valoreMassimo))
                            {
                                if (!classiRischioDefinite.ContainsKey(Convert.ToInt32(rw["CODICE"])))
                                    classiRischioDefinite.Add(Convert.ToInt32(rw["CODICE"]), rw["DESCR"].ToString());
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region Rielaborazione della lista di ritorno delle classiRischioNonDefinite e classiRischioDefinite


        // Aggiungo le classiRischioDefinite
        if (classiRischioDefinite.Count > 0)
        {
            foreach (KeyValuePair<int, string> item in classiRischioDefinite)
            {
                returnCodiciClassiRischio.Add(item.Key);
            }
        }

        if (classiRischioDefinite.Count == 0)
        {
            // Aggiungo le classiRischioNonDefinite
            if (classiRischioNonDefinite.Count > 0)
            {
                foreach (KeyValuePair<int, string> item in classiRischioNonDefinite)
                {
                    returnCodiciClassiRischio.Add(item.Key);
                }
            }
        }

        #endregion

        return returnCodiciClassiRischio;

    }

    /// <summary>
    /// Recupera un valore stringa che rappresenta la classe di rischio per Emittente.
    /// </summary>
    public static string getClasseRischioEmit(misureType aggregato, statType statCopertura)
    {
        try
        {
            string vClasserischio;
            double vMax;
            double vMin;

            vClasserischio = "n.a.";

            DataTable tb_RiskClass = (DataTable)HttpContext.Current.Cache["RiskClassEmit"];

            if (tb_RiskClass == null)
            {
                tb_RiskClass = LoadTabellaRischioCreditoEmit();
            }
            //Controllo se la copertura � uguale a 0
            if (statCopertura == null)
                vClasserischio = "n.c.";
            else
            {
                if (statCopertura.copertura == 0)
                    vClasserischio = "n.c.";
                else
                    //Se l'aggregato isAttivo � uguale 0 restituisco N.A.
                    if (aggregato.isAttivoRC == 0)
                        vClasserischio = "n.a.";
                    else
                        //Confronto il rischio credito con la tabella RISKCLAS per ottenere la classe di rischio
                        foreach (DataRow rw in tb_RiskClass.Rows)
                        {
                            vMax = double.Parse(rw["MAXVAL"].ToString());
                            vMin = double.Parse(rw["MINVAL"].ToString());
                            if (((aggregato.rischioCredito) >= vMin) & ((aggregato.rischioCredito) <= vMax))
                                return rw["DESCR"].ToString();
                        }
            }

            return vClasserischio;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: getClasseRischioEmit ", ex.InnerException);
        }
    }

    /// <summary>
    /// Recupera un valore intero che indica il codice della classe di rischio per Emittente.
    /// Ritorna 0 per rischio credito = "n.a." oppure -1 per rischio credito uguale "n.c".
    /// </summary>
    public static int getCodiceClasseRischioEmit(misureType aggregato, statType statCopertura)
    {
        try
        {
            int codiceClasseRischioCredito;
            double vMax;
            double vMin;

            codiceClasseRischioCredito = 0;

            DataTable tb_RiskClass = (DataTable)HttpContext.Current.Cache["RiskClassEmit"];

            if (tb_RiskClass == null)
            {
                tb_RiskClass = LoadTabellaRischioCreditoEmit();
            }
            //Controllo se la copertura � uguale a 0
            if (statCopertura == null)
            {
                codiceClasseRischioCredito = -1;
            }
            else
            {
                if (statCopertura.copertura == 0)
                    codiceClasseRischioCredito = -1;
                else
                    //Se l'aggregato isAttivo � uguale 0 restituisco N.A.
                    if (aggregato.isAttivoRC == 0)
                        codiceClasseRischioCredito = 0;
                    else
                        //Confronto il rischio credito con la tabella RISKCLAS per ottenere la classe di rischio
                        foreach (DataRow rw in tb_RiskClass.Rows)
                        {
                            vMax = double.Parse(rw["MAXVAL"].ToString());
                            vMin = double.Parse(rw["MINVAL"].ToString());
                            if (((aggregato.rischioCredito) >= vMin) & ((aggregato.rischioCredito) <= vMax))
                                return Convert.ToInt32(rw["CODICE"]);
                        }
            }

            return codiceClasseRischioCredito;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: getCodiceClasseRischioEmit ", ex.InnerException);
        }
    }

    /// <summary>
    /// Recupera un valore stringa che rappresenta la classe di rischio.
    /// </summary>
    public static string getClasseRischio(misureType aggregato, statType statCopertura)
    {
        try
        {
            string vClasserischio;
            double vMax;
            double vMin;

            vClasserischio = "n.a.";
            //Popolo la tabella RISKCLASS   
            DataTable tb_RiskClass = LoadTabellaRischioCredito();

            //Controllo se la copertura � uguale a 0
            if (statCopertura == null)
            {
                vClasserischio = "n.c.";
            }
            else
            {

                if (statCopertura.copertura == 0)
                    vClasserischio = "n.c.";
                else
                    //Se l'aggregato isAttivo � uguale 0 restituisco N.A.
                    if (aggregato.isAttivoRC == 0)
                        vClasserischio = "n.a.";
                    else
                        //Confronto il rischio credito con la tabella RISKCLAS per ottenere la classe di rischio
                        foreach (DataRow rw in tb_RiskClass.Rows)
                        {
                            vMax = double.Parse(rw["MAXVAL"].ToString());
                            vMin = double.Parse(rw["MINVAL"].ToString());
                            if (((aggregato.rischioCredito) >= vMin) & ((aggregato.rischioCredito) <= vMax))
                                return rw["DESCR"].ToString();
                        }
            }
            return vClasserischio;

        }

        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: getClasseRischio ", ex.InnerException);
        }
    }

    /// <summary>
    /// Recupera un valore stringa che rappresenta la classe di rischio. [Classe A, Classe B...]
    /// </summary>
    /// <param name="rischiodicredito"></param>
    /// <param name="copertura"></param>
    /// <param name="tipoprodotto">Passare string.empty per bypassare controllo sul tipoprodotto che impone NC per i CC</param>
    /// <param name="isattivorc"></param>
    /// <returns></returns>
    public static string getClasseRischio(decimal rischiodicredito, decimal copertura, string tipoprodotto, int isattivorc)
    {
        string returnValueRischioCredito = "n.a.";

        if (tipoprodotto.ToLower() == "cc")
            return "n.a.";

        if (copertura.Equals(0))
            return "n.c.";

        if (isattivorc.Equals(0))
            return "n.a.";

        decimal vMin = 0;
        decimal vMax = 0;

        //Popolo la tabella RISKCLASS   
        DataTable tb_RiskClass = LoadTabellaRischioCredito();

        foreach (DataRow rw in tb_RiskClass.Rows)
        {
            vMax = Convert.ToDecimal(rw["MAXVAL"]);
            vMin = Convert.ToDecimal(rw["MINVAL"]);
            if (((rischiodicredito) >= vMin) & ((rischiodicredito) <= vMax))
                returnValueRischioCredito = rw["DESCR"].ToString();
        }

        return returnValueRischioCredito;
    }


    /// <summary>
    /// Recupera un valore stringa che rappresenta la classe di rischio. [Rischio 1/10, Rischio 2/10...]
    /// </summary>
    /// <param name="rischiodicredito"></param>
    /// <param name="copertura"></param>
    /// <param name="tipoprodotto">Passare string.empty per bypassare controllo sul tipoprodotto che impone NC per i CC</param>
    /// <param name="isattivorc"></param>
    /// <returns></returns>
    public static string getClasseRischioEmit(decimal rischiodicredito, decimal copertura, string tipoprodotto, int isattivorc)
    {
        string returnValueRischioCredito = "n.a.";

        if (tipoprodotto.ToLower() == "cc")
            return "n.a.";

        if (copertura.Equals(0))
            return "n.c.";

        if (isattivorc.Equals(0))
            return "n.a.";

        decimal vMin = 0;
        decimal vMax = 0;

        //Popolo la tabella RISKCLASS   
        DataTable tb_RiskClass = LoadTabellaRischioCreditoEmit();

        foreach (DataRow rw in tb_RiskClass.Rows)
        {
            vMax = Convert.ToDecimal(rw["MAXVAL"]);
            vMin = Convert.ToDecimal(rw["MINVAL"]);
            if (((rischiodicredito) >= vMin) & ((rischiodicredito) <= vMax))
                returnValueRischioCredito = rw["DESCR"].ToString();
        }

        return returnValueRischioCredito;
    }


    /// <summary>
    /// Decodifica la classe di rischio passata in input e ritorna il codice relativo (int) della classe rischio.
    /// Ritorna -1 se non trova la classe, 5 per NA, 6 per NC
    /// </summary>
    /// <param name="classe">Classe A, Classe B, Classe C ...</param>
    /// <returns>Il codice (1,2,3,4)</returns>
    public static int DecodeClasseRischio(string classe)
    {
        int ret = -1;
        DataTable dtRischioCredito = LoadTabellaRischioCredito();

        foreach (DataRow row in dtRischioCredito.Rows)
            if (row["DESCR"].ToString().ToLower().Equals(classe.ToLower()))
            {
                ret = Convert.ToInt32(row["COD"]);
                break;
            }
        return ret;
    }

    /// <summary>
    /// Decodifica il codice della classe rischio passata in input e ritorna la descrizione della classe rischio.
    /// Ritorna "n.a." se non trova la classe
    /// </summary>
    /// <param name="codiceclasse">1,2,3...</param>
    /// <returns>La descrizione della classe di rischio (Classe A, Classe B, Classe C ...)</returns>
    public static string DecodeClasseRischio(int codiceclasse)
    {
        string ret = "n.a.";
        DataTable dtRischioCredito = LoadTabellaRischioCredito();

        foreach (DataRow row in dtRischioCredito.Rows)
            if (Convert.ToInt32(row["COD"]).Equals(codiceclasse))
            {
                ret = row["DESCR"].ToString();
                break;
            }
        return ret;
    }


    private static messaggioType CreaRichiestaPortafoglioModello(DataTable dtQuestionario, DataTable dtPosizioniCliente, DataRow drDatiPortModello)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaPTFModelloType richiestaPortafoglioModello;
        parametriPTFModelloType parametriPTFModello;

        #endregion
        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaPortafoglioModello = new richiestaPTFModelloType();
            richiesta.Item = richiestaPortafoglioModello;
            string descrizionePtf = "";

            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaPortafoglioModello

            #region Area Di Bisogno
            richiestaPortafoglioModello.areaBisogno = (int)drDatiPortModello["NEEDAREA"];

            if (richiestaPortafoglioModello.areaBisogno == 3)
                descrizionePtf = "INV";
            else
                if (richiestaPortafoglioModello.areaBisogno == 1)
                    descrizionePtf = "RIS";

            #endregion

            #region Parametri PTF Modello
            parametriPTFModello = new parametriPTFModelloType();
            parametriPTFModello.orizzonteTemporale = (int)drDatiPortModello["ORIZZONTE_TEMPORALE"]; ;
            parametriPTFModello.tolleranzaRischio = (int)drDatiPortModello["PROFILO_RISCHIO"]; ;

            richiestaPortafoglioModello.parametriPTFModello = parametriPTFModello;
            #endregion
            #endregion
            #endregion

            #region I Chiamata Prometeia
            messaggioType retMessageObj = null;

            string ms = SerializeMessage(mt);

            IPrometeia proxy = XmlRpcProxyGen.Create<IPrometeia>();

            proxy.Url = ConfigurationManager.AppSettings["XMLRPCURL"].ToString();
            //da laboratorio:
            string _proxy;
            if (ConfigurationManager.AppSettings["PROXYXMLRPC"] != null)
                _proxy = ConfigurationManager.AppSettings["PROXYXMLRPC"].ToString();
            else
                _proxy = "";

            if (_proxy.Trim() != "")
            {
                //proxy.Proxy = new WebProxy(_proxy); //non disponibile per problemi sistemistici

                // Questa impostazione � utilizzata solo internamente ad HP.
                // E' un rimedio al fatto che http://paa.prometeia.it non � pi� raggiungibile per problemi sistemistici.
                // Non essendo piu disponibile utilizzo http://134.44.28.136:9882 aggiungendo delle eccezioni ai settaggi del proxy da utilizzare.
                // Se dovesse di nuovo essere disponibile � suff scommetare "//non disponibile per problemi sistemistici" ed eliminare il codice sottostante
                List<string> bypasslist = new List<string>();
                bypasslist.Add(@"localhost");
                bypasslist.Add(@"127.0.0.1");
                bypasslist.Add(@"134.44.28.136");

                WebProxy proxyLocale = new WebProxy(_proxy);
                proxyLocale.BypassList = bypasslist.ToArray();
                proxy.Proxy = proxyLocale;

            }

            string retMessage = proxy.AnalizzaRichiesta(ms.TrimStart().TrimEnd());

            retMessageObj = DeserializeMessage(retMessage);
            #endregion

            #region II Chiamata Prometeia
            bodyMessaggioType rispostaBodyMessage = retMessageObj.bodyMessaggio;
            rispostaType rispostaModello = (rispostaType)rispostaBodyMessage.Item;
            rispostaPTFModelloType rispostaPTFModello = (rispostaPTFModelloType)rispostaModello.Item;

            soluzioniType soluzioni = rispostaPTFModello.soluzioni;
            List<strumentoType> strumenti2 = new List<strumentoType>();


            foreach (assetAllocationItemType item in soluzioni.assetAllocation.assetAllocationItem)
            {
                strumentoType strumento = new strumentoType();
                ProdottiKeyType chiave = new ProdottiKeyType();

                if (item.codice.Equals(CodiciPrometeia._MNEU))
                {
                    chiave.codiceIsin = CodiciPrometeia._MNEU;
                    chiave.codiceMaf = CodiciPrometeia._MNEU;
                    chiave.codiceAdeguatezza = CodiciPrometeia._JPEC6ML;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBGVEUBR))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBGVEUBR;
                    chiave.codiceMaf = CodiciPrometeia._OBGVEUBR;
                    chiave.codiceAdeguatezza = CodiciPrometeia._JNEU1R3;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBGVEUML))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBGVEUML;
                    chiave.codiceMaf = CodiciPrometeia._OBGVEUML;
                    chiave.codiceAdeguatezza = CodiciPrometeia._JAGOV3E;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBGVIN))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBGVIN;
                    chiave.codiceMaf = CodiciPrometeia._OBGVIN;
                    chiave.codiceAdeguatezza = CodiciPrometeia._SBNMEUE;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBGLINLK))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBGLINLK;
                    chiave.codiceMaf = CodiciPrometeia._OBGLINLK;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MLGGILE;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBCPEU))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBCPEU;
                    chiave.codiceMaf = CodiciPrometeia._OBCPEU;
                    chiave.codiceAdeguatezza = CodiciPrometeia._IBCRPAL;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBCPNOEU))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBCPNOEU;
                    chiave.codiceMaf = CodiciPrometeia._OBCPNOEU;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MLGCORE;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBPSEM))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBPSEM;
                    chiave.codiceMaf = CodiciPrometeia._OBPSEM;
                    chiave.codiceAdeguatezza = CodiciPrometeia._JPMGCOC_USD;
                }
                else if (item.codice.Equals(CodiciPrometeia._OBGLHGYD))
                {

                    chiave.codiceIsin = CodiciPrometeia._OBGLHGYD;
                    chiave.codiceMaf = CodiciPrometeia._OBGLHGYD;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MLHGBCU;
                }
                else if (item.codice.Equals(CodiciPrometeia._AZEU))
                {

                    chiave.codiceIsin = CodiciPrometeia._AZEU;
                    chiave.codiceMaf = CodiciPrometeia._AZEU;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSEROP;
                }
                else if (item.codice.Equals(CodiciPrometeia._AZUSV))
                {

                    chiave.codiceIsin = CodiciPrometeia._AZUSV;
                    chiave.codiceMaf = CodiciPrometeia._AZUSV;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSNAMR;
                }
                else if (item.codice.Equals(CodiciPrometeia._AZJP))
                {

                    chiave.codiceIsin = CodiciPrometeia._AZJP;
                    chiave.codiceMaf = CodiciPrometeia._AZJP;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSJPAN;
                }
                else if (item.codice.Equals(CodiciPrometeia._AZPCEXJP))
                {
                    chiave.codiceIsin = CodiciPrometeia._AZPCEXJP;
                    chiave.codiceMaf = CodiciPrometeia._AZPCEXJP;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSPXJF;
                }
                else if (item.codice.Equals(CodiciPrometeia._AZEM))
                {

                    chiave.codiceIsin = CodiciPrometeia._AZEM;
                    chiave.codiceMaf = CodiciPrometeia._AZEM;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSEMKF;
                }
                else if (item.codice.Equals(CodiciPrometeia._AZ))
                {

                    chiave.codiceIsin = CodiciPrometeia._AZ;
                    chiave.codiceMaf = CodiciPrometeia._AZ;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSACWF;
                }
                else if (item.codice.Equals(CodiciPrometeia._OB))
                {

                    chiave.codiceIsin = CodiciPrometeia._OB;
                    chiave.codiceMaf = CodiciPrometeia._OB;
                    chiave.codiceAdeguatezza = CodiciPrometeia._SBWGEUE;
                }
                else if (item.codice.Equals(CodiciPrometeia._MN))
                {

                    chiave.codiceIsin = CodiciPrometeia._MN;
                    chiave.codiceMaf = CodiciPrometeia._MN;
                    chiave.codiceAdeguatezza = CodiciPrometeia._MSWRLD;
                }
                else
                {

                    chiave.codiceIsin = CodiciPrometeia._AL;
                    chiave.codiceMaf = CodiciPrometeia._AL;
                    chiave.codiceAdeguatezza = "";

                }

                strumento.risparmioAnnuo = 0.00;
                strumento.nome = item.codice;
                strumento.capitale = item.peso;
                strumento.valore = item.peso;

                strumento.chiave = chiave;

                if (strumento.chiave.codiceIsin.Trim() != "")
                {
                    strumenti2.Add(strumento);
                }
            }

            Aggregato aggregato;
            ptfType ptf;
            ptfType ptfGlobale = new ptfType();

            ptfGlobale.descrizione = descrizionePtf;

            foreach (strumentoType str in strumenti2)
            {
                aggregato = new Aggregato();
                ptf = new ptfType();
                saldoType saldo = new saldoType();
                saldo.chiave = str.chiave;
                saldo.valoreCtv = str.capitale;
                saldo.valoreCtvSpecified = true;
                saldo.valore = str.valore;
                ptf.AddSaldo(saldo);
                ptf.AddChildSaldoToAggregate();
                aggregato.Add(ptf);
                aggregato.AddCollectionAggregateToAggregate();
                ptf.AddChildToAggregate();
                ptfGlobale.AddAggregato(ptf);
                ptfGlobale.AddChildToAggregate();
            }
            #endregion


            richiestaVaRPortafoglioType richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            richiestaVarPortafoglio.Add(ptfGlobale);
            richiestaVarPortafoglio.AddChildToAggregate();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaPortafoglioModello", ex.InnerException);
        }
        return mt;

    }

    private static messaggioType CreaRichiestaPatrimonioComplessivo(DataTable dtPrometeia56, DataTable dtPrometeia23, DataTable dtContrattoSintesiPerCliente, DataTable dtCC)
    {
        messaggioType mtPatrimonioBF = null;
        messaggioType mtPatrimonioAltriIstituti = null;
        ptfType ptfTotalePatrimonioBF = null;
        ptfType ptfTotalePatrimonioAltriIstituti = null;
        messaggioType mt = new messaggioType();

        try
        {
            // Creo il ramo per patrimonio casa
            mtPatrimonioBF = CreaRichiestaVaRPortafoglioSezione56_BisCC(dtPrometeia56, dtContrattoSintesiPerCliente, dtCC);

            // Creo il ramo per patrimonio terzi
            mtPatrimonioAltriIstituti = CreaRichiestaVaRPortafoglioSezione23(dtPrometeia23, dtCC);

            // Creo il ramo per patrimonio complessivo
            ptfTotalePatrimonioBF = ((richiestaVaRPortafoglioType)((richiestaType)mtPatrimonioBF.bodyMessaggio.Item).Item).FindPtf("TOTALEPATRIMONIOBF");

            if (dtPrometeia23.Rows.Count > 0 || dtCC.Rows.Count > 0)
                ptfTotalePatrimonioAltriIstituti = ((richiestaVaRPortafoglioType)((richiestaType)mtPatrimonioAltriIstituti.bodyMessaggio.Item).Item).FindPtf("TOTALEALTRIISTITUTI");

            #region Variabili costruzione oggetto MessageType

            headerMessaggioType hdm;
            bodyMessaggioType bdm;
            richiestaType richiesta;
            richiestaVaRPortafoglioType richiestaVarPortafoglio;
            Aggregato aggregato;
            #endregion

            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEPATRIMONIOCOMPLESSIVO";

            aggregato = new Aggregato();

            aggregato.Add(ptfTotalePatrimonioBF);

            if (ptfTotalePatrimonioAltriIstituti != null)
                aggregato.Add(ptfTotalePatrimonioAltriIstituti);

            aggregato.AddCollectionAggregateToAggregate();
            ptfTotale.aggregato = aggregato.ArrayPtf;
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaPatrimonioComplessivo", ex.InnerException);
        }
        return mt;
    }

    public static DataTable GetContrattoSintesiPerCliente(PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente chiave, PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient info, int chiaveclientepb)
    {
        GlobalPositionWS gpWS = new GlobalPositionWS();
        DataTable dtGetContrattoSintesiPerCliente = gpWS.GetContrattoSintesiPerCliente(chiave, info, chiaveclientepb);
        return dtGetContrattoSintesiPerCliente;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chiave"></param>
    /// <param name="conto"></param>
    /// <param name="info"></param>
    /// <returns></returns>
    public static DataTable GetContrattoContoCorrenteSaldo(PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente chiave, string conto, PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient info)
    {
        GlobalPositionWS gpWS = new GlobalPositionWS();
        DataTable dtContrattoContoCorrenteSaldo = gpWS.GetContrattoContoCorrenteSaldo(chiave, conto, info);
        return dtContrattoContoCorrenteSaldo;
    }

    public static DataTable GetContrattoSintesiPerClienteCaricamentoAsul(PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente chiave, PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient info, int chiaveclientepb)
    {
        GlobalPositionWS gpWS = new GlobalPositionWS();
        DataTable dtGetContrattoSintesiPerCliente = gpWS.GetContrattoSintesiPerClienteCaricamentoAsul(chiave, info, chiaveclientepb);
        return dtGetContrattoSintesiPerCliente;
    }

    public static DataTable GetContrattoUnitLinkedSaldo(PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente chiave, string codiceContratto, PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient info, int chiaveclientepb)
    {
        GlobalPositionWS gpWS = new GlobalPositionWS();
        DataTable dtGetContrattoUnitLinkedSaldo = gpWS.GetContrattoUnitLinkedSaldo(chiave, codiceContratto, info, chiaveclientepb);

        return dtGetContrattoUnitLinkedSaldo;
    }

    public static List<string> GetIntestatari(PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente chiave, string codiceContratto, PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient info, int chiaveclientepb)
    {
        GlobalPositionWS gpWS = new GlobalPositionWS();
        return gpWS.GetIntestatari(chiave, codiceContratto, info, chiaveclientepb);
    }

    private static DataRow[] FindContrattoSintesiPerCliente(DataRow rwContrattiDb, DataTable dtContrattoSintesiPerCliente)
    {
        #region Dichiarazione variabili
        string contratto = "";
        string tipoProdotto = "";
        double ctv = 0;
        string codiceisin = "";
        string codicemaf = "";
        string codiceinterno = "";
        string codicesottoprodotto = "";
        string conto = "";
        string rubricato = "";
        string custodia_garanzia = "";
        string numero_polizza = "";
        string pctkey_termid = "";
        int pctkey_anno = 0;
        string pctkey_prog = "";
        string pctkey = "";
        #endregion


        #region Assegnazione Variabili Chiave position ID
        // contratto
        if (rwContrattiDb["CONTRATTO"] != DBNull.Value)
            contratto = ((string)rwContrattiDb["CONTRATTO"]).ToUpper().Trim();
        // TIpo Prodotto
        if (rwContrattiDb["TIPOPRODOTTO"] != DBNull.Value)
            tipoProdotto = ((string)rwContrattiDb["TIPOPRODOTTO"]).ToUpper().Trim();
        // Controvalre
        if (rwContrattiDb["Controvalore"] != DBNull.Value)
            ctv = Convert.ToDouble(rwContrattiDb["Controvalore"]);

        //codiceisin;
        if (rwContrattiDb["codiceisin"] != DBNull.Value)
            codiceisin = rwContrattiDb["codiceisin"].ToString();

        //codicemaf;
        if (rwContrattiDb["codicemaf"] != DBNull.Value)
            codicemaf = rwContrattiDb["codicemaf"].ToString();

        //codiceinterno;
        if (rwContrattiDb["codiceinterno"] != DBNull.Value)
            codiceinterno = rwContrattiDb["codiceinterno"].ToString();

        //codicesottoprodotto;
        if (rwContrattiDb["codicesottoprodotto"] != DBNull.Value)
            codicesottoprodotto = rwContrattiDb["codicesottoprodotto"].ToString();

        //conto;
        if (rwContrattiDb["conto"] != DBNull.Value)
            conto = rwContrattiDb["conto"].ToString();

        //rubricato
        if (rwContrattiDb["rubricato"] != DBNull.Value)
            rubricato = rwContrattiDb["rubricato"].ToString();

        //custodia_garanzia
        if (rwContrattiDb["custodia_garanzia"] != DBNull.Value)
            custodia_garanzia = rwContrattiDb["custodia_garanzia"].ToString();

        //numero_polizza
        if (rwContrattiDb["numero_polizza"] != DBNull.Value)
            numero_polizza = rwContrattiDb["numero_polizza"].ToString();

        #region Creazione della PCTKEY
        //pctkey_termid
        if (rwContrattiDb["pctkey_termid"] != DBNull.Value)
            pctkey_termid = rwContrattiDb["pctkey_termid"].ToString();

        //pctkey_anno
        if (rwContrattiDb["pctkey_termid"] != DBNull.Value)
            pctkey_anno = Convert.ToInt32(rwContrattiDb["pctkey_anno"]);


        //pctkey_prog
        if (rwContrattiDb["pctkey_prog"] != DBNull.Value)
            pctkey_prog = rwContrattiDb["pctkey_prog"].ToString();

        if (pctkey_termid != "" && pctkey_anno != 0 && pctkey_prog != "")
            pctkey = pctkey_termid + "/" + pctkey_anno.ToString() + "/" + pctkey_prog;
        else
            pctkey = "";

        #endregion
        #endregion

        #region Costruzione StringBuilder expression filter
        StringBuilder expression = new StringBuilder();

        //codiceMAF
        expression.Append("(codiceMAF like '");
        expression.Append(codicemaf);
        expression.Append("' ");

        if (codicemaf == "")
            expression.Append(" OR codiceMAF is null ");

        expression.Append(") AND ");

        //codiceInterno
        expression.Append("(codiceinterno like '");
        expression.Append(codiceinterno);
        expression.Append("' ");

        if (codiceinterno == "")
            expression.Append(" OR codiceinterno is null ");

        expression.Append(") AND ");


        //codicesottoProdotto
        expression.Append("(codicesottoProdotto like '");
        expression.Append(codicesottoprodotto);
        expression.Append("' ");

        if (codicesottoprodotto == "")
            expression.Append(" OR codicesottoProdotto is null ");

        expression.Append(") AND ");

        //codicesottoProdotto
        expression.Append("(codiceContratto like '");
        expression.Append(contratto);
        expression.Append("' ");

        if (contratto == "")
            expression.Append(" OR codiceContratto is null ");

        expression.Append(") AND ");

        //conto
        expression.Append("(conto like '");
        expression.Append(conto);
        expression.Append("' ");

        if (conto == "")
            expression.Append(" OR conto is null ");

        expression.Append(") AND ");


        //Rubricato
        expression.Append("(Rubricato like '");
        expression.Append(rubricato);
        expression.Append("' ");

        if (rubricato == "")
            expression.Append(" OR Rubricato is null ");

        expression.Append(") AND ");

        //CustodiaGaranzia
        expression.Append("(CustodiaGaranzia like '");
        expression.Append(custodia_garanzia);
        expression.Append("' ");

        if (custodia_garanzia == "")
            expression.Append(" OR CustodiaGaranzia is null ");

        expression.Append(") AND ");

        //numeroPolizza
        expression.Append("(numeroPolizza like '");
        expression.Append(numero_polizza);
        expression.Append("' ");

        if (numero_polizza == "")
            expression.Append(" OR numeroPolizza is null ");

        expression.Append(") AND ");


        //pctKey
        expression.Append("(pctKey like '");
        expression.Append(pctkey);
        expression.Append("' ");

        if (pctkey == "")
            expression.Append(" OR pctKey is null ");

        expression.Append(")  ");
        #endregion

        DataRow[] drArray = dtContrattoSintesiPerCliente.Select(expression.ToString());

        return drArray;

    }

    private static List<DataViewSezione21> MakeDataSetSezione21(DataTable dtDistinctNeedArea, DataTable dtRichiesta)
    {
        List<DataViewSezione21> ListDataView = new List<DataViewSezione21>();
        DataViewSezione21 view;

        foreach (DataRow rwdistinct in dtDistinctNeedArea.Rows)
        {
            view = new DataViewSezione21();

            view.Table = dtRichiesta.Copy();
            view.RowFilter = "NEEDAREA like '" + rwdistinct["NEEDAREA"].ToString().Trim().ToUpper() + "'";
            //view.Sort = "CompanyName DESC";
            view.Descrizione = rwdistinct["NEEDAREA"].ToString().Trim().ToUpper();
            ListDataView.Add(view);

        }

        return ListDataView;

    }

    private static void CreaAggregatoSezione21(ptfType ptf, string rwAsulString, string tipoProdottoAsul, DataRowView rw, int chiaveclientepb)
    {
        Aggregato aggregatoAsul;
        ptfType ptfAsul;
        saldoType saldo;
        ProdottiKeyType pkt;
        Aggregato aggregatoNonAsul;
        ptfType ptfNonAsul;


        if (rwAsulString.Equals(tipoProdottoAsul))
        {
            #region SALDO ASUL
            aggregatoAsul = new Aggregato();
            ptfAsul = new ptfType();

            ptfAsul.descrizione = rw["CHIAVEPOSIZIONE"] == DBNull.Value ? "0" : rw["CHIAVEPOSIZIONE"].ToString();

            //if (rw["CONTRATTO"].ToString() != "")
            //    ptfAsul.descrizione = rw["CONTRATTO"].ToString();

            //ptfAsul.descrizione += "|";

            //if (rw["CODICEISIN"].ToString() != "")
            //    ptfAsul.descrizione += rw["CODICEISIN"].ToString();
            //else
            //    if (rw["CODICEADEGUATEZZA"].ToString() != "")
            //        ptfAsul.descrizione += rw["CODICEADEGUATEZZA"].ToString();
            //    else
            //        if (rw["CODICEMAF"].ToString() != "")
            //            ptfAsul.descrizione += rw["CODICEMAF"].ToString();



            #region Chiamata la WSGLOBALPOSITION
            PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
            _chiaveCliente.codiceAgente = codiceAgente;
            _chiaveCliente.codicefiscale = codiceFiscale;
            _chiaveCliente.codiceRete = codiceRete;
            _chiaveCliente.potenzialeClienteNAC = true;

            PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
            _infoCliente.codiceApplicazione = codiceApplicazione;
            _infoCliente.codiceRete = codiceRete;
            _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;
            string codiceContratto = rw["CONTRATTO"].ToString().Trim();

            GlobalPositionWS gpWS = new GlobalPositionWS();

            DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);
            #endregion

            foreach (DataRow rwAsul in dtAsul.Rows)
            {
                saldo = new saldoType();
                //if (rw["VALORE"] != DBNull.Value)
                //    saldo.valore = Convert.ToDouble(rw["VALORE"].ToString());

                //if (rw["VALORESINTESI"] == DBNull.Value || (double)rw["VALORESINTESI"] == 0)
                //    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                //else
                //    saldo.valore = Convert.ToDouble(rw["VALORESINTESI"].ToString());


                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                {
                    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                    saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                }
                saldo.valoreCtvSpecified = true;

                pkt = new ProdottiKeyType();

                //CODICEADEGUATEZZA
                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                    pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                else
                    pkt.codiceAdeguatezza = "";

                //CODICESOTTOPRODOTTO
                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                    pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                else
                    pkt.codiceSottoprodotto = "";
                //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                //if (rw["CODICEISIN"] != DBNull.Value)
                //    pkt.codiceIsin = rw["CODICEISIN"].ToString();

                //if (rw["CODICEMAF"] != DBNull.Value)
                //    pkt.codiceMaf = rw["CODICEMAF"].ToString();


                saldo.chiave = pkt;
                ptfAsul.AddSaldo(saldo);
            }
            ptfAsul.AddChildSaldoToAggregate();
            aggregatoAsul.Add(ptfAsul);
            aggregatoAsul.AddCollectionAggregateToAggregate();
            ptfAsul.AddChildToAggregate();
            ptf.AddAggregato(ptfAsul);

            ptf.AddChildToAggregate();

            #endregion
        }
        else
        {
            aggregatoNonAsul = new Aggregato();
            ptfNonAsul = new ptfType();

            ptfNonAsul.descrizione = rw["CHIAVEPOSIZIONE"] == DBNull.Value ? "0" : rw["CHIAVEPOSIZIONE"].ToString();

            //if (rw["CONTRATTO"].ToString() != "")
            //    ptfNonAsul.descrizione = rw["CONTRATTO"].ToString();

            //ptfNonAsul.descrizione += "|";

            //if (rw["CODICEISIN"].ToString() != "")
            //    ptfNonAsul.descrizione += rw["CODICEISIN"].ToString();
            //else
            //    if (rw["CODICEADEGUATEZZA"].ToString() != "")
            //        ptfNonAsul.descrizione += rw["CODICEADEGUATEZZA"].ToString();
            //    else
            //        if (rw["CODICEMAF"].ToString() != "")
            //            ptfNonAsul.descrizione += rw["CODICEMAF"].ToString();

            #region SALDO NON ASUL
            saldo = new saldoType();
            //if (rw["VALORE"] != DBNull.Value)
            //    saldo.valore = Convert.ToDouble(rw["VALORE"].ToString());

            if (rw["VALORESINTESI"] == DBNull.Value || (double)rw["VALORESINTESI"] == 0)
                saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
            else
                saldo.valore = Convert.ToDouble(rw["VALORESINTESI"].ToString());


            if (rw["CONTROVALORE"] != DBNull.Value)
                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());

            saldo.valoreCtvSpecified = true;

            pkt = new ProdottiKeyType();

            if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
            else
                pkt.codiceAdeguatezza = "";

            if (rw["CODICEINTERNO"] != DBNull.Value)
                pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
            else
                pkt.codiceInterno = "";

            if (rw["CODICEISIN"] != DBNull.Value)
                pkt.codiceIsin = rw["CODICEISIN"].ToString();
            else
                pkt.codiceIsin = "";

            if (rw["CODICEMAF"] != DBNull.Value)
                pkt.codiceMaf = rw["CODICEMAF"].ToString();
            else
                pkt.codiceMaf = "";

            saldo.chiave = pkt;
            ptfNonAsul.AddSaldo(saldo);
            ptfNonAsul.AddChildSaldoToAggregate();
            aggregatoNonAsul.Add(ptfNonAsul);
            aggregatoNonAsul.AddCollectionAggregateToAggregate();
            ptfNonAsul.AddChildToAggregate();
            ptf.AddAggregato(ptfNonAsul);

            ptf.AddChildToAggregate();
            #endregion
        }
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezione19(DataTable dt)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaPTFModelloType richiestaPortafoglioModello;
        parametriPTFModelloType parametriPTFModello;

        #endregion
        try
        {

            #region

            List<strumentoType> strumenti2 = new List<strumentoType>();

            foreach (DataRow rw in dt.Rows)
            {
                strumentoType strumento = new strumentoType();
                ProdottiKeyType chiave = new ProdottiKeyType();


                chiave.codiceIsin = rw["codiceisin"].ToString();
                chiave.codiceMaf = rw["codicemaf"].ToString();
                chiave.codiceAdeguatezza = rw["codiceadeguatezza"].ToString();


                strumento.risparmioAnnuo = 0.00;
                strumento.nome = rw["assetname"].ToString();

                strumento.capitale = Convert.ToDouble(rw["peso"]);
                strumento.valore = Convert.ToDouble(rw["peso"]);

                strumento.chiave = chiave;

                if (strumento.chiave.codiceIsin.Trim() != "")
                {
                    strumenti2.Add(strumento);
                }
            }
            #endregion
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();

            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVaRPortafoglioType richiestaPatrimonioFinanziario = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaPatrimonioFinanziario;
            richiestaPatrimonioFinanziario.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaPatrimonioFinanziario.alphaSpecified = true;
            // hp - ST
            richiestaPatrimonioFinanziario.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaPatrimonioFinanziario.hpSpecified = true;

            Aggregato aggregato;
            ptfType ptf;
            ptfType ptfGlobale = new ptfType();

            ptfGlobale.descrizione = "RISCHIOPATRIMONIOFINANZIARIO";

            foreach (strumentoType str in strumenti2)
            {
                aggregato = new Aggregato();
                ptf = new ptfType();
                ptf.descrizione = str.nome;
                saldoType saldo = new saldoType();
                saldo.chiave = str.chiave;
                saldo.valoreCtv = str.capitale;
                saldo.valoreCtvSpecified = true;
                saldo.valore = str.valore;
                ptf.AddSaldo(saldo);
                ptf.AddChildSaldoToAggregate();
                aggregato.Add(ptf);
                aggregato.AddCollectionAggregateToAggregate();
                ptf.AddChildToAggregate();
                ptfGlobale.AddAggregato(ptf);
                ptfGlobale.AddChildToAggregate();
            }
            #endregion

            richiestaPatrimonioFinanziario.Add(ptfGlobale);
            richiestaPatrimonioFinanziario.AddChildToAggregate();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Classe: Prometeia; Metodo: CreaRichiestaVaRPortafoglioSezione19", ex.InnerException);
        }
        return mt;

    }

    private static void AggiungiColonnaTipoProdottoContrattoSintesi(ref DataTable dt, DataTable dtContrattoSintesi)
    {

        if (!dt.Columns.Contains("TIPOPRODOTTOSINTESI"))
        {
            DataColumn colTipoProdottoContrattoSintesi = new DataColumn("TIPOPRODOTTOSINTESI", typeof(string));
            dt.Columns.Add(colTipoProdottoContrattoSintesi);

            DataColumn colValoreContrattoSintesi = new DataColumn("VALORESINTESI", typeof(double));
            dt.Columns.Add(colValoreContrattoSintesi);

            DataColumn colCTVContrattoSintesi = new DataColumn("CTVSINTESI", typeof(double));
            dt.Columns.Add(colCTVContrattoSintesi);

            DataColumn colDataSottoscrizioneContrattoSintesi = new DataColumn("DATASOTTOSCRIZIONESINTESI", typeof(string));
            dt.Columns.Add(colDataSottoscrizioneContrattoSintesi);

            DataColumn colPerformanceYTD = new DataColumn("PERFORMANCEYTDSINTESI", typeof(double));
            dt.Columns.Add(colPerformanceYTD);

            DataColumn colPerformanceDS = new DataColumn("PERFORMANCEDSSINTESI", typeof(double));
            dt.Columns.Add(colPerformanceDS);

            //K Skandia
            DataColumn colIsinDaCS = new DataColumn("ISIN_ASU2", typeof(string));
            dt.Columns.Add(colIsinDaCS);
        }

        StringBuilder expression = new StringBuilder();


        if (dtContrattoSintesi != null)
        {
            foreach (DataRow rw in dtContrattoSintesi.Rows)
            {

                // codice contratto
                expression.Append("(contratto like '");
                expression.Append(rw["codiceContratto"].ToString());
                expression.Append("%') and ");


                // rw riga contenente i contratti
                switch (rw["TIPOPRODOTTO"].ToString())
                {
                    case "FI":
                    case "GE":
                    case "GP":
                    case "ASUL":
                    case "ASU1":
                    case "ASU2":  //K Skandia
                    case "ASU3":
                    case "ASVI":
                    case "ASCM":
                    case "CC":
                        // Da confrontare: codice_Interno, codice_SottoProdotto
                        // codice interno
                        expression.Append("(CodiceInterno like '");
                        expression.Append(rw["codiceInterno"].ToString());
                        expression.Append("' ");

                        if (rw["codiceInterno"].ToString() == "")
                            expression.Append(" OR CodiceInterno is null ");

                        expression.Append(") AND ");

                        // codice_SottoProdotto
                        expression.Append("(codicesottoprodotto like '");
                        expression.Append(rw["codicesottoProdotto"].ToString());
                        expression.Append("' ");

                        if (rw["codicesottoProdotto"].ToString() == "")
                            expression.Append(" OR codicesottoprodotto is null ) ");
                        else
                            expression.Append(" ) ");

                        //K Skandia e GP Eligo
                        if (rw["TIPOPRODOTTO"].ToString() == "ASU2" || rw["TIPOPRODOTTO"].ToString() == "ASU3" || rw["TIPOPRODOTTO"].ToString() == "GP")
                        {
                            //Qualora l'ISIN da WS non fosse valorizzato il filtro che si sta creando non risulterebbe efficace 
                            //determinando un'estrazione di n a 1, a cascata la chiamata a Prometeia sarebbe disastrosamente sbagliata
                            //Quindi provvedo ad inchiodare tutto solevando un'eccezione.
                            if (rw["ISIN"] == DBNull.Value || rw["ISIN"].ToString().Trim() == "")
                            {
                                string msg = "Errore da GlobalPosition : ISIN non valorizzato per prodotto skandia, impossibile eseguire il match con le info del DB."
                                    + "\n Info da WS : "
                                    + "\n CodInterno=" + rw["codiceInterno"].ToString()
                                    + "\n CodSottoprodotto=" + rw["codicesottoProdotto"].ToString()
                                    + "\n CTV=" + rw["CTV"].ToString();
                                throw new Exception(msg);
                            }

                            expression.Append(" AND codiceisin = '").Append(rw["ISIN"].ToString()).Append("'");
                        }
                        break;


                    case "DT":
                        // codice interno
                        expression.Append("(CodiceInterno like '");
                        expression.Append(rw["codiceInterno"].ToString());
                        expression.Append("%' ");

                        if (rw["codiceInterno"].ToString() == "")
                            expression.Append(" OR CodiceInterno is null ");

                        expression.Append(") AND ");


                        // conto
                        expression.Append("(conto like '");
                        expression.Append(rw["conto"].ToString());
                        expression.Append("%' ");
                        if (rw["conto"].ToString() == "")
                            expression.Append(" OR conto is null ");

                        expression.Append(") AND ");



                        // rubricato
                        expression.Append("(rubricato like '");
                        expression.Append(rw["rubricato"].ToString());
                        expression.Append("%' ");
                        if (rw["rubricato"].ToString() == "")
                            expression.Append(" OR rubricato is null ");

                        expression.Append(")");


                        //// codice_SottoProdotto
                        //if (dt.Columns.Contains("controvalore_attuale"))
                        //    expression.Append("(controvalore_attuale = ");
                        //else
                        //    expression.Append("(Controvalore = ");

                        //expression.Append(rw["ctv"].ToString().Replace(",", "."));
                        ////expression.Append("D' ");

                        //if (rw["ctv"].ToString() == "")
                        //    expression.Append(" OR Controvalore is null ) ");
                        //else
                        //    expression.Append(" ) ");

                        break;

                    case "ASD":
                        //codiceInterno
                        // codice interno
                        expression.Append("(CodiceInterno like '");
                        expression.Append(rw["codiceInterno"].ToString());
                        expression.Append("' ");

                        if (rw["codiceInterno"].ToString() == "")
                            expression.Append(" OR CodiceInterno is null) ");
                        else
                            expression.Append(" ) ");

                        break;


                    case "GES":

                        //codiceMAF
                        expression.Append("(codicemaf like '");
                        expression.Append(rw["codiceMaf"].ToString());
                        expression.Append("' ");

                        if (rw["codiceMaf"].ToString() == "")
                            expression.Append(" OR codicemaf is null ");

                        expression.Append(") AND ");

                        // codice interno
                        expression.Append("(CodiceInterno like '");
                        expression.Append(rw["codiceInterno"].ToString());
                        expression.Append("' ");

                        if (rw["codiceInterno"].ToString() == "")
                            expression.Append(" OR CodiceInterno is null ) ");
                        else
                            expression.Append(" ) ");
                        break;

                }

                DataRow[] drArray = dt.Select(expression.ToString());

                if (drArray.Length > 0)
                {

                    foreach (DataRow riga in drArray)
                    {
                        riga["TIPOPRODOTTOSINTESI"] = rw["TIPOPRODOTTO"];
                        riga["VALORESINTESI"] = rw["VALORE"];
                        riga["CTVSINTESI"] = rw["CTV"];
                        riga["DATASOTTOSCRIZIONESINTESI"] = rw["DataDiSottoscrizione"];
                        riga["PERFORMANCEYTDSINTESI"] = rw["RendimentoDaInizioAnno"];
                        riga["PERFORMANCEDSSINTESI"] = rw["RendimentoDaSottoscrizione"];
                        //K Skandia
                        /*  riga["ISIN"] = rw["ISIN"];  */
                        riga["ISIN_ASU2"] = rw["ISIN"];
                    }
                }
                expression.Length = 0;
            }
        }
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS48PerTipoProdotto(DataTable dtRichiesta)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        DataTable dtDistincttipoprodotto;
        DataTable dtDistinctprodotto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfTipoProdotto;
        ptfType ptfProdotto;
        saldoType saldo;
        ProdottiKeyType pkt;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumntipoprodotto = new string[1];
            paramColumntipoprodotto[0] = "DESCR_GRUPPO";
            dtDistincttipoprodotto = dtRichiesta.DefaultView.ToTable(true, paramColumntipoprodotto);

            string[] paramColumnprodotto = new string[4];
            paramColumnprodotto[0] = "DESCR_GRUPPO";
            paramColumnprodotto[1] = "NOMEPRODOTTO";
            paramColumnprodotto[2] = "ASSETID";
            paramColumnprodotto[3] = "Prod_non_in_catalogo";

            dtDistinctprodotto = dtRichiesta.DefaultView.ToTable(true, paramColumnprodotto);

            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string rwdistincttipoprodotto = "";
            string rwdistinctprodottotiporpodotto = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;
            decimal controvalore = 0;
            bool prodottononincatalogo;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEPRODOTTIALTRIISTITUTI";

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rwdistinct in dtDistincttipoprodotto.Rows)
            {
                // Creo un aggregato
                ptfTipoProdotto = new ptfType();
                ptfTipoProdotto.descrizione = rwdistinct["DESCR_GRUPPO"].ToString();

                rwdistincttipoprodotto = rwdistinct["DESCR_GRUPPO"].ToString().Trim().ToUpper();

                foreach (DataRow rwdistinctprodotto in dtDistinctprodotto.Rows)
                {
                    rwdistinctprodottotiporpodotto = rwdistinctprodotto["DESCR_GRUPPO"].ToString().Trim().ToUpper();
                    prodottononincatalogo = Convert.ToBoolean(rwdistinctprodotto["Prod_non_in_catalogo"]);

                    if (rwdistincttipoprodotto.Equals(rwdistinctprodottotiporpodotto))
                    {
                        #region Aggregato di Prodotto
                        ptfProdotto = new ptfType();
                        #endregion

                        if (!prodottononincatalogo)
                        {
                            #region Prodotti in catalogo
                            string strComputeSelect = "";
                            strComputeSelect += " ASSETID = '" + rwdistinctprodotto["ASSETID"].ToString().Replace("'", "''") + "'";
                            strComputeSelect += " and NOMEPRODOTTO = '" + rwdistinctprodotto["NOMEPRODOTTO"].ToString().Replace("'", "''") + "'";
                            strComputeSelect += " and DESCR_GRUPPO = '" + rwdistinctprodotto["DESCR_GRUPPO"].ToString().Replace("'", "''") + "'";

                            //  object SumControvalore = dtRichiesta.Compute("Sum(CONTROVALORE)", " assetid = '" + rwdistinctprodotto["assetid"].ToString().Replace("'", "''") + "' and CODICEISIN = '" + rwdistinctprodotto["CODICEISIN"].ToString().Replace("'", "''") + "'");

                            object SumControvalore = dtRichiesta.Compute("Sum(CONTROVALORE)", strComputeSelect);

                            //   DataRow[] rwProdottiArray = dtRichiesta.Select(" assetid = '" + rwdistinctprodotto["assetid"].ToString().Replace("'", "''") + "' and CODICEISIN = '" + rwdistinctprodotto["CODICEISIN"].ToString().Replace("'", "''") + "'");
                            DataRow[] rwProdottiArray = dtRichiesta.Select(strComputeSelect);

                            string codAdeguatzza = "";


                            if (rwProdottiArray != null && rwProdottiArray.Length > 0 && rwProdottiArray[0]["CODICEADEGUATEZZA"] != DBNull.Value)
                                codAdeguatzza = rwProdottiArray[0]["CODICEADEGUATEZZA"].ToString();

                            if (codAdeguatzza != "")
                            {
                                #region Codice Adeguatezza Valorizzato
                                #region Ciclo datarow
                                //foreach (DataRow rw in dtRichiesta.Rows)
                                //{
                                //    if (rwdistinctprodotto["DESCR_GRUPPO"].ToString() == rw["DESCR_GRUPPO"].ToString() &&
                                //        rwdistinctprodotto["NOMEPRODOTTO"].ToString() == rw["NOMEPRODOTTO"].ToString() &&
                                //        rwdistinctprodotto["ASSETID"].ToString() == rw["ASSETID"].ToString())
                                //    {

                                #region SALDO NON ASUL

                                string codIsin = "";
                                string codMaf = "";
                                string codSottoProdotto = "";
                                string codInterno = "";


                                foreach (DataRow _rw in rwProdottiArray)
                                {
                                    ptfProdotto.descrizione += _rw["ID"].ToString() + "|";
                                    if (_rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                        codAdeguatzza = _rw["CODICEADEGUATEZZA"].ToString();
                                    if (_rw["CODICEISIN"] != DBNull.Value)
                                        codIsin = _rw["CODICEISIN"].ToString();
                                    if (_rw["CODICEMAF"] != DBNull.Value)
                                        codMaf = _rw["CODICEMAF"].ToString();
                                    if (_rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                        codSottoProdotto = _rw["CODICESOTTOPRODOTTO"].ToString();
                                    if (_rw["CODICEINTERNO"] != DBNull.Value)
                                        codInterno = _rw["CODICEINTERNO"].ToString();

                                }

                                saldo = new saldoType();

                                if (SumControvalore == DBNull.Value)
                                {
                                    saldo.valore = 0;
                                    saldo.valoreCtv = 0;

                                }
                                else
                                {
                                    saldo.valore = Convert.ToDouble(SumControvalore);
                                    saldo.valoreCtv = Convert.ToDouble(SumControvalore);
                                }


                                saldo.valoreCtvSpecified = true;

                                pkt = new ProdottiKeyType();

                                if (codAdeguatzza != "")
                                    pkt.codiceAdeguatezza = codAdeguatzza;
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (codIsin != "")
                                    pkt.codiceIsin = codIsin;
                                else
                                    pkt.codiceIsin = "";

                                if (codMaf != "")
                                    pkt.codiceMaf = codMaf;
                                else
                                    pkt.codiceMaf = "";

                                if (codSottoProdotto != "")
                                    pkt.codiceSottoprodotto = codSottoProdotto;
                                else
                                    pkt.codiceSottoprodotto = "";

                                if (codInterno != "")
                                    pkt.codiceInterno = codInterno;
                                else
                                    pkt.codiceInterno = "";



                                saldo.chiave = pkt;
                                ptfProdotto.AddSaldo(saldo);


                                #endregion
                                //    }
                                //}
                                #endregion
                                #endregion
                            }
                            else
                            {
                                #region Codice Adeguatezza Non Valorizzato

                                #region Ciclo datarow
                                foreach (DataRow rw in dtRichiesta.Rows)
                                {
                                    if (rwdistinctprodotto["DESCR_GRUPPO"].ToString() == rw["DESCR_GRUPPO"].ToString() &&
                                        rwdistinctprodotto["NOMEPRODOTTO"].ToString() == rw["NOMEPRODOTTO"].ToString() &&
                                        rwdistinctprodotto["ASSETID"].ToString() == rw["ASSETID"].ToString())
                                    {

                                        ptfProdotto.descrizione += rw["ID"].ToString() + "|";

                                        #region SALDO NON ASUL
                                        saldo = new saldoType();
                                        if (rw["CONTROVALORE"] != DBNull.Value)
                                        {
                                            saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                            saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                        }

                                        saldo.valoreCtvSpecified = true;

                                        pkt = new ProdottiKeyType();

                                        if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                            pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                        else
                                            pkt.codiceAdeguatezza = "";

                                        if (rw["CODICEISIN"] != DBNull.Value)
                                            pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                        else
                                            pkt.codiceIsin = "";

                                        if (rw["CODICEMAF"] != DBNull.Value)
                                            pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                        else
                                            pkt.codiceMaf = "";

                                        if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                            pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                                        else
                                            pkt.codiceSottoprodotto = "";

                                        if (rw["CODICEINTERNO"] != DBNull.Value)
                                            pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                        else
                                            pkt.codiceInterno = "";


                                        saldo.chiave = pkt;
                                        ptfProdotto.AddSaldo(saldo);


                                        #endregion
                                    }
                                }
                                #endregion
                                #endregion
                            }

                            #endregion
                        }
                        else
                        {
                            #region Prodotti non in catalogo
                            #region Ciclo datarow
                            foreach (DataRow rw in dtRichiesta.Rows)
                            {
                                if (rwdistinctprodotto["DESCR_GRUPPO"].ToString() == rw["DESCR_GRUPPO"].ToString() &&
                                    rwdistinctprodotto["NOMEPRODOTTO"].ToString() == rw["NOMEPRODOTTO"].ToString() &&
                                    rwdistinctprodotto["ASSETID"].ToString() == rw["ASSETID"].ToString())
                                {

                                    ptfProdotto.descrizione += rw["ID"].ToString() + "|";

                                    #region SALDO NON ASUL
                                    saldo = new saldoType();
                                    if (rw["CONTROVALORE"] != DBNull.Value)
                                    {
                                        saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                        saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                    }

                                    saldo.valoreCtvSpecified = true;

                                    pkt = new ProdottiKeyType();

                                    if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                        pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                    else
                                        pkt.codiceAdeguatezza = "";

                                    if (rw["CODICEISIN"] != DBNull.Value)
                                        pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                    else
                                        pkt.codiceIsin = "";

                                    if (rw["CODICEMAF"] != DBNull.Value)
                                        pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                    else
                                        pkt.codiceMaf = "";

                                    if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                        pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                                    else
                                        pkt.codiceSottoprodotto = "";

                                    if (rw["CODICEINTERNO"] != DBNull.Value)
                                        pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                    else
                                        pkt.codiceInterno = "";


                                    saldo.chiave = pkt;
                                    ptfProdotto.AddSaldo(saldo);


                                    #endregion
                                }
                            }
                            #endregion
                            #endregion
                        }

                        if (ptfProdotto.descrizione != "" && ptfProdotto.descrizione != null)
                        {
                            ptfProdotto.AddChildSaldoToAggregate();

                            ptfTipoProdotto.AddAggregato(ptfProdotto);
                        }
                    }
                }
                ptfTipoProdotto.AddChildToAggregate();
                ptfTotale.AddAggregato(ptfTipoProdotto);
            }

            ptfTotale.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS48PerTipoProdotto", ex.InnerException);
        }
        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS48PerIntermediario(DataTable dtRichiesta)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        DataTable dtDistinctintermediario;
        DataTable dtDistinctprodotto;
        DataTable dtDistinctintermediarioTipoProdotto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfIntermediario = null;
        ptfType ptfProdotto;
        ptfType ptfTipoProdotto;
        saldoType saldo;
        ProdottiKeyType pkt;
        Aggregato aggregatoIntermediario;
        Aggregato aggregatoProdotto;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumnIntermediario = new string[1];
            paramColumnIntermediario[0] = "NOMEBANCATERZA";
            dtDistinctintermediario = dtRichiesta.DefaultView.ToTable(true, paramColumnIntermediario);

            string[] paramColumntipoprodottointermediario = new string[2];
            paramColumntipoprodottointermediario[0] = "DESCR_GRUPPO";
            paramColumntipoprodottointermediario[1] = "NOMEBANCATERZA";

            dtDistinctintermediarioTipoProdotto = dtRichiesta.DefaultView.ToTable(true, paramColumntipoprodottointermediario);

            // Filtro per Intermediario: NOMEBANCATERZA e per prodotto: NOMEPRODOTTO

            string[] paramColumnprodotto = new string[5];
            paramColumnprodotto[0] = "NOMEBANCATERZA";
            paramColumnprodotto[1] = "DESCR_GRUPPO";
            paramColumnprodotto[2] = "NOMEPRODOTTO";
            paramColumnprodotto[3] = "ASSETID";
            paramColumnprodotto[4] = "Prod_non_in_catalogo";


            dtDistinctprodotto = dtRichiesta.DefaultView.ToTable(true, paramColumnprodotto);

            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string Intermediario = "";
            string TipoProdotto_Intermediario = "";
            string TipoProdotto_TipoProdotto = "";
            string Prodotto_TipoProdotto = "";
            string Prodotto_Prodotto = "";
            string Prodotto_Assetid = "";
            string Prodotto_Intermediario = "";
            string rwintermediario = "";
            string prodotto = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;
            bool prodottononincatalogo = false;


            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEINTERMEDIARIALTRIISTITUTI";

            #region CREAZIONE OGGETTO MESSAGE
            // Distinct Intermediaio
            foreach (DataRow rwdistinct in dtDistinctintermediario.Rows)
            {
                // Creo un aggregato
                ptfIntermediario = new ptfType();
                ptfIntermediario.descrizione = rwdistinct["NOMEBANCATERZA"].ToString();

                Intermediario = rwdistinct["NOMEBANCATERZA"].ToString().Trim().ToUpper();
                // Distinct Tipo Prodotto
                foreach (DataRow rwdistincttipoprodottointermediario in dtDistinctintermediarioTipoProdotto.Rows)
                {

                    TipoProdotto_Intermediario = rwdistincttipoprodottointermediario["NOMEBANCATERZA"].ToString().Trim().ToUpper();
                    TipoProdotto_TipoProdotto = rwdistincttipoprodottointermediario["DESCR_GRUPPO"].ToString().Trim().ToUpper();

                    if (Intermediario.Equals(TipoProdotto_Intermediario))
                    {
                        ptfTipoProdotto = new ptfType();
                        ptfTipoProdotto.descrizione = rwdistincttipoprodottointermediario["DESCR_GRUPPO"].ToString().Trim().ToUpper();

                        // Distinct Prodotto
                        #region Aggreagato PTF Prodotto
                        foreach (DataRow rwdistinctprodotto in dtDistinctprodotto.Rows)
                        {
                            Prodotto_TipoProdotto = rwdistinctprodotto["DESCR_GRUPPO"].ToString().Trim().ToUpper();
                            Prodotto_Intermediario = rwdistinctprodotto["NOMEBANCATERZA"].ToString().Trim().ToUpper();
                            Prodotto_Prodotto = rwdistinctprodotto["NOMEPRODOTTO"].ToString().Trim().ToUpper();
                            Prodotto_Assetid = rwdistinctprodotto["ASSETID"].ToString().Trim().ToUpper();
                            prodottononincatalogo = Convert.ToBoolean(rwdistinctprodotto["Prod_non_in_catalogo"]);

                            if (TipoProdotto_TipoProdotto == Prodotto_TipoProdotto && Prodotto_Intermediario == Intermediario)
                            {
                                #region Aggregato di Prodotto
                                ptfProdotto = new ptfType();
                                #endregion

                                if (!prodottononincatalogo)
                                {
                                    string strComputeSelect = "";
                                    strComputeSelect += " NOMEBANCATERZA = '" + rwdistinctprodotto["NOMEBANCATERZA"].ToString().Replace("'", "''") + "'";
                                    strComputeSelect += " and ASSETID = '" + rwdistinctprodotto["ASSETID"].ToString().Replace("'", "''") + "'";
                                    strComputeSelect += " and NOMEPRODOTTO = '" + rwdistinctprodotto["NOMEPRODOTTO"].ToString().Replace("'", "''") + "'";
                                    strComputeSelect += " and DESCR_GRUPPO = '" + rwdistinctprodotto["DESCR_GRUPPO"].ToString().Replace("'", "''") + "'";

                                    //  object SumControvalore = dtRichiesta.Compute("Sum(CONTROVALORE)", " assetid = '" + rwdistinctprodotto["assetid"].ToString().Replace("'", "''") + "' and CODICEISIN = '" + rwdistinctprodotto["CODICEISIN"].ToString().Replace("'", "''") + "'");

                                    object SumControvalore = dtRichiesta.Compute("Sum(CONTROVALORE)", strComputeSelect);

                                    //   DataRow[] rwProdottiArray = dtRichiesta.Select(" assetid = '" + rwdistinctprodotto["assetid"].ToString().Replace("'", "''") + "' and CODICEISIN = '" + rwdistinctprodotto["CODICEISIN"].ToString().Replace("'", "''") + "'");
                                    DataRow[] rwProdottiArray = dtRichiesta.Select(strComputeSelect);

                                    #region Prodotti in catalogo

                                    string codAdeguatzza = "";

                                    if (rwProdottiArray != null && rwProdottiArray.Length > 0 && rwProdottiArray[0]["CODICEADEGUATEZZA"] != DBNull.Value)
                                        codAdeguatzza = rwProdottiArray[0]["CODICEADEGUATEZZA"].ToString();

                                    if (codAdeguatzza != "")
                                    {
                                        #region Codice Adeguatezza Valorizzato
                                        #region Ciclo DataRow
                                        //foreach (DataRow rw in dtRichiesta.Rows)
                                        //{
                                        //    if (Intermediario == rw["NOMEBANCATERZA"].ToString().Trim().ToUpper() &&
                                        //        TipoProdotto_TipoProdotto == rw["DESCR_GRUPPO"].ToString().Trim().ToUpper() &&
                                        //        Prodotto_Prodotto == rw["NOMEPRODOTTO"].ToString().Trim().ToUpper() &&
                                        //        Prodotto_Assetid == rw["ASSETID"].ToString().Trim().ToUpper())
                                        //    {


                                        string codIsin = "";
                                        string codMaf = "";
                                        string codSottoProdotto = "";
                                        string codInterno = "";

                                        foreach (DataRow _rw in rwProdottiArray)
                                        {
                                            ptfProdotto.descrizione += _rw["ID"].ToString() + "|"; //+"_" + rw["DESCR_GRUPPO"].ToString() + "_" + rw["NOMEBANCATERZA"].ToString() + "|";

                                            if (_rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                                codAdeguatzza = _rw["CODICEADEGUATEZZA"].ToString();
                                            if (_rw["CODICEISIN"] != DBNull.Value)
                                                codIsin = _rw["CODICEISIN"].ToString();
                                            if (_rw["CODICEMAF"] != DBNull.Value)
                                                codMaf = _rw["CODICEMAF"].ToString();
                                            if (_rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                                codSottoProdotto = _rw["CODICESOTTOPRODOTTO"].ToString();
                                            if (_rw["CODICEINTERNO"] != DBNull.Value)
                                                codInterno = _rw["CODICEINTERNO"].ToString();
                                        }
                                        #region SALDO NON ASUL
                                        saldo = new saldoType();

                                        if (SumControvalore == DBNull.Value)
                                        {
                                            saldo.valore = 0;
                                            saldo.valoreCtv = 0;
                                        }
                                        else
                                        {
                                            saldo.valore = Convert.ToDouble(SumControvalore);
                                            saldo.valoreCtv = Convert.ToDouble(SumControvalore);
                                        }
                                        //if (rw["CONTROVALORE"] != DBNull.Value)
                                        //{
                                        //    saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                        //    saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                        //}

                                        saldo.valoreCtvSpecified = true;

                                        pkt = new ProdottiKeyType();

                                        if (codAdeguatzza != "")
                                            pkt.codiceAdeguatezza = codAdeguatzza;
                                        else
                                            pkt.codiceAdeguatezza = "";

                                        if (codIsin != "")
                                            pkt.codiceIsin = codIsin;
                                        else
                                            pkt.codiceIsin = "";

                                        if (codMaf != "")
                                            pkt.codiceMaf = codMaf;
                                        else
                                            pkt.codiceMaf = "";

                                        if (codSottoProdotto != "")
                                            pkt.codiceSottoprodotto = codSottoProdotto;
                                        else
                                            pkt.codiceSottoprodotto = "";

                                        if (codInterno != "")
                                            pkt.codiceInterno = codInterno;
                                        else
                                            pkt.codiceInterno = "";


                                        saldo.chiave = pkt;
                                        ptfProdotto.AddSaldo(saldo);


                                        #endregion
                                        //    }
                                        //}
                                        #endregion
                                        #endregion
                                    }
                                    else
                                    {
                                        #region Codice Adeguatezza Non Valorizzato
                                        #region Ciclo DataRow
                                        foreach (DataRow rw in dtRichiesta.Rows)
                                        {
                                            if (Intermediario == rw["NOMEBANCATERZA"].ToString().Trim().ToUpper() &&
                                                TipoProdotto_TipoProdotto == rw["DESCR_GRUPPO"].ToString().Trim().ToUpper() &&
                                                Prodotto_Prodotto == rw["NOMEPRODOTTO"].ToString().Trim().ToUpper() &&
                                                Prodotto_Assetid == rw["ASSETID"].ToString().Trim().ToUpper())
                                            {

                                                ptfProdotto.descrizione += rw["ID"].ToString() + "|"; //+"_" + rw["DESCR_GRUPPO"].ToString() + "_" + rw["NOMEBANCATERZA"].ToString() + "|";

                                                #region SALDO NON ASUL
                                                saldo = new saldoType();
                                                if (rw["CONTROVALORE"] != DBNull.Value)
                                                {
                                                    saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                                    saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                                }

                                                saldo.valoreCtvSpecified = true;

                                                pkt = new ProdottiKeyType();

                                                if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                                    pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                                else
                                                    pkt.codiceAdeguatezza = "";

                                                if (rw["CODICEISIN"] != DBNull.Value)
                                                    pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                                else
                                                    pkt.codiceIsin = "";

                                                if (rw["CODICEMAF"] != DBNull.Value)
                                                    pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                                else
                                                    pkt.codiceMaf = "";

                                                if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                                    pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                                                else
                                                    pkt.codiceSottoprodotto = "";

                                                if (rw["CODICEINTERNO"] != DBNull.Value)
                                                    pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                                else
                                                    pkt.codiceInterno = "";


                                                saldo.chiave = pkt;
                                                ptfProdotto.AddSaldo(saldo);


                                                #endregion
                                            }
                                        }
                                        #endregion
                                        #endregion
                                    }

                                    #endregion
                                }
                                else
                                {
                                    #region Prodotti non in catalogo
                                    #region Ciclo DataRow
                                    foreach (DataRow rw in dtRichiesta.Rows)
                                    {
                                        if (Intermediario == rw["NOMEBANCATERZA"].ToString().Trim().ToUpper() &&
                                            TipoProdotto_TipoProdotto == rw["DESCR_GRUPPO"].ToString().Trim().ToUpper() &&
                                            Prodotto_Prodotto == rw["NOMEPRODOTTO"].ToString().Trim().ToUpper() &&
                                            Prodotto_Assetid == rw["ASSETID"].ToString().Trim().ToUpper())
                                        {

                                            ptfProdotto.descrizione += rw["ID"].ToString() + "|"; //+"_" + rw["DESCR_GRUPPO"].ToString() + "_" + rw["NOMEBANCATERZA"].ToString() + "|";

                                            #region SALDO NON ASUL
                                            saldo = new saldoType();
                                            if (rw["CONTROVALORE"] != DBNull.Value)
                                            {
                                                saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                            }

                                            saldo.valoreCtvSpecified = true;

                                            pkt = new ProdottiKeyType();

                                            if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                                pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                            else
                                                pkt.codiceAdeguatezza = "";

                                            if (rw["CODICEISIN"] != DBNull.Value)
                                                pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                            else
                                                pkt.codiceIsin = "";

                                            if (rw["CODICEMAF"] != DBNull.Value)
                                                pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                            else
                                                pkt.codiceMaf = "";

                                            if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                                pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                                            else
                                                pkt.codiceSottoprodotto = "";

                                            if (rw["CODICEINTERNO"] != DBNull.Value)
                                                pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                            else
                                                pkt.codiceInterno = "";


                                            saldo.chiave = pkt;
                                            ptfProdotto.AddSaldo(saldo);


                                            #endregion
                                        }
                                    }
                                    #endregion
                                    #endregion
                                }
                                if (ptfProdotto.descrizione != "" && ptfProdotto.descrizione != null)
                                {
                                    ptfProdotto.AddChildSaldoToAggregate();
                                    ptfTipoProdotto.AddAggregato(ptfProdotto);
                                }
                            }
                        }
                        #endregion
                        ptfTipoProdotto.AddChildToAggregate();
                        ptfIntermediario.AddAggregato(ptfTipoProdotto);

                    }
                }
                ptfIntermediario.AddChildToAggregate();
                ptfTotale.AddAggregato(ptfIntermediario);
            }

            ptfTotale.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS48PerIntermediario", ex.InnerException);
        }
        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS44(DataTable dtRichiesta, DataTable dtContrattiSintesiPerCliente)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        DataTable dtDistincttipoprodotto;
        DataTable dtDistinctprodotto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfTipoProdotto;
        ptfType ptfProdotto;
        saldoType saldo;
        ProdottiKeyType pkt;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumntipoprodotto = new string[1];
            paramColumntipoprodotto[0] = "SOTTOGRUPPO";
            dtDistincttipoprodotto = dtRichiesta.DefaultView.ToTable(true, paramColumntipoprodotto);
            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string distincttipoprodotto = "";
            string tipoprodotto = "";
            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            string rwAsulString = "";
            int versioneDBSimpb = 0;
            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALETITOLI";

            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesiPerCliente);

            #region Elimino linea self positiva (quella negativa � esclusa a livello stored)

            DataRow[] drSelfPositiva = dtRichiesta.Select(" CODICEISIN  IN ('EURO00000009','EURO10000007')"); // Cod Isin che identifica la linea self positiva

            foreach (DataRow row in drSelfPositiva)
            {
                dtRichiesta.Rows.Remove(row);
            }

            #endregion

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rwdistinct in dtDistincttipoprodotto.Rows)
            {
                // Creo un aggregato
                ptfTipoProdotto = new ptfType();
                ptfTipoProdotto.descrizione = rwdistinct["SOTTOGRUPPO"].ToString();

                distincttipoprodotto = rwdistinct["SOTTOGRUPPO"].ToString().Trim().ToUpper();

                #region Ciclo datarow
                foreach (DataRow rw in dtRichiesta.Rows)
                {
                    if (distincttipoprodotto == rw["SOTTOGRUPPO"].ToString().Trim().ToUpper())
                    {
                        if (rw["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)rw["TIPOPRODOTTOSINTESI"] == "")
                            rwAsulString = rw["TIPOPRODOTTO"].ToString();
                        else
                            rwAsulString = rw["TIPOPRODOTTOSINTESI"].ToString();

                        #region Aggregato di Prodotto
                        ptfProdotto = new ptfType();
                        ptfProdotto.descrizione = rw["ID"].ToString();
                        #endregion

                        if (tipoProdottoAsul.Equals(rwAsulString))
                        {
                            #region SALDO ASUL

                            #region Chiamata la WSGLOBALPOSITION
                            PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                            _chiaveCliente.codiceAgente = codiceAgente;
                            _chiaveCliente.codicefiscale = codiceFiscale;
                            _chiaveCliente.codiceRete = codiceRete;
                            _chiaveCliente.potenzialeClienteNAC = true;

                            PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                            _infoCliente.codiceApplicazione = codiceApplicazione;
                            _infoCliente.codiceRete = codiceRete;
                            _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;
                            string codiceContratto = rw["CONTRATTO"].ToString().Trim();

                            GlobalPositionWS gpWS = new GlobalPositionWS();

                            DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codiceContratto, _infoCliente, chiaveclientepb);
                            #endregion

                            foreach (DataRow rwAsul in dtAsul.Rows)
                            {
                                saldo = new saldoType();

                                if (rwAsul["CONTROVALORE"] != DBNull.Value)
                                {
                                    saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                    saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                }

                                saldo.valoreCtvSpecified = true;

                                pkt = new ProdottiKeyType();

                                //CODICEADEGUATEZZA
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                //if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                //    pkt.codiceInterno = rwAsul["ISINFITTIZIO"].ToString();

                                //if (rw["CODICEISIN"] != DBNull.Value)
                                //    pkt.codiceIsin = rw["CODICEISIN"].ToString();

                                //if (rw["CODICEMAF"] != DBNull.Value)
                                //    pkt.codiceMaf = rw["CODICEMAF"].ToString();


                                saldo.chiave = pkt;
                                ptfProdotto.AddSaldo(saldo);
                            }
                            #endregion
                        }
                        else
                        {
                            #region SALDO NON ASUL

                            saldo = new saldoType();
                            if (rw["CONTROVALORE"] != DBNull.Value)
                            {
                                saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                            }

                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();

                            if (rwAsulString.Equals(tipoProdottoAsu2)) //K Skandia
                            {
                                //CODICEADEGUATEZZA
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                //CODICESOTTOPRODOTTO
                                if (rw["ISIN_ASU2"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rw["ISIN_ASU2"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";
                            }
                            else
                            {
                                if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (rw["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (rw["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";

                                if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                if (rw["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";
                            }
                            saldo.chiave = pkt;
                            ptfProdotto.AddSaldo(saldo);


                            #endregion
                        }
                        ptfProdotto.AddChildSaldoToAggregate();

                        ptfTipoProdotto.AddAggregato(ptfProdotto);

                    }
                }
                #endregion

                ptfTipoProdotto.AddChildToAggregate();
                ptfTotale.AddAggregato(ptfTipoProdotto);
            }

            ptfTotale.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS44", ex.InnerException);
        }
        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS46(DataTable dtRichiesta, DataTable dtContrattiSintesiPerCliente)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 46 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfProdotto;
        saldoType saldo;
        ProdottiKeyType pkt;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;
            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;
            //K Skandia
            string rwAsu2String = "";
            string tipoProdottoAsu2 = ConfigurationManager.AppSettings["TIPOPRODOTTOASU2"].ToString().Trim().ToUpper();

            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEFONDIPENSIONE";

            AggiungiColonnaTipoProdottoContrattoSintesi(ref dtRichiesta, dtContrattiSintesiPerCliente);

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rw in dtRichiesta.Rows)
            {
                #region Aggregato di Prodotto
                ptfProdotto = new ptfType();
                ptfProdotto.descrizione = rw["ID"].ToString();
                #endregion

                #region SALDO NON ASUL

                saldo = new saldoType();
                if (rw["CONTROVALORE"] != DBNull.Value)
                {
                    saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                    saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                }

                saldo.valoreCtvSpecified = true;

                //K Skandia
                if (rw["TIPOPRODOTTOSINTESI"] == DBNull.Value || (string)rw["TIPOPRODOTTOSINTESI"] == "")
                    rwAsu2String = rw["TIPOPRODOTTO"].ToString();
                else
                    rwAsu2String = rw["TIPOPRODOTTOSINTESI"].ToString();

                pkt = new ProdottiKeyType();

                //K Skandia
                if (rwAsu2String.Equals(tipoProdottoAsu2))
                {
                    //CODICEADEGUATEZZA
                    if (rw["ISIN_ASU2"] != DBNull.Value)
                        pkt.codiceAdeguatezza = rw["ISIN_ASU2"].ToString();
                    else
                        pkt.codiceAdeguatezza = "";

                    //CODICESOTTOPRODOTTO
                    if (rw["ISIN_ASU2"] != DBNull.Value)
                        pkt.codiceSottoprodotto = rw["ISIN_ASU2"].ToString();
                    else
                        pkt.codiceSottoprodotto = "";
                }
                else
                {
                    if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                        pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                    else
                        pkt.codiceAdeguatezza = "";

                    if (rw["CODICEISIN"] != DBNull.Value)
                        pkt.codiceIsin = rw["CODICEISIN"].ToString();
                    else
                        pkt.codiceIsin = "";

                    if (rw["CODICEMAF"] != DBNull.Value)
                        pkt.codiceMaf = rw["CODICEMAF"].ToString();
                    else
                        pkt.codiceMaf = "";

                    if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                        pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                    else
                        pkt.codiceSottoprodotto = "";

                    if (rw["CODICEINTERNO"] != DBNull.Value)
                        pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                    else
                        pkt.codiceInterno = "";
                }

                saldo.chiave = pkt;
                ptfProdotto.AddSaldo(saldo);
                ptfProdotto.AddChildSaldoToAggregate();
                ptfTotale.AddAggregato(ptfProdotto);
                #endregion
            }
            #endregion

            ptfTotale.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS46", ex.InnerException);
        }
        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS50(DataTable dtRichiesta)
    {
        #region Variabili costruzione oggetto MessageType

        //la query � diversa dalla 56 non c'� la needarea il nome la descrizione dell'aggregato dovrebbe essere il nome dell'intemediario
        //non sarebbe meglio fare un ptf per ogni intermediario?
        //al posto del codice isin sembra che utilizzano l'asset class

        DataTable dtDistinctintermediario;
        DataTable dtDistinctprodotto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfIntermediario;
        ptfType ptfProdotto;
        saldoType saldo;
        ProdottiKeyType pkt;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;

            // DataView ordinato per NEEDAREA 
            string[] paramColumnintermediario = new string[1];
            paramColumnintermediario[0] = "intermediario";
            dtDistinctintermediario = dtRichiesta.DefaultView.ToTable(true, paramColumnintermediario);

            string[] paramColumnprodotto = new string[2];
            paramColumnprodotto[0] = "intermediario";
            paramColumnprodotto[1] = "ord_per_join_pr";

            dtDistinctprodotto = dtRichiesta.DefaultView.ToTable(true, paramColumnprodotto);

            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;


            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            ptfType ptfTotale = new ptfType();
            ptfTotale.descrizione = "TOTALEFONDIPENSIONE";

            #region CREAZIONE OGGETTO MESSAGE
            foreach (DataRow rwdistinct in dtDistinctintermediario.Rows)
            {
                // Creo un aggregato
                ptfIntermediario = new ptfType();
                ptfIntermediario.descrizione = rwdistinct["intermediario"].ToString();

                foreach (DataRow rwdistinctprodotto in dtDistinctprodotto.Rows)
                {
                    if (rwdistinctprodotto["intermediario"].ToString() == rwdistinct["intermediario"].ToString())
                    {
                        ptfProdotto = new ptfType();
                        ptfProdotto.descrizione = rwdistinctprodotto["ord_per_join_pr"].ToString();

                        #region Ciclo datarow
                        foreach (DataRow rw in dtRichiesta.Rows)
                        {
                            if (rwdistinctprodotto["intermediario"].ToString() == rw["intermediario"].ToString() &&
                                rwdistinctprodotto["ord_per_join_pr"].ToString() == rw["ord_per_join_pr"].ToString())
                            {

                                #region SALDO NON ASUL
                                saldo = new saldoType();
                                if (rw["CONTROVALORE"] != DBNull.Value)
                                {
                                    saldo.valore = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                    saldo.valoreCtv = Convert.ToDouble(rw["CONTROVALORE"].ToString());
                                }

                                saldo.valoreCtvSpecified = true;

                                pkt = new ProdottiKeyType();

                                if (rw["CODICEADEGUATEZZA"] != DBNull.Value)
                                    pkt.codiceAdeguatezza = rw["CODICEADEGUATEZZA"].ToString();
                                else
                                    pkt.codiceAdeguatezza = "";

                                if (rw["CODICEISIN"] != DBNull.Value)
                                    pkt.codiceIsin = rw["CODICEISIN"].ToString();
                                else
                                    pkt.codiceIsin = "";

                                if (rw["CODICEMAF"] != DBNull.Value)
                                    pkt.codiceMaf = rw["CODICEMAF"].ToString();
                                else
                                    pkt.codiceMaf = "";

                                if (rw["CODICESOTTOPRODOTTO"] != DBNull.Value)
                                    pkt.codiceSottoprodotto = rw["CODICESOTTOPRODOTTO"].ToString();
                                else
                                    pkt.codiceSottoprodotto = "";

                                if (rw["CODICEINTERNO"] != DBNull.Value)
                                    pkt.codiceInterno = rw["CODICEINTERNO"].ToString();
                                else
                                    pkt.codiceInterno = "";


                                saldo.chiave = pkt;
                                ptfProdotto.AddSaldo(saldo);

                                #endregion
                            }
                        }
                        #endregion

                        ptfProdotto.AddChildSaldoToAggregate();
                        ptfIntermediario.AddAggregato(ptfProdotto);
                    }
                }
                ptfIntermediario.AddChildToAggregate();
                ptfTotale.AddAggregato(ptfIntermediario);
            }

            ptfTotale.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfTotale);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS50", ex.InnerException);
        }
        return mt;
    }

    /// <summary>
    /// Crea l'albero di input per la chiamata dei VaR dei mercati finanziari
    /// </summary>
    /// <returns>input per la chiamata a prometeia per i mercati finanziari</returns>
    private static messaggioType CreaRichiestaVaRMercatiFinanziari()
    {

        #region Variabili costruzione oggetto MessageType

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfVaRMercati, ptfMacroAzionario, ptfMacroObbligazionario, ptfAsset = null;
        saldoType saldo = null;
        ProdottiKeyType pkt = null;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;


            #endregion

            #region HeaderMessage
            hdm.cliente = System.Configuration.ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = System.Configuration.ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType


            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            ptfVaRMercati = new ptfType();
            ptfVaRMercati.descrizione = "VAR_ASSET";

            #region CREAZIONE OGGETTO MESSAGE


            // Creo un aggregato
            ptfMacroAzionario = new ptfType();
            ptfMacroAzionario.descrizione = "MACRO_AZIONARIO";

            ptfMacroObbligazionario = new ptfType();
            ptfMacroObbligazionario.descrizione = "MACRO_OBBLIGAZIONARIO";

            Dictionary<string, List<AssetClass>> tabellaAsset = Prometeia.initializeTabellaAsset();

            List<AssetClass> AZ = tabellaAsset["AZ"];
            List<AssetClass> OB = tabellaAsset["OB"];

            #region CICLO ASSET AZIONARIO
            foreach (AssetClass asset in AZ)
            {
                ptfAsset = new ptfType();
                ptfAsset.descrizione = asset.ISIN + "|" + asset.Descrizione;

                saldo = new saldoType(); // Ogni prodotto avr� un saldo
                saldo.valore = 50.0;
                saldo.valoreCtv = 50.0;
                saldo.valoreCtvSpecified = true;

                pkt = new ProdottiKeyType();

                pkt.codiceAdeguatezza = asset.Adeguatezza;
                pkt.codiceInterno = string.Empty;
                pkt.codiceIsin = asset.ISIN;
                pkt.codiceMaf = asset.MAF;
                pkt.codiceSottoprodotto = string.Empty;

                saldo.chiave = pkt;
                ptfAsset.AddSaldo(saldo);

                ptfAsset.AddChildSaldoToAggregate();

                //ptfAsset.AddChildToAggregate(); //forse non serve
                ptfMacroAzionario.AddAggregato(ptfAsset);

            }
            ptfMacroAzionario.AddChildToAggregate();
            #endregion

            #region CICLO ASSET OBBLIGAZIONARIO

            foreach (AssetClass asset in OB)
            {
                ptfAsset = new ptfType();
                ptfAsset.descrizione = asset.ISIN + "|" + asset.Descrizione;

                saldo = new saldoType(); // Ogni prodotto avr� un saldo
                saldo.valore = 50.0;
                saldo.valoreCtv = 50.0;
                saldo.valoreCtvSpecified = true;

                pkt = new ProdottiKeyType();

                pkt.codiceAdeguatezza = asset.Adeguatezza;
                pkt.codiceInterno = string.Empty;
                pkt.codiceIsin = asset.ISIN;
                pkt.codiceMaf = asset.MAF;
                pkt.codiceSottoprodotto = string.Empty;

                saldo.chiave = pkt;
                ptfAsset.AddSaldo(saldo);

                ptfAsset.AddChildSaldoToAggregate();

                //ptfAsset.AddChildToAggregate(); //forse non serve
                ptfMacroObbligazionario.AddAggregato(ptfAsset);

            }
            ptfMacroObbligazionario.AddChildToAggregate();

            #endregion
            //ptfAsset.AddChildSaldoToAggregate();
            //ptfAsset.AddChildToAggregate();
            ptfVaRMercati.AddAggregato(ptfMacroAzionario);
            ptfVaRMercati.AddAggregato(ptfMacroObbligazionario);
            ptfVaRMercati.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfVaRMercati);
            richiestaVarPortafoglio.AddChildToAggregate();

            #endregion

            #endregion

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: Mercati obbligazionari e azionari", ex.InnerException);
        }


        return mt;
    }

    /// <summary>
    /// Usata nel job di storicizzazione del VaR per le macro asset OB,AZ,MN
    /// Crea l'albero di input per la chiamata dei VaR dei mercati finanziari
    /// </summary>
    /// <returns>input per la chiamata a prometeia per i mercati finanziari</returns>
    private static messaggioType CreaRichiestaVaRMacroAsset()
    {

        #region Variabili costruzione oggetto MessageType

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfVaRMercati, ptfMacroAzionario, ptfMacroObbligazionario, ptfAsset = null;
        saldoType saldo = null;
        ProdottiKeyType pkt = null;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;


            #endregion

            #region HeaderMessage
            hdm.cliente = System.Configuration.ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = System.Configuration.ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType


            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            ptfVaRMercati = new ptfType();
            ptfVaRMercati.descrizione = "VAR_ASSET";

            #region CREAZIONE OGGETTO MESSAGE


            // Creo un aggregato
            ptfMacroAzionario = new ptfType();
            ptfMacroAzionario.descrizione = "MACRO_AZIONARIO";

            ptfMacroObbligazionario = new ptfType();
            ptfMacroObbligazionario.descrizione = "MACRO_OBBLIGAZIONARIO";


            #region ASSET AZIONARIO

            ptfAsset = new ptfType();
            ptfAsset.descrizione = "MSACWF$|AZIONARIO";

            saldo = new saldoType(); // Ogni prodotto avr� un saldo
            saldo.valore = 50.0;
            saldo.valoreCtv = 50.0;
            saldo.valoreCtvSpecified = true;

            pkt = new ProdottiKeyType();

            pkt.codiceAdeguatezza = "MSACWF$";
            pkt.codiceInterno = string.Empty;
            pkt.codiceIsin = "MSACWF$";
            pkt.codiceMaf = "MSACWF$";
            pkt.codiceSottoprodotto = string.Empty;

            saldo.chiave = pkt;
            ptfAsset.AddSaldo(saldo);

            ptfAsset.AddChildSaldoToAggregate();

            //ptfAsset.AddChildToAggregate(); //forse non serve
            ptfMacroAzionario.AddAggregato(ptfAsset);


            ptfMacroAzionario.AddChildToAggregate();
            #endregion

            #region ASSET OBBLIGAZIONARIO


            ptfAsset = new ptfType();
            ptfAsset.descrizione = "SBWGEUE|OBBLIGAZIONARIO";

            saldo = new saldoType(); // Ogni prodotto avr� un saldo
            saldo.valore = 50.0;
            saldo.valoreCtv = 50.0;
            saldo.valoreCtvSpecified = true;

            pkt = new ProdottiKeyType();

            pkt.codiceAdeguatezza = "SBWGEUE";
            pkt.codiceInterno = string.Empty;
            pkt.codiceIsin = "SBWGEUE";
            pkt.codiceMaf = "SBWGEUE";
            pkt.codiceSottoprodotto = string.Empty;

            saldo.chiave = pkt;
            ptfAsset.AddSaldo(saldo);

            ptfAsset.AddChildSaldoToAggregate();

            //ptfAsset.AddChildToAggregate(); //forse non serve
            ptfMacroObbligazionario.AddAggregato(ptfAsset);


            ptfMacroObbligazionario.AddChildToAggregate();

            #endregion
            //ptfAsset.AddChildSaldoToAggregate();
            //ptfAsset.AddChildToAggregate();
            ptfVaRMercati.AddAggregato(ptfMacroAzionario);
            ptfVaRMercati.AddAggregato(ptfMacroObbligazionario);
            ptfVaRMercati.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfVaRMercati);
            richiestaVarPortafoglio.AddChildToAggregate();

            #endregion

            #endregion

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: Mercati obbligazionari e azionari", ex.InnerException);
        }


        return mt;
    }

    /// <summary>
    /// Crea l'albero di input per la chiamata dei VaR del portafoglio suddiviso per AssetClass
    /// </summary>
    /// <returns>input per la chiamata a prometeia per il portafoglio suddiviso per AssetClass</returns>
    private static messaggioType CreaRichiestaVaRPortafoglioAsset(DataTable portafoglio, DataTable dettPtf)
    {

        #region Variabili costruzione oggetto MessageType

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfAsset = null;
        saldoType saldo = null;
        ProdottiKeyType pkt = null;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;


            #endregion

            #region HeaderMessage
            hdm.cliente = System.Configuration.ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = System.Configuration.ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType


            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            ptfType ptfVaRAsset = new ptfType();
            ptfVaRAsset.descrizione = "VAR_ASSET";

            #region CREAZIONE OGGETTO MESSAGE

            string codiceMacroAsset = null;
            ptfType PtfMacroAsset = null;


            foreach (DataRow rowAsset in portafoglio.Rows)
            {
                string new_codiceMacroAsset = rowAsset["ASSET"].ToString().Substring(0, 2);
                string new_codiceAsset = rowAsset["ASSET"].ToString();

                AssetClass asset = Prometeia.findAssetClass(rowAsset["ASSET"].ToString());
                if (new_codiceMacroAsset != codiceMacroAsset) //Crea l'aggregato di MacroAsset
                {
                    if (codiceMacroAsset != null)
                    {
                        PtfMacroAsset.AddChildToAggregate();
                        ptfVaRAsset.AddAggregato(PtfMacroAsset);
                    }

                    PtfMacroAsset = new ptfType();
                    PtfMacroAsset.descrizione = new_codiceMacroAsset;
                    codiceMacroAsset = new_codiceMacroAsset;
                }

                if (new_codiceAsset == "FLLR" || new_codiceAsset == "FLMR" || new_codiceAsset == "FLHR")
                {

                    DataView dwFlessibili = new DataView(dettPtf);
                    dwFlessibili.RowFilter = "Tipologia_Flessibili='" + new_codiceAsset + "'";
                    DataTable dtFlessibili = dwFlessibili.ToTable();

                    ptfAsset = new ptfType();
                    ptfAsset.descrizione = rowAsset["ASSET"].ToString();

                    foreach (DataRow prodottoFlex in dtFlessibili.Rows)
                    {
                        ptfType ptfProdottoFL = new ptfType();
                        ptfProdottoFL.descrizione = prodottoFlex["NOME_PRODOTTO"].ToString();

                        saldo = new saldoType();
                        saldo.valore = Convert.ToDouble(prodottoFlex["FLESSIBILI"]);
                        saldo.valoreCtv = Convert.ToDouble(prodottoFlex["FLESSIBILI"]);
                        saldo.valoreCtvSpecified = true;

                        pkt = new ProdottiKeyType();

                        pkt.codiceAdeguatezza = prodottoFlex["Cod_Adeguatezza"].ToString();
                        pkt.codiceInterno = prodottoFlex["Cod_Interno"].ToString();
                        pkt.codiceIsin = string.Empty;// prodottoFlex["Cod_Isin"].ToString();
                        pkt.codiceMaf = prodottoFlex["Cod_Maf"].ToString();
                        pkt.codiceSottoprodotto = prodottoFlex["Cod_SottoProdotto"].ToString(); //string.Empty;

                        saldo.chiave = pkt;

                        ptfProdottoFL.AddSaldo(saldo);
                        ptfProdottoFL.AddChildSaldoToAggregate();

                        ptfAsset.AddAggregato(ptfProdottoFL);

                    }
                    ptfAsset.AddChildToAggregate();

                }
                else
                {

                    ptfAsset = new ptfType();
                    ptfAsset.descrizione = rowAsset["ASSET"].ToString();
                    saldo = new saldoType();
                    saldo.valore = Convert.ToDouble(rowAsset["CONTROVALORE"]);
                    saldo.valoreCtv = Convert.ToDouble(rowAsset["CONTROVALORE"]);
                    saldo.valoreCtvSpecified = true;

                    pkt = new ProdottiKeyType();

                    pkt.codiceAdeguatezza = asset == null ? string.Empty : asset.Adeguatezza;
                    pkt.codiceInterno = string.Empty;
                    pkt.codiceIsin = asset == null ? string.Empty : asset.ISIN;
                    pkt.codiceMaf = asset == null ? string.Empty : asset.MAF;
                    pkt.codiceSottoprodotto = string.Empty;

                    saldo.chiave = pkt;
                    ptfAsset.AddSaldo(saldo);

                    ptfAsset.AddChildSaldoToAggregate();

                    //ptfAsset.AddChildToAggregate(); //forse non serve
                }
                PtfMacroAsset.AddAggregato(ptfAsset);

            }


            #endregion

            PtfMacroAsset.AddChildToAggregate();
            ptfVaRAsset.AddAggregato(PtfMacroAsset);
            ptfVaRAsset.AddChildToAggregate();

            richiestaVarPortafoglio.Add(ptfVaRAsset);
            richiestaVarPortafoglio.AddChildToAggregate();

            #endregion



        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: Portafoglio suddiviso per assetClass", ex.InnerException);
        }


        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS102(DataTable dtRichiesta)
    {
        #region Variabili costruzione oggetto MessageType


        DataTable dtDistinctprodotto;
        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfIntermediario;
        ptfType ptfProdotto = null;
        saldoType saldo = null;
        ProdottiKeyType pkt = null;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;


            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;
            decimal controvalore = 0;
            bool prodottoincatalogo;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            ptfType ptfProdotti = new ptfType();
            ptfProdotti.descrizione = "PRODOTTI";

            #region CREAZIONE OGGETTO MESSAGE

            DataTable dtIntermediario = dtRichiesta.DefaultView.ToTable(true, "intermediario"); // Contiene la lista degli intermediari

            foreach (DataRow rwdistinctIntermediario in dtIntermediario.Rows)
            {
                // Creo un aggregato
                ptfIntermediario = new ptfType();
                ptfIntermediario.descrizione = rwdistinctIntermediario["intermediario"].ToString().Trim().Replace("'", "''").Length == 0 ? "BF" : rwdistinctIntermediario["intermediario"].ToString();

                DataView dwProdottiPerIntermediario = new DataView(dtRichiesta);
                dwProdottiPerIntermediario.RowFilter = rwdistinctIntermediario["intermediario"].ToString().Length > 0 ? "intermediario='" + rwdistinctIntermediario["intermediario"].ToString().Replace("'", "''") + "'" : string.Empty;
                DataTable dtProdottiPerIntermediario = dwProdottiPerIntermediario.ToTable(); // contiene la lsista dei prodotti per singolo intermediario.                

                foreach (DataRow rwprodotto in dtProdottiPerIntermediario.Rows)
                {
                    ptfProdotto = new ptfType(); // Ogni ptfProdotto corrisponde ad un prodotto

                    string codAdeguatezza = string.Empty;
                    string codIsin = string.Empty;
                    string codMaf = string.Empty;
                    string codSottoProdotto = string.Empty;
                    string codInterno = string.Empty;
                    string codContratto = string.Empty;

                    #region Recupero il Saldo per ogni prodotto

                    // Distinguo il tipo prodotto ASUL dagli altri. 
                    // Per i prodotti ASUL di patrimonio terzi non devo chiamare la Chiamata a WSGLOBALPOSITION GetContrattoUnitLinkedSaldo
                    // K Skandia
                    if (tipoProdottoAsul.Equals(rwprodotto["TipoProdotto"].ToString()) && rwdistinctIntermediario["intermediario"].ToString().Trim().Length == 0)
                    {
                        #region Prodotto ASUL

                        if (rwprodotto["CONTRATTO"].ToString() != "")
                        {
                            codContratto = rwprodotto["CONTRATTO"].ToString();
                            ptfProdotto.descrizione = codContratto;

                        }
                        ptfProdotto.descrizione += "|";

                        if (rwprodotto["CODICE_ISIN"].ToString() != "")
                            ptfProdotto.descrizione += rwprodotto["CODICE_ISIN"].ToString();
                        else
                            if (rwprodotto["COD_ADEGUATEZZA"].ToString() != "")
                                ptfProdotto.descrizione += rwprodotto["COD_ADEGUATEZZA"].ToString();
                            else
                                if (rwprodotto["CODICE_MAF"].ToString() != "")
                                    ptfProdotto.descrizione += rwprodotto["CODICE_MAF"].ToString();

                        #region Chiamata a WSGLOBALPOSITION
                        PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                        _chiaveCliente.codiceAgente = codiceAgente;
                        _chiaveCliente.codicefiscale = codiceFiscale;
                        _chiaveCliente.codiceRete = codiceRete;
                        _chiaveCliente.potenzialeClienteNAC = true;

                        PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                        _infoCliente.codiceApplicazione = codiceApplicazione;
                        _infoCliente.codiceRete = codiceRete;
                        _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;


                        GlobalPositionWS gpWS = new GlobalPositionWS();
                        DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codContratto, _infoCliente, chiaveclientepb);
                        #endregion

                        foreach (DataRow rwAsul in dtAsul.Rows)
                        {
                            saldo = new saldoType();

                            if (rwAsul["CONTROVALORE"] != DBNull.Value)
                            {
                                saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                            }
                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();

                            //CODICEADEGUATEZZA
                            if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                            else
                                pkt.codiceAdeguatezza = "";

                            //CODICESOTTOPRODOTTO
                            if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                            else
                                pkt.codiceSottoprodotto = "";


                            saldo.chiave = pkt;
                            ptfProdotto.AddSaldo(saldo);
                        }


                        #endregion
                    }
                    else
                    {
                        #region Prodotto NON ASUL


                        ptfProdotto.descrizione += rwprodotto["POSITIONID"].ToString() + "|";
                        if (rwprodotto["COD_ADEGUATEZZA"] != DBNull.Value)
                            codAdeguatezza = rwprodotto["COD_ADEGUATEZZA"].ToString();

                        if (rwprodotto["CODICE_ISIN"] != DBNull.Value)
                            codIsin = rwprodotto["CODICE_ISIN"].ToString();

                        if (rwprodotto["CODICE_MAF"] != DBNull.Value)
                            codMaf = rwprodotto["CODICE_MAF"].ToString();

                        if (rwprodotto["CODICE_SOTTOPRODOTTO"] != DBNull.Value)
                            codSottoProdotto = rwprodotto["CODICE_SOTTOPRODOTTO"].ToString();

                        if (rwprodotto["CODICE_INTERNO"] != DBNull.Value)
                            codInterno = rwprodotto["CODICE_INTERNO"].ToString();

                        saldo = new saldoType(); // Ogni prodotto avr� un saldo
                        saldo.valore = Convert.ToDouble(rwprodotto["CONTROVALORE_PRODOTTO"]);
                        saldo.valoreCtv = Convert.ToDouble(rwprodotto["CONTROVALORE_PRODOTTO"]);
                        saldo.valoreCtvSpecified = true;


                        pkt = new ProdottiKeyType();

                        if (codAdeguatezza != "")
                            pkt.codiceAdeguatezza = codAdeguatezza;
                        else
                            pkt.codiceAdeguatezza = "";

                        if (codIsin != "")
                            pkt.codiceIsin = codIsin;
                        else
                            pkt.codiceIsin = "";

                        if (codMaf != "")
                            pkt.codiceMaf = codMaf;
                        else
                            pkt.codiceMaf = "";

                        if (codSottoProdotto != "")
                            pkt.codiceSottoprodotto = codSottoProdotto;
                        else
                            pkt.codiceSottoprodotto = "";

                        if (codInterno != "")
                            pkt.codiceInterno = codInterno;
                        else
                            pkt.codiceInterno = "";



                        saldo.chiave = pkt;
                        ptfProdotto.AddSaldo(saldo);

                        #endregion
                    }


                    #endregion

                    if (ptfProdotto.descrizione != "" && ptfProdotto.descrizione != null)
                    {
                        ptfProdotto.AddChildSaldoToAggregate();
                        ptfIntermediario.AddAggregato(ptfProdotto);
                    }

                }
                ptfIntermediario.AddChildToAggregate();
                ptfProdotti.AddAggregato(ptfIntermediario);
            }

            ptfProdotti.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfProdotti);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS102", ex.InnerException);
        }
        return mt;
    }

    private static messaggioType CreaRichiestaVaRPortafoglioSezioneS120(DataTable dtRichiesta)
    {

        #region Variabili costruzione oggetto MessageType

        messaggioType mt = new messaggioType();
        headerMessaggioType hdm;
        bodyMessaggioType bdm;
        richiestaType richiesta;
        richiestaVaRPortafoglioType richiestaVarPortafoglio;
        ptfType ptfIntermediario;
        ptfType ptfProdotto = null;
        saldoType saldo = null;
        ProdottiKeyType pkt = null;
        #endregion

        try
        {
            #region Costruzione struttura base oggetto di tipo MessageType
            // L'oggetto e' costruito fino a richiestaVaRPortafoglio
            mt = new messaggioType();
            hdm = new headerMessaggioType();
            bdm = new bodyMessaggioType();
            richiesta = new richiestaType();
            bdm.Item = richiesta;
            mt.headerMessaggio = hdm;
            mt.bodyMessaggio = bdm;
            richiestaVarPortafoglio = new richiestaVaRPortafoglioType();
            richiesta.Item = richiestaVarPortafoglio;


            #endregion

            #region HeaderMessage
            hdm.cliente = ConfigurationManager.AppSettings["CLIENTE"].ToString();
            hdm.ip = ConfigurationManager.AppSettings["IP"].ToString();
            #endregion

            #region BodyMessageType

            #region RichiestaVarPortafoglio

            // PTF - CT
            #region PTF
            //ciclo per leggere tutti i nodi e i campi in esso contenuti
            // alpha - ST
            richiestaVarPortafoglio.alpha = Convert.ToDouble(ConfigurationManager.AppSettings["ALPHA"].ToString());
            richiestaVarPortafoglio.alphaSpecified = true;
            // hp - ST
            richiestaVarPortafoglio.hp = Convert.ToInt32(ConfigurationManager.AppSettings["HP"].ToString());
            richiestaVarPortafoglio.hpSpecified = true;

            string codiceAgente = "";
            string codiceRete = "";
            string codiceFiscale = "";
            string codiceApplicazione = "";
            int versioneDBSimpb = 0;
            //decimal controvalore = 0;
            //bool prodottoincatalogo;

            string tipoProdottoAsul = ConfigurationManager.AppSettings["TIPOPRODOTTOASUL"].ToString().Trim().ToUpper();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAGENTE"))
                codiceAgente = dtRichiesta.ExtendedProperties["CODICEAGENTE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICERETE"))
                codiceRete = dtRichiesta.ExtendedProperties["CODICERETE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEFISCALE"))
                codiceFiscale = dtRichiesta.ExtendedProperties["CODICEFISCALE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("CODICEAPPLICAZIONE"))
                codiceApplicazione = dtRichiesta.ExtendedProperties["CODICEAPPLICAZIONE"].ToString();

            if (dtRichiesta.ExtendedProperties.Contains("VERSIONEDATABASESIMPB"))
                versioneDBSimpb = int.Parse(dtRichiesta.ExtendedProperties["VERSIONEDATABASESIMPB"].ToString());

            if (dtRichiesta.ExtendedProperties.Contains("CHIAVECLIENTEPB"))
                chiaveclientepb = int.Parse(dtRichiesta.ExtendedProperties["CHIAVECLIENTEPB"].ToString());

            ptfType ptfProdotti = new ptfType();
            ptfProdotti.descrizione = "PRODOTTI";

            #region CREAZIONE OGGETTO MESSAGE

            DataTable dtIntermediario = dtRichiesta.DefaultView.ToTable(true, "intermediario"); // Contiene la lista degli intermediari

            foreach (DataRow rwdistinctIntermediario in dtIntermediario.Rows)
            {
                // Creo un aggregato
                ptfIntermediario = new ptfType();
                ptfIntermediario.descrizione = rwdistinctIntermediario["intermediario"].ToString().Trim().Replace("'", "''").Length == 0 ? "BF" : rwdistinctIntermediario["intermediario"].ToString();

                DataView dwProdottiPerIntermediario = new DataView(dtRichiesta);
                dwProdottiPerIntermediario.RowFilter = rwdistinctIntermediario["intermediario"].ToString().Length > 0 ? "intermediario='" + rwdistinctIntermediario["intermediario"].ToString().Replace("'", "''") + "'" : string.Empty;
                DataTable dtProdottiPerIntermediario = dwProdottiPerIntermediario.ToTable(); // contiene la lsista dei prodotti per singolo intermediario.                

                foreach (DataRow rwprodotto in dtProdottiPerIntermediario.Rows)
                {
                    ptfProdotto = new ptfType(); // Ogni ptfProdotto corrisponde ad un prodotto

                    string codAdeguatezza = string.Empty;
                    string codIsin = string.Empty;
                    string codMaf = string.Empty;
                    string codSottoProdotto = string.Empty;
                    string codInterno = string.Empty;
                    string codContratto = string.Empty;

                    #region Recupero il Saldo per ogni prodotto

                    // Distinguo il tipo prodotto ASUL dagli altri. 
                    // Per i prodotti ASUL di patrimonio terzi non devo chiamare la Chiamata a WSGLOBALPOSITION GetContrattoUnitLinkedSaldo
                    // K Skandia
                    //if (tipoProdottoAsul.Equals(rwprodotto["TipoProdotto"].ToString()) && (rwdistinctIntermediario["intermediario"].ToString().Equals("BF") || rwdistinctIntermediario["intermediario"].ToString().Equals("TOTALE")))
                    if (tipoProdottoAsul.Equals(rwprodotto["TipoProdotto"].ToString()) && !string.IsNullOrEmpty(rwprodotto["PositionId"].ToString()) && (rwdistinctIntermediario["intermediario"].ToString().Equals("BF") || rwdistinctIntermediario["intermediario"].ToString().Equals("TOTALE")) && rwprodotto["CONTRATTO"] != null && rwprodotto["CONTRATTO"].ToString() != "")
                    {
                        #region Prodotto ASUL

                        if (rwprodotto["CONTRATTO"].ToString() != "")
                        {
                            codContratto = rwprodotto["CONTRATTO"].ToString();
                            ptfProdotto.descrizione = codContratto;

                        }
                        ptfProdotto.descrizione = rwprodotto["EMITTENTE"].ToString();

                        if (rwprodotto["CODICE_ISIN"].ToString() != "")
                            ptfProdotto.descrizione += rwprodotto["CODICE_ISIN"].ToString();
                        else
                            if (rwprodotto["COD_ADEGUATEZZA"].ToString() != "")
                                ptfProdotto.descrizione += rwprodotto["COD_ADEGUATEZZA"].ToString();
                            else
                                if (rwprodotto["CODICE_MAF"].ToString() != "")
                                    ptfProdotto.descrizione += rwprodotto["CODICE_MAF"].ToString();

                        #region Chiamata a WSGLOBALPOSITION
                        PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.ChiaveCliente();
                        _chiaveCliente.codiceAgente = codiceAgente;
                        _chiaveCliente.codicefiscale = codiceFiscale;
                        _chiaveCliente.codiceRete = codiceRete;
                        _chiaveCliente.potenzialeClienteNAC = true;

                        PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient _infoCliente = new PrometeiaMessage.bancafideuram.nac.globalposition.InfoClient();
                        _infoCliente.codiceApplicazione = codiceApplicazione;
                        _infoCliente.codiceRete = codiceRete;
                        _infoCliente.versioneDatabaseSIMPB = versioneDBSimpb;


                        GlobalPositionWS gpWS = new GlobalPositionWS();
                        DataTable dtAsul = gpWS.GetContrattoUnitLinkedSaldo(_chiaveCliente, codContratto, _infoCliente, chiaveclientepb);
                        #endregion

                        foreach (DataRow rwAsul in dtAsul.Rows)
                        {
                            saldo = new saldoType();

                            if (rwAsul["CONTROVALORE"] != DBNull.Value)
                            {
                                saldo.valore = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                                saldo.valoreCtv = Convert.ToDouble(rwAsul["CONTROVALORE"].ToString());
                            }
                            saldo.valoreCtvSpecified = true;

                            pkt = new ProdottiKeyType();

                            //CODICEADEGUATEZZA
                            if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                pkt.codiceAdeguatezza = rwAsul["ISINFITTIZIO"].ToString();
                            else
                                pkt.codiceAdeguatezza = "";

                            //CODICESOTTOPRODOTTO
                            if (rwAsul["ISINFITTIZIO"] != DBNull.Value)
                                pkt.codiceSottoprodotto = rwAsul["ISINFITTIZIO"].ToString();
                            else
                                pkt.codiceSottoprodotto = "";


                            saldo.chiave = pkt;
                            ptfProdotto.AddSaldo(saldo);
                        }


                        #endregion
                    }
                    else
                    {
                        #region Prodotto NON ASUL


                        ptfProdotto.descrizione = rwprodotto["EMITTENTE"].ToString();
                        if (rwprodotto["COD_ADEGUATEZZA"] != DBNull.Value)
                            codAdeguatezza = rwprodotto["COD_ADEGUATEZZA"].ToString();

                        if (rwprodotto["CODICE_ISIN"] != DBNull.Value)
                            codIsin = rwprodotto["CODICE_ISIN"].ToString();

                        if (rwprodotto["CODICE_MAF"] != DBNull.Value)
                            codMaf = rwprodotto["CODICE_MAF"].ToString();

                        if (rwprodotto["CODICE_SOTTOPRODOTTO"] != DBNull.Value)
                            codSottoProdotto = rwprodotto["CODICE_SOTTOPRODOTTO"].ToString();

                        if (rwprodotto["CODICE_INTERNO"] != DBNull.Value)
                            codInterno = rwprodotto["CODICE_INTERNO"].ToString();

                        saldo = new saldoType(); // Ogni prodotto avr� un saldo
                        saldo.valore = Convert.ToDouble(rwprodotto["CONTROVALORE_PRODOTTO"]);
                        saldo.valoreCtv = Convert.ToDouble(rwprodotto["CONTROVALORE_PRODOTTO"]);
                        saldo.valoreCtvSpecified = true;


                        pkt = new ProdottiKeyType();

                        if (codAdeguatezza != "")
                            pkt.codiceAdeguatezza = codAdeguatezza;
                        else
                            pkt.codiceAdeguatezza = "";

                        if (codIsin != "")
                            pkt.codiceIsin = codIsin;
                        else
                            pkt.codiceIsin = "";

                        if (codMaf != "")
                            pkt.codiceMaf = codMaf;
                        else
                            pkt.codiceMaf = "";

                        if (codSottoProdotto != "")
                            pkt.codiceSottoprodotto = codSottoProdotto;
                        else
                            pkt.codiceSottoprodotto = "";

                        if (codInterno != "")
                            pkt.codiceInterno = codInterno;
                        else
                            pkt.codiceInterno = "";



                        saldo.chiave = pkt;
                        ptfProdotto.AddSaldo(saldo);

                        #endregion
                    }


                    #endregion

                    if (ptfProdotto.descrizione != "" && ptfProdotto.descrizione != null)
                    {
                        ptfProdotto.AddChildSaldoToAggregate();
                        ptfIntermediario.AddAggregato(ptfProdotto);
                    }

                }
                ptfIntermediario.AddChildToAggregate();
                ptfProdotti.AddAggregato(ptfIntermediario);
            }

            ptfProdotti.AddChildToAggregate();
            richiestaVarPortafoglio.Add(ptfProdotti);
            richiestaVarPortafoglio.AddChildToAggregate();
            #endregion

            #endregion

            #endregion

            #endregion
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + "; Metodo: CreaRichiestaVaRPortafoglioSezioneS120", ex.InnerException);
        }
        return mt;

    }

    private static void SetVarpConCoperturaZero(messaggioType MessageObj)
    {

        if (MessageObj != null)
        {
            rispostaType risposta = (rispostaType)MessageObj.bodyMessaggio.Item;

            #region Risposta rispostaVaRPortafoglioType
            if (risposta.Item is rispostaVaRPortafoglioType)
            {
                rispostaVaRPortafoglioType rispostaPtf = (rispostaVaRPortafoglioType)risposta.Item;

                foreach (ptfType ptf in rispostaPtf.ptf)
                {
                    if (ptf.stat.copertura == 0)
                    {
                        ptf.misureRischio.varp = -1000;
                        ptf.stat.copertura = -1000;
                    }
                    FunzioneRicorsivaPtf(ptf);
                }
            }
            #endregion
        }
    }

    private static void FunzioneRicorsivaPtf(ptfType ptf)
    {
        if (ptf.aggregato != null)
        {
            foreach (ptfType ptfAggreagato in ptf.aggregato)
            {

                if (ptfAggreagato.stat.copertura == 0)
                    ptfAggreagato.misureRischio.varp = -1000;
                FunzioneRicorsivaPtf(ptfAggreagato);


            }
        }

    }

    private static bool IsFAOFAP(string codiceInterno)
    {
        switch (codiceInterno)
        {
            case "48":
            case "49":
            case "60":
            case "18":
            case "35":
            case "PR":
            case "PX":
                return true;
            default:
                return false;
        }
    }

    private static DataTable DettagliAssicurativi(DataRow drProdotto, PrometeiaMessage.bancafideuram.nac.posizionecliente.ChiaveCliente chiave, string codiceContratto, string codiceInterno, PrometeiaMessage.bancafideuram.nac.posizionecliente.InfoClient info, int chiaveclientepb)
    {
        double investi, disinvesti;

        DettaglioOperazione[] dettagliOperazione = new DettaglioOperazione[1]; // totale operazioni
        DettaglioOperazione dettaglioOperazione = new DettaglioOperazione();

        investi = 0;
        disinvesti = 0;

        if (drProdotto["investi"] != DBNull.Value)
            investi = Convert.ToDouble(drProdotto["investi"]);

        if (drProdotto["disinvesti"] != DBNull.Value)
            disinvesti = Convert.ToDouble(drProdotto["disinvesti"]);


        if (investi > 0)
            dettaglioOperazione.aggiuntivoLiquidazione = true;
        if (disinvesti > 0)
            dettaglioOperazione.aggiuntivoLiquidazione = false;

        dettaglioOperazione.codicesottoProdotto = string.Empty;
        dettaglioOperazione.importo = Math.Abs(investi - disinvesti);
        dettaglioOperazione.isinFittizio = string.Empty;
        dettagliOperazione[0] = dettaglioOperazione;

        PosizioneClienteWS pcWS = new PosizioneClienteWS();
        return pcWS.GetDettaglioAssicurativi(chiave, codiceContratto, codiceInterno, dettagliOperazione, info, chiaveclientepb);
    }
}

public class DataViewSezione21 : DataView
{
    private string _descrizione;

    public string Descrizione
    {
        get
        {
            return _descrizione;
        }
        set { _descrizione = value; }
    }
}