public static int SaveReportOptionValueWithLineNumber(Guid idReport, Upsilab.Data.Model.Option option,
            int idOptionAttribute, string value, string fieldType, string colomnName, int idReportAttributeValue)
        {
            ReportOptionAttributeValue optionAttributeValue = null;
            int idOption = option.idOption;
            bool updateDateUpdated = false;
            string completedStatus = Report.ReportBL.Status.Completed.ToString();
            string waitingForClientUpdateStatus = Report.ReportBL.Status.WaitingForClientUpdate.ToString();

            using (UpsilabEntities db = new UpsilabEntities())
            {
                ReportOptionAttributeValue reportOptionAttrValueToUpdate =
                    db.ReportOptionAttributeValue.FirstOrDefault(
                        x => x.idReportOptionAttributeValue == idReportAttributeValue);

                /* UPDATE */
                if (reportOptionAttrValueToUpdate != null)
                {
                    dynamic customData = reportOptionAttrValueToUpdate.CustomObjectValue;

                    if (customData != null)
                    {
                        bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                        if (!isTheSameValue)
                        {

                            CustomObject.SetValueByPropertyName(customData, colomnName, value);
                            reportOptionAttrValueToUpdate.CustomObjectValue = customData;
                            reportOptionAttrValueToUpdate.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                            if (reportOptionAttrValueToUpdate.ReportOptionValue!=null)
                            {
                                reportOptionAttrValueToUpdate.ReportOptionValue.DateUpdated = (updateDateUpdated)
                                                        ? DateTime.Now
                                                        : (DateTime?)null; 
                            }

                            
                            //
                        }
                    }
                    optionAttributeValue = reportOptionAttrValueToUpdate;
                }
                /* CREATE */
                else
                {
                    //Get current report
                    Data.Model.Report report = (from rep in db.Report
                                                where rep.idReport == idReport
                                                select rep).FirstOrDefault();

                    //Check if customer has completed report
                    var checkCompletedReport = (from rep in db.Report
                                                where rep.CustomerProspect.idCustomer == report.CustomerProspect.idCustomer
                                                      && rep.Status == completedStatus
                                                select rep).FirstOrDefault();

                    if (checkCompletedReport != null)
                    {
                        updateDateUpdated = true;
                    }

                    //#9262 : Check if customer changes the info after Adviser request
                    if (!updateDateUpdated)
                    {
                        if (report.Status == waitingForClientUpdateStatus && SessionManager.GetUserSession().IsEndUser())
                        {
                            updateDateUpdated = true;
                        }
                    }

                    {
                        //pour agreg
                        ReportOptionAttributeValue agregOptionAttributeValue = null;
                        //

                        ReportOptionValue optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                         where rov.idReport == idReport && rov.idOption == idOption
                                                         && rov.ReportOptionAttributeValue.FirstOrDefault(x => x.idReportOptionAttributeValue == idReportAttributeValue).idReportOptionAttributeValue == idReportAttributeValue
                                                         select rov).FirstOrDefault();

                        IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>();

                        //Option value ?
                        if (optionValue != null)
                        {
                            lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            lstOptionAttributeValues = lstOptionAttributeValues.Where(oav => oav.idOptionAttribute == idOptionAttribute).ToList();
                        }
                        else if (!string.IsNullOrEmpty(value))
                        {
                            optionValue = new ReportOptionValue()
                            {
                                idReport = idReport,
                                idOption = idOption,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                            };

                            //Add ReportOptionValue to DB : don't save yet
                            db.ReportOptionValue.AddObject(optionValue);

                            //Insert parent
                            while (option.idParent.HasValue)
                            {
                                ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                       where rov.idReport == idReport && rov.idOption == option.idParent
                                                                       select rov).FirstOrDefault();

                                if (optionParentValue == null && option.idParent != null)
                                {
                                    optionParentValue = new ReportOptionValue()
                                    {
                                        idReport = idReport,
                                        idOption = option.idParent.Value,
                                        Value = string.Empty,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    //Add ReportOptionValue to DB : don't save yet
                                    db.ReportOptionValue.AddObject(optionParentValue);

                                    //Check if this parent option has already parent ?
                                    option = optionParentValue.Option;
                                }
                                else
                                {
                                    optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                    break;
                                }
                            }
                        }

                        

                        //Get target option attribute
                        if (lstOptionAttributeValues.Any())
                        {
                            //Line already in database
                            ReportOptionAttributeValue reportOptionAttrValue = lstOptionAttributeValues.FirstOrDefault();
                            dynamic customData = reportOptionAttrValue.CustomObjectValue;

                            if (customData != null)
                            {
                                bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                if (!isTheSameValue)
                                {

                                    CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                    reportOptionAttrValue.CustomObjectValue = customData;
                                    reportOptionAttrValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                    reportOptionAttrValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                    //pour agreg
                                    agregOptionAttributeValue = reportOptionAttrValue;
                                    optionAttributeValue = reportOptionAttrValue;
                                    //
                                }
                            }

                        }
                        else
                        {
                            //Get Custom datatype columns
                            List<string> customAttribute = OptionBL.GetCustomAttributeNames(fieldType);

                            if (customAttribute.Count > 0)
                            {
                                dynamic customData = new Upsilab.Data.Model.CustomObject();
                                dynamic customDataEmpty = new Upsilab.Data.Model.CustomObject();

                                foreach (string itemColumnName in customAttribute)
                                {
                                    string _strVal = string.Empty;

                                    if (itemColumnName == colomnName)
                                    {
                                        _strVal = value;
                                        CustomObject.SetValueByPropertyName(customData, itemColumnName, _strVal);
                                        CustomObject.SetValueByPropertyName(customDataEmpty, itemColumnName, string.Empty);
                                    }
                                }


                                bool createOptionAttr = true;
                                //Create empty lines
                                if (lstOptionAttributeValues.Count == 0)
                                {
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customData;

                                    lstOptionAttributeValues.Add(optionAttributeValue);
                                    //optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                                }

                                if (optionAttributeValue == null)
                                //if (createOptionAttr)
                                {
                                    //Add new line
                                    //Insert optionattrubutevalue
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customData;

                                    //pour agreg
                                    agregOptionAttributeValue = optionAttributeValue;
                                    //
                                }
                                else
                                {
                                    customData = optionAttributeValue.CustomObjectValue;

                                    if (customData != null)
                                    {
                                        bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                        if (!isTheSameValue)
                                        {
                                            CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                            optionAttributeValue.CustomObjectValue = customData;
                                            optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                            optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                            //pour agreg
                                            agregOptionAttributeValue = optionAttributeValue;
                                            //
                                        }
                                    }
                                }

                                //Add ReportOptionAttributeValue to DB : don't save yet
                                optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);

                            }
                        }
                        

                        //#region Save patrimoine from Recueil/lab to Agregateur
                        ////update/add ag_upsideo_compte
                        //if (report.CustomerProspect.User1.idLicenseAgreg.HasValue && report.CustomerProspect.User1.idAgregCGP.HasValue
                        //    && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                        //    && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                        //{
                        //    //Les ids en cours : agregCabinet, agregCGP et agregClient
                        //    Guid idAgregCGP = report.CustomerProspect.User1.idAgregCGP.Value;
                        //    Guid idAgregCabinet = report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet;
                        //    Guid currentAgregClientId = Guid.Empty;

                        //    if (report.CustomerProspect.idAgregClient.HasValue)
                        //    {
                        //        currentAgregClientId = report.CustomerProspect.idAgregClient.Value;
                        //    }
                        //    else
                        //    {
                        //        ag_upsideo_client clientAgregToAdd = new ag_upsideo_client()
                        //        {
                        //            idclient = Guid.NewGuid(),
                        //            idcgp = idAgregCGP,
                        //            nomclient = report.CustomerProspect.User.UserName,
                        //            prenomclient = report.CustomerProspect.User.UserFirstName,
                        //            adr = report.CustomerProspect.Adress,
                        //            cp = report.CustomerProspect.ZipCode,
                        //            ville = report.CustomerProspect.City,
                        //            titre = report.CustomerProspect.Title,
                        //            ddn = DateTime.Now,
                        //            deleted = "n"
                        //        };

                        //        db.ag_upsideo_client.AddObject(clientAgregToAdd);

                        //        report.CustomerProspect.idAgregClient = clientAgregToAdd.idclient;
                        //        currentAgregClientId = clientAgregToAdd.idclient;
                        //    }

                        //    //Fournisseur de l'actif : comme il s'agit de données provenant du "Recueil/LAB", mettre "UPSIDEO" comme fournisseur fictif (pour chaque cabinet / etablissement)
                        //    //Get fournisseur
                        //    ag_upsideo_fournisseur agregFournisseur = db.ag_upsideo_fournisseur.Where(f => f.idcrmcabinet == report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet
                        //                                                                              && f.nomfournisseur == Business.Agreg.agupsideocompteBL.FournisseurUpsideo).FirstOrDefault();

                        //    if (agregFournisseur == null)
                        //    {
                        //        agregFournisseur = new ag_upsideo_fournisseur()
                        //        {
                        //            idcrmcabinet = idAgregCabinet,
                        //            nomfournisseur = Business.Agreg.agupsideocompteBL.FournisseurUpsideo,
                        //            cleAgreg = Business.Agreg.agupsideocompteBL.FournisseurUpsideo.ToLower(),
                        //            deleted = "n",
                        //        };

                        //        //TODO : to delete : normalement à faire lors de la souscription mais garder ce code pour test
                        //        //Insertion fournisseur avec un autre contexte
                        //        using (UpsilabEntities dbTemp = new UpsilabEntities())
                        //        {
                        //            dbTemp.ag_upsideo_fournisseur.AddObject(agregFournisseur);
                        //            dbTemp.SaveChanges();
                        //        }
                        //    }

                        //    //num compte fictif dans table compte Agreg
                        //    string numCompteFictif = string.Empty;
                        //    numCompteFictif = string.Format("{0}_{1}", idOptionAttribute.ToString(), lineNumber.Value.ToString());

                        //    //teste si existe déjà (maj) si no new
                        //    ag_upsideo_compte currentCompte = db.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numCompteFictif).FirstOrDefault();

                        //    //maj
                        //    if (currentCompte != null && agregOptionAttributeValue != null)
                        //    {
                        //        switch (idOptionAttribute)
                        //        {
                        //            case 204:
                        //            case 205:
                        //                {
                        //                    currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                        //                    currentCompte.dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null;
                        //                    currentCompte.valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null;
                        //                    currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null;
                        //                    currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                        //                    currentCompte.type = "n"; //pour l'instant : non géré
                        //                }
                        //                break;
                        //            case 206:
                        //                currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                        //                currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null;
                        //                currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                        //                currentCompte.type = "n"; //pour l'instant : non géré
                        //                break;
                        //            default:
                        //                break;

                        //        }
                        //    }
                        //    //new
                        //    else if (currentCompte == null && agregOptionAttributeValue != null)
                        //    {
                        //        switch (idOptionAttribute)
                        //        {
                        //            case 204:
                        //            case 205:
                        //                {
                        //                    currentCompte = new ag_upsideo_compte()
                        //                    {
                        //                        idclient = currentAgregClientId,
                        //                        idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                        //                        idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                        //                        numcompte = numCompteFictif,
                        //                        typecontrat = "bien immobilier",
                        //                        deleted = "n",

                        //                        designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                        //                        dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null,
                        //                        valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null,
                        //                        totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null
                        //                    };
                        //                    if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                        //                    {
                        //                        db.ag_upsideo_compte.AddObject(currentCompte);
                        //                    }

                        //                }
                        //                break;

                        //            case 206:
                        //                {
                        //                    currentCompte = new ag_upsideo_compte()
                        //                    {
                        //                        idclient = currentAgregClientId,
                        //                        idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                        //                        idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                        //                        numcompte = numCompteFictif,
                        //                        typecontrat = "professionels",
                        //                        deleted = "n",

                        //                        designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                        //                        totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null

                        //                    };
                        //                    if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                        //                    {
                        //                        db.ag_upsideo_compte.AddObject(currentCompte);
                        //                    }
                        //                }
                        //                break;
                        //            default:
                        //                break;

                        //        }
                        //    }
                        //}
                        //#endregion


                    }

                    #region Report
                    //5- Update dateupdated report               
                    report.DateUpdated = DateTime.Now;
                    #endregion 
                }

                //6- Commit all changes here
                db.SaveChanges();

                return optionAttributeValue!=null ? optionAttributeValue.idReportOptionAttributeValue : 0;
            }
        }
 public static bool IsAlreadyExist(Guid idReport, int idOptionAttribute, string value, string fieldType, string colomnName)
 {
     bool exist = false;
     using (UpsilabEntities db = new UpsilabEntities())
     {
         var lst =
             db.ReportOptionAttributeValue.Where(
                 x => x.idReport == idReport && x.idOptionAttribute == idOptionAttribute).ToList();
         if (lst.Any())
         {
             ReportOptionAttributeValue report = new ReportOptionAttributeValue();
             dynamic customData = report.CustomObjectValue;
             CustomObject.SetValueByPropertyName(customData, colomnName, value);
             report.CustomObjectValue = customData;
             foreach (var reportOptionAttrValue in lst)
             {
                 if (reportOptionAttrValue.Value == report.Value)
                 {
                     exist = true;
                     break;
                 }
             }
         }
     }
     return exist;
 }
        private static void SetOptionToSave(Guid idReport, Upsilab.Data.Model.Option option, OptionAttribute optionAttribute, string value, string fieldType, List<ReportOptionValue> lstOptionValues, UpsilabEntities db)
        {
            if (option == null && optionAttribute == null)
            {
                return; //ce cas ne doit pas se présenter
            }

            string action = string.Empty;

            ReportOptionValue optionValue = null;
            ReportOptionAttributeValue optionAttributeValue = null;

            //1- Champ
            #region TXT
            if (fieldType == "txt")
            {
                //Do nothing if value is null. Don't check empty because it's a value :) ?
                if (value == null)
                {
                    return;
                }

                optionValue = lstOptionValues.Where(rov => rov.idOption == optionAttribute.idOption).FirstOrDefault();

                if (optionValue == null)
                {
                    action = "I";
                }
                else
                {
                    optionAttributeValue = optionValue.ReportOptionAttributeValue.Where(roav => roav.idOptionAttribute == optionAttribute.idOptionAttribute).FirstOrDefault();
                    if (optionAttributeValue == null)
                    {
                        action = "I";
                    }
                    else
                    {
                        //No need to add if the same value
                        if (optionAttributeValue.Value != value)
                        {
                            optionAttributeValue.Value = value;
                            //optionAttributeValue.DateUpdated = DateTime.Now; TODO

                            //TODO
                            //db.ReportOptionAttributeValue.Attach(optionAttributeValue);
                            //db.ObjectStateManager.ChangeObjectState(optionAttributeValue, System.Data.EntityState.Modified);
                            //db.SaveChanges();
                        }
                    }
                }

                if (action == "I")
                {
                    //Check if reportOptionValue exists
                    if (optionValue == null) //insert option value
                    {
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = option.idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        lstOptionValues.Add(optionValue);

                        db.ReportOptionValue.Attach(optionValue);
                        db.ObjectStateManager.ChangeObjectState(optionValue, System.Data.EntityState.Added);

                        //Insert parent ??
                        List<ReportOptionValue> lstParents = GetParentOptionToAdd(idReport, lstOptionValues, option);
                        foreach (var optionParentValue in lstParents)
                        {
                            lstOptionValues.Add(optionParentValue);

                            //db.ReportOptionValue.Attach(optionParentValue);
                            //db.ObjectStateManager.ChangeObjectState(optionValue, System.Data.EntityState.Added);

                            db.ReportOptionValue.AddObject(optionParentValue);
                        }
                    }

                    //Insert optionattrubutevalue
                    ReportOptionAttributeValue newReportOptionAttributeValue = new ReportOptionAttributeValue()
                    {
                        idReport = idReport,
                        idOptionAttribute = optionAttribute.idOptionAttribute,
                        idReportOptionValue = optionValue.idReportOptionValue,
                        Value = value,
                        DateCreated = DateTime.Now,
                    };

                    //Add ReportOptionAttributeValue to DB : don't save yet
                    optionValue.ReportOptionAttributeValue.Add(newReportOptionAttributeValue);
                }
            }
            #endregion

            //2- Radio
            #region RB
            //2- Save option attribute value (Radio button)
            else if (fieldType == "rb")
            {
                //No need to delete if it's the option
                optionValue = lstOptionValues.Where(rov => rov.idOption == option.idOption).FirstOrDefault();
                if (optionValue == null)
                {
                    //Delete old rb
                    IList<ReportOptionValue> optionValues = (from rov in lstOptionValues
                                                             where rov.Option.idParent == option.idParent
                                                             select rov).ToList();

                    //Delete option attribute values attached to option value
                    if (optionValues != null)
                    {
                        foreach (var itemOptionValue in optionValues)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(itemOptionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = itemOptionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();

                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            lstOptionValues.Remove(itemOptionValue);

                            db.ReportOptionValue.DeleteObject(itemOptionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in lstOptionValues
                                                                             where rov.Option.idParent == itemOptionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();

                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    lstOptionValues.Remove(optionValueChild);

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }

                    }

                    //Insert new rb
                    ReportOptionValue newOptionValue = new ReportOptionValue()
                    {
                        idReport = idReport,
                        idOption = option.idOption,
                        Value = string.Empty,
                        DateCreated = DateTime.Now,
                    };

                    //Add ReportOptionValue to DB : don't save yet
                    lstOptionValues.Add(newOptionValue);

                    db.ReportOptionValue.AddObject(newOptionValue);

                    //Insert parent
                    List<ReportOptionValue> lstParents = GetParentOptionToAdd(idReport, lstOptionValues, option);
                    foreach (var optionParentValue in lstParents)
                    {
                        lstOptionValues.Add(optionParentValue);

                        db.ReportOptionValue.AddObject(optionParentValue);
                    }
                }
            }
            #endregion

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reportIdDest"></param>
        /// <param name="lstReportOptionValuesSource"></param>
        public static void SaveReportOptionValues(Upsilab.Data.Model.Report reportDest, List<ReportOptionValue> lstReportOptionValuesSource)
        {
            //Insert new OptionValue
            using (UpsilabEntities db = new UpsilabEntities())
            {
                foreach (var reportOptionValueSource in lstReportOptionValuesSource)
                {
                    //1- Report option value
                    ReportOptionValue newReportOptionValue = new ReportOptionValue()
                    {
                        idReport = reportDest.idReport,
                        idOption = reportOptionValueSource.idOption,
                        Value = string.Empty,
                        DateCreated = DateTime.Now,
                    };

                    //Add ReportOptionValue to DB : don't save yet
                    db.ReportOptionValue.AddObject(newReportOptionValue);

                    if (reportOptionValueSource.ReportOptionAttributeValue.Count > 0)
                    {
                        //2- Report option attribute value
                        foreach (var reportOptAttrValueSource in reportOptionValueSource.ReportOptionAttributeValue)
                        {
                            ReportOptionAttributeValue newReportOptionAttrValue = new ReportOptionAttributeValue()
                            {
                                idReport = reportDest.idReport,
                                idOptionAttribute = reportOptAttrValueSource.idOptionAttribute,
                                idReportOptionValue = newReportOptionValue.idReportOptionValue,
                                Value = reportOptAttrValueSource.Value,
                                DateCreated = DateTime.Now,
                            };

                            //Add ReportOptionAttributeValue to DB : don't save yet
                            newReportOptionValue.ReportOptionAttributeValue.Add(newReportOptionAttrValue);
                        }
                    }
                }

                //3- Commit all changes here
                db.SaveChanges();
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reportIdDest"></param>
        /// <param name="lstReportOptionValuesSource"></param>
        public static int SaveReportOptionValue(Guid idReport, Upsilab.Data.Model.Option option, int idOptionAttribute, string value, string fieldType, string colomnName, int? lineNumber)
        {
            ReportOptionAttributeValue optionAttributeValue2 = null;
            int idOption = option.idOption;
            bool updateDateUpdated = false;
            string completedStatus = Report.ReportBL.Status.Completed.ToString();
            string waitingForClientUpdateStatus = Report.ReportBL.Status.WaitingForClientUpdate.ToString();

            //Insert new OptionValue
            using (UpsilabEntities db = new UpsilabEntities())
            {
                //Get current report
                Data.Model.Report report = (from rep in db.Report
                                            where rep.idReport == idReport
                                            select rep).FirstOrDefault();

                //Check if customer has completed report
                var checkCompletedReport = (from rep in db.Report
                                            where rep.CustomerProspect.idCustomer == report.CustomerProspect.idCustomer
                                                  && rep.Status == completedStatus
                                            select rep).FirstOrDefault();

                if (checkCompletedReport != null)
                {
                    updateDateUpdated = true;
                }

                //#9262 : Check if customer changes the info after Adviser request
                if (!updateDateUpdated)
                {
                    if (report.Status == waitingForClientUpdateStatus && SessionManager.GetUserSession().IsEndUser())
                    {
                        updateDateUpdated = true;
                    }
                }

                #region TEXTBOX, DROPDOWN : txt, dt, enum
                //1- Save option attribute value (simple textbox / textarea)
                if (fieldType == "txt" || fieldType == "dt" || fieldType == "enum")
                {
                    ReportOptionAttributeValue optionAttributeValue = (from roav in db.ReportOptionAttributeValue.Include("ReportOptionValue")
                                                                       where roav.idReport == idReport && roav.idOptionAttribute == idOptionAttribute
                                                                       select roav).FirstOrDefault();

                    if (optionAttributeValue != null)
                    {
                        if (optionAttributeValue.Value != value) //update if not equal
                        {
                            optionAttributeValue.Value = value;
                            optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                            optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                        }
                        else
                        {
                            //Do nothing if equal
                        }
                        optionAttributeValue2 = optionAttributeValue;
                    }
                    else if (!string.IsNullOrEmpty(value)) //Insert if value is not empty
                    {
                        //Check if reportOptionValue exists
                        ReportOptionValue optionValue = (from rov in db.ReportOptionValue
                                                         where rov.idReport == idReport && rov.idOption == idOption
                                                         select rov).FirstOrDefault();

                        if (optionValue == null) //insert option value
                        {
                            optionValue = new ReportOptionValue()
                            {
                                idReport = idReport,
                                idOption = idOption,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                            };

                            //Add ReportOptionValue to DB : don't save yet
                            db.ReportOptionValue.AddObject(optionValue);

                            //Insert parent
                            while (option.idParent.HasValue)
                            {
                                ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                       where rov.idReport == idReport && rov.idOption == option.idParent
                                                                       select rov).FirstOrDefault();

                                if (optionParentValue == null)
                                {
                                    optionParentValue = new ReportOptionValue()
                                    {
                                        idReport = idReport,
                                        idOption = option.idParent.Value,
                                        Value = string.Empty,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    //Add ReportOptionValue to DB : don't save yet
                                    db.ReportOptionValue.AddObject(optionParentValue);

                                    //Check if this parent option has already parent ?
                                    option = optionParentValue.Option;
                                }
                                else
                                {
                                    optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                    break;
                                }
                            }
                        }

                        //Insert optionattrubutevalue
                        ReportOptionAttributeValue newReportOptionAttributeValue = new ReportOptionAttributeValue()
                        {
                            idReport = idReport,
                            idOptionAttribute = idOptionAttribute,
                            idReportOptionValue = optionValue.idReportOptionValue,
                            Value = value,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionAttributeValue to DB : don't save yet
                        optionValue.ReportOptionAttributeValue.Add(newReportOptionAttributeValue);
                        optionAttributeValue2 = newReportOptionAttributeValue;
                    }
                }
                #endregion

                #region RADIO BUTTON : rb
                //2- Save option attribute value (Radio button)
                else if (fieldType == "rb")
                {
                    //Delete old rb
                    IList<ReportOptionValue> optionValues = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                             where rov.idReport == idReport && rov.Option.idParent == option.idParent
                                                             select rov).ToList();

                    //Delete option attribute values attached to option value
                    if (optionValues != null)
                    {
                        foreach (var optionValue in optionValues)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.ReportOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                                             where rov.idReport == idReport && rov.Option.idParent == optionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }

                    }

                    if (!string.IsNullOrEmpty(value) && value.ToLower() == "true")
                    {
                        //Insert new rb
                        ReportOptionValue newOptionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(newOptionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }


                    
                    }
                }
                #endregion

                #region CHECKBOX : chk
                //3- Save option attribute value (Checkbox)
                else if (fieldType == "chk")
                {
                    ReportOptionValue optionValue;

                    if (value == "false")
                    {
                        //Delete old chk
                        optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                       where rov.idReport == idReport && rov.idOption == idOption
                                       select rov).FirstOrDefault();

                        //Delete option attribute values attached to option value
                        if (optionValue != null)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.ReportOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                                             where rov.idReport == idReport && rov.Option.idParent == optionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }
                    }
                    else if (value == "true")
                    {
                        //Insert new chk
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(optionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region CUSTOM DATATYPE
                //4- Custom datatype
                else
                {
                    //pour agreg
                    ReportOptionAttributeValue agregOptionAttributeValue = null;
                    //

                    ReportOptionValue optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                     where rov.idReport == idReport && rov.idOption == idOption
                                                     select rov).FirstOrDefault();

                    IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>();

                    //Option value ?
                    if (optionValue != null)
                    {
                        lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                        lstOptionAttributeValues = lstOptionAttributeValues.Where(oav => oav.idOptionAttribute == idOptionAttribute).ToList();
                    }
                    else if (!string.IsNullOrEmpty(value))
                    {
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(optionValue);

                        //Insert parent
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }
                    }

                    //Get target option attribute
                    if (lineNumber.HasValue && lineNumber.Value < lstOptionAttributeValues.Count)
                    {
                        //Line already in database
                        ReportOptionAttributeValue reportOptionAttrValue = lstOptionAttributeValues[lineNumber.Value];
                        dynamic customData = reportOptionAttrValue.CustomObjectValue;

                        if (customData != null)
                        {
                            bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                            if (!isTheSameValue)
                            {
                                CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                reportOptionAttrValue.CustomObjectValue = customData;
                                reportOptionAttrValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                reportOptionAttrValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                //pour agreg
                                agregOptionAttributeValue = reportOptionAttrValue;
                                //
                            }
                        }
                        optionAttributeValue2 = reportOptionAttrValue;

                    }
                    else
                    {
                        //Get Custom datatype columns
                        List<string> customAttribute = OptionBL.GetCustomAttributeNames(fieldType);

                        if (customAttribute.Count > 0)
                        {
                            dynamic customData = new Upsilab.Data.Model.CustomObject();
                            dynamic customDataEmpty = new Upsilab.Data.Model.CustomObject();

                            foreach (string itemColumnName in customAttribute)
                            {
                                string _strVal = string.Empty;

                                if (itemColumnName == colomnName)
                                {
                                    _strVal = value;
                                }
                                CustomObject.SetValueByPropertyName(customData, itemColumnName, _strVal);
                                CustomObject.SetValueByPropertyName(customDataEmpty, itemColumnName, string.Empty);
                            }

                            ReportOptionAttributeValue optionAttributeValue = null;
                            bool createOptionAttr = true;
                            if (!lineNumber.HasValue && lstOptionAttributeValues.Count > 0)
                            {
                                createOptionAttr = false;
                                optionAttributeValue = optionValue.ReportOptionAttributeValue.Where(oav => oav.idOptionAttribute == idOptionAttribute).FirstOrDefault();
                                optionAttributeValue2 = optionAttributeValue;
                            }
                            else if (lineNumber.HasValue)
                            {
                                //Create empty lines
                               // while (lstOptionAttributeValues.Count < lineNumber.Value)
                                {
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customDataEmpty;

                                    lstOptionAttributeValues.Add(optionAttributeValue);
                                    optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                                }
                            }

                            //if (optionAttributeValue == null)
                            if (createOptionAttr)
                            {
                                //Add new line
                                //Insert optionattrubutevalue
                                optionAttributeValue = new ReportOptionAttributeValue()
                                {
                                    idReport = idReport,
                                    idOptionAttribute = idOptionAttribute,
                                    idReportOptionValue = optionValue.idReportOptionValue,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                optionAttributeValue.CustomObjectValue = customData;

                                //pour agreg
                                agregOptionAttributeValue = optionAttributeValue;
                                optionAttributeValue2 = agregOptionAttributeValue;
                                //
                            }
                            else
                            {
                                customData = optionAttributeValue.CustomObjectValue;

                                if (customData != null)
                                {
                                    bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                    if (!isTheSameValue)
                                    {
                                        CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                        optionAttributeValue.CustomObjectValue = customData;
                                        optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                        optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                        //pour agreg
                                        agregOptionAttributeValue = optionAttributeValue;
                                        //
                                    }
                                }
                            }

                            //Add ReportOptionAttributeValue to DB : don't save yet
                            optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                            optionAttributeValue2 = optionAttributeValue;
                        }
                    }

                    #region Save patrimoine from Recueil/lab to Agregateur
                    //update/add ag_upsideo_compte
                    //if (report.CustomerProspect.User1.idLicenseAgreg.HasValue && report.CustomerProspect.User1.idAgregCGP.HasValue
                    //    && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                    //    && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                    if (report.CustomerProspect.User1.HasAggregatorLicense() && report.CustomerProspect.User1.idAgregCGP.HasValue
                        && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                        && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                    {
                        //Les ids en cours : agregCabinet, agregCGP et agregClient
                        Guid idAgregCGP = report.CustomerProspect.User1.idAgregCGP.Value;
                        Guid idAgregCabinet = report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet;
                        Guid currentAgregClientId = Guid.Empty;

                        if (report.CustomerProspect.idAgregClient.HasValue)
                        {
                            currentAgregClientId = report.CustomerProspect.idAgregClient.Value;
                        }
                        else
                        {
                            ag_upsideo_client clientAgregToAdd = new ag_upsideo_client()
                            {
                                idclient = Guid.NewGuid(),
                                idcgp = idAgregCGP,
                                nomclient = report.CustomerProspect.User.UserName,
                                prenomclient = report.CustomerProspect.User.UserFirstName,
                                adr = report.CustomerProspect.Adress,
                                cp = report.CustomerProspect.ZipCode,
                                ville = report.CustomerProspect.City,
                                titre = report.CustomerProspect.Title,
                                ddn = DateTime.Now,
                                deleted = "n"
                            };

                            db.ag_upsideo_client.AddObject(clientAgregToAdd);

                            report.CustomerProspect.idAgregClient = clientAgregToAdd.idclient;
                            currentAgregClientId = clientAgregToAdd.idclient;
                        }

                        //Fournisseur de l'actif : comme il s'agit de données provenant du "Recueil/LAB", mettre "UPSIDEO" comme fournisseur fictif (pour chaque cabinet / etablissement)
                        //Get fournisseur
                        ag_upsideo_fournisseur agregFournisseur = db.ag_upsideo_fournisseur.Where(f => f.idcrmcabinet == report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet
                                                                                                  && f.nomfournisseur == Business.Agreg.agupsideocompteBL.FournisseurUpsideo).FirstOrDefault();

                        if (agregFournisseur == null)
                        {
                            agregFournisseur = new ag_upsideo_fournisseur()
                            {
                                idcrmcabinet = idAgregCabinet,
                                nomfournisseur = Business.Agreg.agupsideocompteBL.FournisseurUpsideo,
                                cleAgreg = Business.Agreg.agupsideocompteBL.FournisseurUpsideo.ToLower(),
                                deleted = "n",
                            };

                            //TODO : to delete : normalement à faire lors de la souscription mais garder ce code pour test
                            //Insertion fournisseur avec un autre contexte
                            using (UpsilabEntities dbTemp = new UpsilabEntities())
                            {
                                dbTemp.ag_upsideo_fournisseur.AddObject(agregFournisseur);
                                dbTemp.SaveChanges();
                            }
                        }

                        //num compte fictif dans table compte Agreg
                        string numCompteFictif = string.Empty;
                        numCompteFictif = string.Format("{0}_{1}", idOptionAttribute.ToString(), lineNumber.Value.ToString());

                        //teste si existe déjà (maj) si no new
                        ag_upsideo_compte currentCompte = db.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numCompteFictif).FirstOrDefault();

                        //maj
                        if (currentCompte != null && agregOptionAttributeValue != null)
                        {
                            switch (idOptionAttribute)
                            {
                                case 204:
                                case 205:
                                    {
                                        currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                                        currentCompte.dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null;
                                        currentCompte.valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null;
                                        currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null;
                                        currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                        currentCompte.type = "n"; //pour l'instant : non géré
                                    }
                                    break;
                                case 206:
                                    currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                                    currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null;
                                    currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                    currentCompte.type = "n"; //pour l'instant : non géré
                                    break;
                                default:
                                    break;

                            }
                        }
                        //new
                        else if (currentCompte == null && agregOptionAttributeValue != null)
                        {
                            switch (idOptionAttribute)
                            {
                                case 204:
                                case 205:
                                    {
                                        currentCompte = new ag_upsideo_compte()
                                        {
                                            idclient = currentAgregClientId,
                                            idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                                            idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                            numcompte = numCompteFictif,
                                            typecontrat = "bien immobilier",
                                            deleted = "n",

                                            designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                                            dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null,
                                            valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null,
                                            totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null
                                        };
                                        if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                                        {
                                            db.ag_upsideo_compte.AddObject(currentCompte);
                                        }

                                    }
                                    break;

                                case 206:
                                    {
                                        currentCompte = new ag_upsideo_compte()
                                        {
                                            idclient = currentAgregClientId,
                                            idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                                            idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                            numcompte = numCompteFictif,
                                            typecontrat = "professionels",
                                            deleted = "n",

                                            designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                                            totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null

                                        };
                                        if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                                        {
                                            db.ag_upsideo_compte.AddObject(currentCompte);
                                        }
                                    }
                                    break;
                                default:
                                    break;

                            }
                        }
                    }
                    #endregion


                }
                #endregion

                #region Report
                //5- Update dateupdated report               
                report.DateUpdated = DateTime.Now;
                #endregion

                //6- Commit all changes here
                db.SaveChanges();
                return optionAttributeValue2!=null ? optionAttributeValue2.idReportOptionAttributeValue : 0;
            }
        }
        public static bool UpdateReportOptions(Guid idReport, List<ReportOptionValue> SelectedOptions)
        {
            // Particular case for mobile 151, email 152
            Upsilab.Data.Model.Report report = ReportBL.GetReportById(idReport);
            Upsilab.Data.Model.User userClient = report.CustomerProspect.User;
            bool saveDataUser = false;
            //

            bool retVal = true;
            try
            {
                var parentOptions = SelectedOptions.Where(so => so.Option.idParent.HasValue.Equals(false));
                foreach (var parentOption in parentOptions)
                {

                    List<Data.Model.Option> optList = OptionBL.GetOptionsByIdParent(parentOption.idOption); //TODO

                    #region Delete existing OptionAttributeValue under Parent
                    List<ReportOptionAttributeValue> toBeDeletedAttr = new List<ReportOptionAttributeValue>();
                    using (UpsilabEntities retrieveContext = new UpsilabEntities())
                    {
                        foreach (var opt in optList)
                        {
                            var deleteAttr = (from toBeDel in retrieveContext.ReportOptionAttributeValue.ToList()
                                              join o in opt.OptionAttribute on toBeDel.idOptionAttribute equals o.idOptionAttribute
                                              where toBeDel.idReport.Equals(idReport)
                                              select toBeDel).ToList();
                            toBeDeletedAttr.AddRange(deleteAttr);
                        }

                        foreach (var toBeDel in toBeDeletedAttr)
                        {
                            retrieveContext.ReportOptionAttributeValue.DeleteObject(toBeDel);
                            retrieveContext.SaveChanges();
                        }

                        //Commit all changes here
                        //retrieveContext.SaveChanges();
                    }
                    #endregion

                    //Delete existing OptionValue under Parent
                    List<ReportOptionValue> toBeDeletedOpt = new List<ReportOptionValue>();
                    using (UpsilabEntities retrieveContext = new UpsilabEntities())
                    {
                        toBeDeletedOpt = (from toBeDel in retrieveContext.ReportOptionValue.ToList()
                                          join opt in optList on toBeDel.idOption equals opt.idOption
                                          where toBeDel.idReport.Equals(idReport)
                                          select toBeDel).ToList();

                        foreach (var toBeDel in toBeDeletedOpt)
                        {
                            retrieveContext.ReportOptionValue.DeleteObject(toBeDel);
                            retrieveContext.SaveChanges();
                        }

                        //Commit all changes here
                        //retrieveContext.SaveChanges();
                    }
                }

                #region Update OptionValue
                //Insert new OptionValue
                using (UpsilabEntities insertContext = new UpsilabEntities())
                {
                    foreach (var toBeAdded in SelectedOptions)
                    {
                        ReportOptionValue newVal = new ReportOptionValue();
                        newVal.idReport = idReport;
                        newVal.idOption = toBeAdded.idOption;
                        newVal.Value = string.Empty;

                        insertContext.ReportOptionValue.AddObject(newVal);
                        insertContext.SaveChanges();

                        if (toBeAdded.ReportOptionAttributeValue.Count > 0)
                        {
                            foreach (var optAttr in toBeAdded.ReportOptionAttributeValue)
                            {
                                ReportOptionAttributeValue newAttVal = new ReportOptionAttributeValue();
                                newAttVal.idReport = idReport;
                                newAttVal.idOptionAttribute = optAttr.idOptionAttribute;
                                newAttVal.idReportOptionValue = newVal.idReportOptionValue;
                                newAttVal.Value = optAttr.Value;

                                insertContext.ReportOptionAttributeValue.AddObject(newAttVal);
                                insertContext.SaveChanges();

                                //----- Particular cas for field existing in table USER : Mobile and email
                                //151 PP mobile. 391 PM Mobile
                                //152 PP email. 392 PM email
                                if (optAttr.idOptionAttribute == 151 || optAttr.idOptionAttribute == 391)
                                {
                                    userClient.UserMobilePhone = optAttr.Value;
                                    saveDataUser = true;
                                }
                                if (optAttr.idOptionAttribute == 152 || optAttr.idOptionAttribute == 392)
                                {
                                    userClient.UserEmail = optAttr.Value;
                                    saveDataUser = true;
                                }
                                //-----
                            }
                        }
                    }

                    //Commit all changes here
                    //insertContext.SaveChanges();
                }

                if (saveDataUser)
                {
                    if (!UserBL.IsEmailUsed(userClient.UserEmail, userClient))
                        Upsilab.Business.User.UserBL.UpdateUser(userClient);
                }
                #endregion
            }
            catch (Exception e)
            {
                retVal = false;
                Log.Log.AppendException(e);
            }
            return retVal;
        }
        private static void BuildOrientationTable(FoxitPDFGenerator pdfGen, Data.Model.Report report, float y, float x = 0)
        {
            var languageDataPP = PageLanguageHelper.GetLanguageContent("User", "PDFReportPP");
            List<string> colsNames = new List<string>() { languageDataPP.GetContent("PdfReportPP_088"), languageDataPP.GetContent("PdfReportPP_089"), languageDataPP.GetContent("PdfReportPP_090") };
            List<float> colsWidth = new List<float>() { 60, 280, 160 };
            ReportOptionAttributeValue dataPrior = new ReportOptionAttributeValue();
            List<int> lstIdOption = new List<int>() { 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243 };
            string autre1 = "", autre2 = "";
            Dictionary<int, List<string>> data = new Dictionary<int, List<string>>();
            int nbLignes = 14;
            for (int i = 0; i < nbLignes; i++)
            {
                data.Add(i, new List<string>());
                data[i] = new List<string>();
                dataPrior = report.ReportOptionAttributeValue.Where(roav => roav.idOptionAttribute == lstIdOption[i]).FirstOrDefault();
                if (dataPrior != null)
                {
                    if (lstIdOption[i] == 242)
                    {
                        autre1 = Convert.ToString(dataPrior.CustomObjectValue.Object);
                    }

                    if (lstIdOption[i] == 243)
                    {
                        autre2 = Convert.ToString(dataPrior.CustomObjectValue.Object);
                    }

                    for (int j = 1; j <= colsNames.Count; j++)
                    {
                        if (j == 2)
                            data[i].Add("");
                        else
                        {
                            if (dataPrior != null)
                            {
                                switch (j)
                                {
                                    case 1:
                                        data[i].Add(GetEnumValue(Convert.ToString(dataPrior.CustomObjectValue.Priority), 5));
                                        break;
                                    case 3:
                                        data[i].Add(GetEnumValue(Convert.ToString(dataPrior.CustomObjectValue.YearImmediate), 6));
                                        break;
                                }
                            }
                            else
                            {
                                data[i].Add("");
                            }
                        }
                    }
                }
                else
                {
                    for (int j = 1; j <= colsNames.Count; j++)
                    {
                        data[i].Add("");
                    }
                }
            }
            data[0][1] = languageDataPP.GetContent("PdfReportPP_091");
            data[1][1] = languageDataPP.GetContent("PdfReportPP_092");
            data[2][1] = languageDataPP.GetContent("PdfReportPP_093");
            data[3][1] = languageDataPP.GetContent("PdfReportPP_094");
            data[4][1] = languageDataPP.GetContent("PdfReportPP_095");
            data[5][1] = languageDataPP.GetContent("PdfReportPP_096");
            data[6][1] = languageDataPP.GetContent("PdfReportPP_097");
            data[7][1] = languageDataPP.GetContent("PdfReportPP_098");
            data[8][1] = languageDataPP.GetContent("PdfReportPP_099");
            data[9][1] = languageDataPP.GetContent("PdfReportPP_100");
            data[10][1] = languageDataPP.GetContent("PdfReportPP_101");
            data[11][1] = languageDataPP.GetContent("PdfReportPP_102");
            data[12][1] = languageDataPP.GetContent("PdfReportPP_103") + " " + autre1;
            data[13][1] = languageDataPP.GetContent("PdfReportPP_104") + " " + autre2;


            pdfGen.AddTable(colsNames, colsWidth, data, y, colsWidth.Sum(), (nbLignes + 3) * 20, x);
        }
        //update
        //private static float GeneratePMRLesPersonnesHabilitées(FoxitPDFGenerator instance, Data.Model.Report report, PageLanguageHelper languageData, int idOptionAttribute, float yStartPoint = 0)
        //{
        //    if (yStartPoint + 310 >= 700)
        //    {
        //        instance.CreatePage();
        //        yStartPoint = 0;
        //    }

        //    yStartPoint = yStartPoint + 20; //spacing

        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(languageData.GetContent("PersonnesHabiliteesSection_Line1"), yStartPoint, 500, 20);
        //    ReportBL.PlotBooleanValue(instance, ReportBL.GetBooleanValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), String.Empty, "Title"), yStartPoint, 40);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"Madame", yStartPoint, 500, 20, 60);
        //    ReportBL.PlotBooleanValue(instance, ReportBL.GetBooleanValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), Boolean.FalseString, "Title"), yStartPoint, 110);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"Monsieur", yStartPoint, 500, 20, 130);

        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(String.Format(@"Nom : {0}", ReportBL.GetStringValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), "Name")), yStartPoint + 20, 500, 20);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(String.Format(@"Prénom : {0}", ReportBL.GetStringValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), "FirstName")), yStartPoint + 35, 500, 20);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(String.Format(@"Date de naissance : {0}", ReportBL.GetStringValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), "DateOfBirth")), yStartPoint + 50, 500, 20);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(String.Format(@"Fonction : {0}", ReportBL.GetStringValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), "Function")), yStartPoint + 65, 500, 20);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(String.Format(@"Nationalité : {0}", ReportBL.GetStringValue(ReportBL.GetReportOptionAttributeValueFromReportInstance(report, idOptionAttribute), "Nationality")), yStartPoint + 80, 500, 20);

        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[8], idReport), yStartPoint + 100);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"Résident", yStartPoint + 100, 500, 20, 20);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[9], idReport), yStartPoint + 100, 80);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"Non Résident", yStartPoint + 100, 500, 20, 100);

        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(String.Format(@"Pays de résidence : {0}", ReportBL.GetStringValue(ReportOptionBL.GetReportOptionAttributeValueByIdOptionAttributeAndIdReport(values[10], idReport))), yStartPoint + 120, 500, 20);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"La personne habilitée est-elle domiciliée dans un pays définis par le GAFI ?  (Accédez à la ", yStartPoint + 140, 500, 20, 100);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"liste de ces  pays sur : http://www.fatf-gafi.org/fr/)", yStartPoint + 155, 500, 20, 100);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[11], idReport), yStartPoint + 170, 100);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"OUI", yStartPoint + 170, 500, 20, 120);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[12], idReport), yStartPoint + 170, 150);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"NON", yStartPoint + 170, 500, 20, 170);

        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"La personne habilitée est-elle domiciliée dans un centre dit « Off-shore » ?  (Accédez à ", yStartPoint + 200, 500, 20, 100);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"la liste de ces  pays sur : http://www.oecd.org/ctp/harmful/43775845.pdf)", yStartPoint + 215, 500, 20, 100);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[13], idReport), yStartPoint + 230, 100);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"OUI", yStartPoint + 230, 500, 20, 120);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[14], idReport), yStartPoint + 230, 150);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"NON", yStartPoint + 230, 500, 20, 170);

        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"Cette personne est-elle bénéficiaire effectif * ?", yStartPoint + 260, 500, 20);
        //    instance.AddReceuil_DetailText_Justify_Calibri_Label(@"Le bénéficiaire effectif est la personne dont la participation directe ou indirecte au capital de la personne morale est supérieure ou égale à 25%", yStartPoint + 275, 500, 20);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[15], idReport), yStartPoint + 290);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"OUI", yStartPoint + 290, 500, 20, 20);
        //    ReportBL.PlotBooleanValue(instance, ReportOptionBL.GetReportOptionValueByIdOptionAndIdReport(values[16], idReport), yStartPoint + 290, 50);
        //    instance.AddReceuil_DefaultText_Justify_Calibri_Label(@"NON", yStartPoint + 290, 500, 20, 70);

        //    //added spacing
        //    return yStartPoint + 310;
        //}

        private static float GeneratePMRLesBénéficiaireEffectif(FoxitPDFGenerator instance, ReportOptionAttributeValue data, PageLanguageHelper languageData, float yStartPoint = 0)
        {
            if (data != null)
            {

                //if (yStartPoint + 530 >= 700)
                //{
                instance.CreatePage();
                yStartPoint = 0;
                //}

                // yStartPoint = yStartPoint + 20; //spacing

                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line1"), yStartPoint, 500, 20);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.Title, yStartPoint, 40, "2");
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line1_Item2"), yStartPoint, 500, 20, 60);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.Title, yStartPoint, 110, "1");
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line1_Item1"), yStartPoint, 500, 20, 130);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.Title, yStartPoint, 200, "3");
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line1_Item3"), yStartPoint, 500, 20, 220);


                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line2"), data.CustomObjectValue.Name), yStartPoint + 20, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line2"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Name, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line3"), data.CustomObjectValue.MaidenName), yStartPoint + 35, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line3"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.MaidenName, yStartPoint, answer_width, 20, answer_x);

                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line4"), data.CustomObjectValue.FirstName), yStartPoint + 50, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line4"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.FirstName, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line5"), data.CustomObjectValue.DateOfBirth), yStartPoint + 65, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line5"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.DateOfBirth, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line6_Item1"), data.CustomObjectValue.Phone), yStartPoint + 80, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line6_Item1"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Phone, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line6_Item2"), data.CustomObjectValue.Mobile), yStartPoint + 80, 500, 20, 200);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line6_Item2"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Mobile, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line7"), data.CustomObjectValue.Email), yStartPoint + 95, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line7"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Email, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line8"), data.CustomObjectValue.Address), yStartPoint + 120, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line8"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Address, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line9"), data.CustomObjectValue.Function), yStartPoint + 135, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line9"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Function, yStartPoint, answer_width, 20, answer_x);

                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line10"), data.CustomObjectValue.Nationality), yStartPoint + 150, 500, 20);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line10"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Nationality, yStartPoint, answer_width, 20, answer_x);


                //instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line11"), yStartPoint + 165, 500, 20, 100);
                //instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line12"), yStartPoint + 180, 500, 20, 100);
                instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line11"), languageData.GetContent("LesBénéficiaireEffectifSection_Line12")), yStartPoint += interline * 1.5f, 500 - 100, 40, 100);

                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsGAFI, yStartPoint += interline * 1.5f, 100, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 115);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsGAFI, yStartPoint, 145, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 170);
                instance.AddDefaultText(string.Format("{0} {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line13"), data.CustomObjectValue.GAFICountry), yStartPoint += interline, 500, 20, 100);

                //instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line14"), yStartPoint + 240, 500, 20, 100);
                //instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line15"), yStartPoint + 255, 500, 20, 100);
                instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line14"), languageData.GetContent("LesBénéficiaireEffectifSection_Line15")), yStartPoint += interline * 1.5f, 500 - 100, 40, 100);

                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsOffshore, yStartPoint += interline * 1.5f, 100, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 115);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsOffshore, yStartPoint, 150, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 165);
                instance.AddDefaultText(string.Format("{0} {1}", languageData.GetContent("LesBénéficiaireEffectifSection_Line16"), data.CustomObjectValue.OffshoreCountry), yStartPoint += interline, 500, 20, 100);

                instance.AddDefaultBoldText(languageData.GetContent("LesBénéficiaireEffectifSection_Line17"), yStartPoint += interline * 1.5f, 500, 20, 15);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsPPE, yStartPoint += interline, 35, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 50);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsPPE, yStartPoint, 85, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 105);

                /*instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line18"), yStartPoint + 340, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line19"), yStartPoint + 355, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line20"), yStartPoint + 370, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line21"), yStartPoint + 385, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line22"), yStartPoint + 400, 500, 20);
                */
                //string strBenef = String.Format(@"{0} {1} {2} {3} {4}",
                //    languageData.GetContent("LesBénéficiaireEffectifSection_Line18"),
                //    languageData.GetContent("LesBénéficiaireEffectifSection_Line19"),
                //    languageData.GetContent("LesBénéficiaireEffectifSection_Line20"),
                //    languageData.GetContent("LesBénéficiaireEffectifSection_Line21"),
                //    languageData.GetContent("LesBénéficiaireEffectifSection_Line22"));
                string strBenef = languageData.GetContent("LesBénéficiaireEffectifSection_Line18_1");
                instance.AddJustifyText(strBenef, yStartPoint += interline * 2, 500, 100); ;

                /*instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line23"), yStartPoint + 415, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line24"), yStartPoint + 430, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line25"), yStartPoint + 445, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line26"), yStartPoint + 460, 500, 20);
                instance.AddReceuil_DetailText_Justify_Calibri_Label(languageData.GetContent("LesBénéficiaireEffectifSection_Line27"), yStartPoint + 475, 500, 20);
                */
                instance.AddJustifyText(String.Format(@"{0} {1} {2} {3} {4}", languageData.GetContent("LesBénéficiaireEffectifSection_Line23"), languageData.GetContent("LesBénéficiaireEffectifSection_Line24"), languageData.GetContent("LesBénéficiaireEffectifSection_Line25"), languageData.GetContent("LesBénéficiaireEffectifSection_Line26"), languageData.GetContent("LesBénéficiaireEffectifSection_Line27")), yStartPoint += interline * 3.5f, 500, 100);

                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line28"), yStartPoint += interline * 3.5f, 500, 20, 15);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsBusinessRel, yStartPoint += interline, 35, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 55);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsBusinessRel, yStartPoint, 85, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 105);
                instance.AddDefaultText(languageData.GetContent("LesBénéficiaireEffectifSection_Line29"), yStartPoint += interline, 500, 20, 35);

                //added spacing
                //return yStartPoint + 545;
                return yStartPoint;
            }
            return yStartPoint;
        }
        private static float GeneratePMRLesPersonnesHabilitées(FoxitPDFGenerator instance, ReportOptionAttributeValue data, PageLanguageHelper languageData, float yStartPoint = 0)
        {
            if (data != null)
            {

                if (yStartPoint + 310 >= 700)
                {
                    instance.CreatePage();
                    yStartPoint = 0;
                }

                yStartPoint = yStartPoint + 20; //spacing

                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line1"), yStartPoint, 500, 20);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.Title, yStartPoint, 40, "2");
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line1_Item3"), yStartPoint, 500, 20, 60);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.Title, yStartPoint, 110, "1");
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line1_Item2"), yStartPoint, 500, 20, 130);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.Title, yStartPoint, 200, "3");
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line1_Item4"), yStartPoint, 500, 20, 220);

                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line2"), data.CustomObjectValue.Name), yStartPoint + 20, 500, 20);
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line2"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Name, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line3"), data.CustomObjectValue.FirstName), yStartPoint + 35, 500, 20);
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line3"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.FirstName, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PDFPM_telPortable"), data.CustomObjectValue.Phone), yStartPoint + 50, 500, 20);//tel
                instance.AddDefaultText(languageData.GetContent("PDFPM_telPortable"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Phone, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PDFPM_fax"), data.CustomObjectValue.Fax), yStartPoint + 65, 500, 20);//fax
                instance.AddDefaultText(languageData.GetContent("PDFPM_fax"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Fax, yStartPoint, answer_width, 20, answer_x);

                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PDFPM_email"), data.CustomObjectValue.Email), yStartPoint + 80, 500, 20);//email
                instance.AddDefaultText(languageData.GetContent("PDFPM_email"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Email, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(languageData.GetContent("PDFPM_adresse"), yStartPoint + 95, 500, 20);//adresse
                //instance.AddDefaultText(data.CustomObjectValue.Address, yStartPoint + 95, 400, 60, 50);//adresse
                instance.AddDefaultText(languageData.GetContent("PDFPM_adresse"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.MaidenName, yStartPoint, answer_width, 60, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PDFPM_cp"), data.CustomObjectValue.ZipCode), yStartPoint + 140, 500, 20);//cp
                instance.AddDefaultText(languageData.GetContent("PDFPM_cp"), yStartPoint += interline * 2.8f, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.ZipCode, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PDFPM_ville"), data.CustomObjectValue.City), yStartPoint + 155, 500, 20);//ville
                instance.AddDefaultText(languageData.GetContent("PDFPM_ville"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.City, yStartPoint, answer_width, 20, answer_x);

                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line4"), data.CustomObjectValue.DateOfBirth), yStartPoint + 170, 500, 20);
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line4"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.DateOfBirth, yStartPoint, answer_width, 20, answer_x);

                // instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line5"), data.CustomObjectValue.Function), yStartPoint + 185, 500, 20);
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line5"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Function, yStartPoint, answer_width, 20, answer_x);

                //instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line6"), data.CustomObjectValue.Nationality), yStartPoint + 200, 500, 20);
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line6"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Nationality, yStartPoint, answer_width, 20, answer_x);

                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsResident, yStartPoint += interline, 0, "1");
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line7_Item1"), yStartPoint, 500, 20, 15);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsResident, yStartPoint, 80, "2");
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line7_Item2"), yStartPoint, 500, 20, 95);

                //   instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line8"), data.CustomObjectValue.Country), yStartPoint + 230, 500, 20);
                //instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line9"), yStartPoint + 245, 500, 20, 100);
                //instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line10"), yStartPoint + 260, 500, 20, 100);
                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line8"), yStartPoint += interline, label_width, height);
                instance.AddAnswer(data.CustomObjectValue.Country, yStartPoint, answer_width, 20, answer_x);

                instance.AddBlueBorder(yStartPoint += 25, 70, 400, 92);
                instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line9"), languageData.GetContent("PersonnesHabiliteesSection_Line10")), yStartPoint += 10, 380, 40, 80);

                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsFATF, yStartPoint += interline * 1.5f, 100, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 120);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsFATF, yStartPoint, 150, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 170);


                //instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line11"), yStartPoint + 290, 500, 20, 100);
                //instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line12"), yStartPoint + 305, 500, 20, 100);
                instance.AddDefaultText(String.Format(@"{0} : {1}", languageData.GetContent("PersonnesHabiliteesSection_Line11"), languageData.GetContent("PersonnesHabiliteesSection_Line12")), yStartPoint += interline, 380, 40, 80);

                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsOffshore, yStartPoint += interline * 1.5f, 100, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 115);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsOffshore, yStartPoint, 150, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 165);

                instance.AddDefaultText(languageData.GetContent("PersonnesHabiliteesSection_Line13"), yStartPoint += interline * 1.8f, 500, 20);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsOwner, yStartPoint += interline, 0, "1");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_Yes_Caps"), yStartPoint, 500, 20, 15);
                ReportBL.PlotBooleanValue(instance, data.CustomObjectValue.IsOwner, yStartPoint, 50, "2");
                instance.AddDefaultText(languageData.GetContent("Report_Symbol_No_Caps"), yStartPoint, 500, 20, 65);
                instance.AddReference(languageData.GetContent("PersonnesHabiliteesSection_Line14"), yStartPoint += interline * 1.3f, 500, 20);

                return yStartPoint + 380;
            }
            //added spacing
            return yStartPoint;
        }
        public List<ReportOptionAttributeValue> RetrieveCustomDataTypeValues(OptionAttribute _optionAttribute, Guid _idReport)
        {
            List<ReportOptionAttributeValue> retVal = new List<ReportOptionAttributeValue>();

            //List<string> customAttribute = new List<string>();
            List<string> customAttribute = OptionBL.GetCustomAttributeNames(_optionAttribute.Datatype);

            if (customAttribute.Count > 0)
            {
                string param_Prefix = string.Format("{0}_{1}_{2}", _optionAttribute.Datatype.ToLower(), _optionAttribute.idOption, _optionAttribute.idOptionAttribute);
                var paramList = Request.Params.AllKeys.Where(s => s.StartsWith(param_Prefix));

                //int entryCount = paramList.Count() / customAttribute.Count; TODO : For knowledgelevet, this condition doesn't work                 
                int entryCount = paramList.Count();

                int entryCountFinal = paramList.Where(x => x.Contains(customAttribute[0])).Count();
                if (entryCountFinal > 0)
                {
                    entryCount = entryCountFinal;
                }

                for (int i = 0; i < entryCount; i++)
                {
                    dynamic _customData = new Upsilab.Data.Model.CustomObject();
                    foreach (string _attr in customAttribute)
                    {
                        string _strVal = string.Empty;
                        string param = string.Format("{0}_{1}", param_Prefix, _attr);
                        if (_optionAttribute.SingleOption.HasValue && !_optionAttribute.SingleOption.Value)
                        {
                            param = string.Format("{0}_{1}_{2}", param_Prefix, i, _attr);
                        }
                        if (!string.IsNullOrEmpty(Request.Params[param]))
                        {
                            _strVal = Request.Params[param];
                        }
                        CustomObject.SetValueByPropertyName(_customData, _attr, _strVal);
                    }
                    ReportOptionAttributeValue newVal = new ReportOptionAttributeValue();
                    newVal.idOptionAttribute = _optionAttribute.idOptionAttribute;
                    newVal.idReport = _idReport;
                    newVal.CustomObjectValue = _customData;
                    retVal.Add(newVal);
                }
            }

            return retVal;
        }
        public List<ReportOptionAttributeValue> GetAttributValueFromPostData(RecueilModel _dataModel, int idOption)
        {
            List<ReportOptionAttributeValue> retVal = new List<ReportOptionAttributeValue>();

            Option targetOption = _dataModel.Option.Where(o => o.idOption.Equals(idOption)).FirstOrDefault();

            if (targetOption.OptionAttribute != null)
            {
                foreach (var optAttr in targetOption.OptionAttribute)
                {
                    string idPrefix = string.Empty;
                    string dataType = optAttr.Datatype.ToLower();
                    bool isBasicDataType = true;

                    if (dataType.Equals("string") || dataType.Equals("multiline") || dataType.Equals("mobilephone")) idPrefix = "txt_{0}_{1}";
                    else if (dataType.Equals("int") || dataType.Equals("float") || dataType.Equals("percent")) idPrefix = "txt_{0}_{1}";
                    else if (dataType.Equals("datetime")) idPrefix = "dt_{0}_{1}";
                    else if (dataType.Equals("profession")) idPrefix = "enum_{0}_{1}";
                    else if (dataType.Equals("country") || dataType.Equals("industry") || dataType.Equals("profession"))
                        idPrefix = "enum_{0}_{1}";
                    else isBasicDataType = false;

                    if (isBasicDataType)
                    {
                        string ParamName = string.Format(idPrefix, optAttr.idOption, optAttr.idOptionAttribute);

                        if (!string.IsNullOrEmpty(Request.Params[ParamName]))
                        {
                            string strVal = Request.Params[ParamName];
                            //strVal = strVal.Replace("'", "''");
                            ReportOptionAttributeValue newVal = new ReportOptionAttributeValue();
                            newVal.idOptionAttribute = optAttr.idOptionAttribute;
                            newVal.idReport = _dataModel.Report.idReport;
                            newVal.Value = strVal;
                            retVal.Add(newVal);
                        }
                    }
                    else
                    {
                        retVal.AddRange(RetrieveCustomDataTypeValues(optAttr, _dataModel.Report.idReport));
                    }
                }
            }

            return retVal;
        }