public ActionResult UtilisateurPartial_Update(FirmInstitutionAdviser _adviserData)
        {
            try
            {
                int idFirmAdviser = Convert.ToInt16(Request.Params["idFirmInstitutionAdviser"].ToString());
                string userName = Request.Params["User.UserName"].ToString();
                string userFirstName = Request.Params["User.UserFirstName"].ToString();
                string userEmail = Request.Params["User.UserEmail"].ToString();
                string userMobile = Request.Params["User.UserMobilePhone"].ToString();
                int idProfil = Convert.ToInt32(Request.Params["User.idUserProfile"]);

                bool hasReport = false;
                try { hasReport = _adviserData.HasReport; }
                catch { hasReport = true; };

                bool hasLab = false;
                try { hasLab = _adviserData.HasLAB; }
                catch { hasLab = true; };

                Guid gIdLicenseReport = Guid.Empty;
                Guid gIdLicenseLab = Guid.Empty;

                string sIdLicenseReport = string.Empty;
                try { sIdLicenseReport = Request.Params["User.IdLicenseReport"].ToString(); }
                catch { };

                string sIdLicenseLab = string.Empty;
                try { sIdLicenseLab = Request.Params["User.IdLicenseLab"].ToString(); }
                catch { };

                if (!string.IsNullOrEmpty(sIdLicenseReport))
                    Guid.TryParse(sIdLicenseReport, out gIdLicenseReport);

                if (!string.IsNullOrEmpty(sIdLicenseLab))
                    Guid.TryParse(sIdLicenseLab, out gIdLicenseLab);

                Guid idUser = Guid.Empty;
                Guid.TryParse(Request.Params["User.idUser"].ToString(), out idUser);

                User objUserToModify = UserBL.GetUserById(idUser);

                if (!UserBL.IsEmailUsed(userEmail, objUserToModify) || objUserToModify.UserEmail.CompareTo(userEmail) == 0)
                {
                    //_adviserData.idUser = FirmInstitutionAdviserBL.GetAdviserById(_adviserData.idFirmInstitutionAdviser).idUser;

                    //_adviserData.User.idUser = _adviserData.idUser;
                    //_adviserData.User.idUserProfile = UserProfileBL.GetAllUserProfiles().Where(up => up.UserProfileName.ToLower().Equals("adviser")).FirstOrDefault().idUserProfile;
                    //_adviserData.User.IsActive = true;
                    //_adviserData.User.UserLogin = _adviserData.User.UserEmail;

                    //_adviserData.idFirmInstitution = Business.Utility.SessionManager.GetFirmInstitutionSession().idFirmInstitution;

                    //FirmInstitutionAdviserBL.UpdateAdviser(_adviserData);

                    #region Création des Adviser par rapport aux firminstitions séléctionnées
                    // Modification de l'User en question
                    objUserToModify.IsActive = true;
                    objUserToModify.UserEmail = userEmail;
                    objUserToModify.UserName = userName;
                    objUserToModify.UserFirstName = userFirstName;
                    objUserToModify.UserMobilePhone = userMobile;
                    objUserToModify.idUserProfile = idProfil;

                    if (gIdLicenseLab != Guid.Empty && hasLab)
                        objUserToModify.IdLicenseLab = gIdLicenseLab;
                    else if ((gIdLicenseLab == Guid.Empty && hasLab) || (gIdLicenseLab != Guid.Empty && hasLab))
                        return Content(string.Format("<span id='spanError'>{0}</span>", LanguageData.GetContent("Merci_de_séléctionner_une_license_lab")));

                    if (gIdLicenseReport != Guid.Empty && hasReport)
                        objUserToModify.IdLicenseReport = gIdLicenseReport;
                    else if ((hasReport && gIdLicenseReport == Guid.Empty) || (hasReport && gIdLicenseReport != Guid.Empty))
                        return Content(string.Format("<span id='spanError'>{0}</span>", LanguageData.GetContent("Merc_de_séléctionner_une_license_report")));

                    User userModified = UserBL.UpdateUser(objUserToModify);

                   
                    // Suppression des Adviser rattaché à l'iduser selectionné
                    FirmInstitutionAdviserBL.DeleteFirmInstitutionAdviserByIdUser(idUser);

                    Guid idCurrentFirm = SessionManager.GetFirmInstitutionSession().idFirmInstitution;

                    string _FirmInstitutions = Request.Params["FirmIdsEdit"].ToString();
                    if (!string.IsNullOrEmpty(_FirmInstitutions))
                    {
                        string[] firmIds = _FirmInstitutions.Trim(',').Split(',');

                        foreach (var item in firmIds)
                        {
                            Guid idF = Guid.Empty;

                            bool res = Guid.TryParse(item, out idF);
                            if (res)
                            {
                                FirmInstitution f = FirmInstitutionBL.GetFirmInstitutionByIdFirmInstitution(idF);

                                FirmInstitutionAdviser currAdviser = new FirmInstitutionAdviser();
                                currAdviser.User = userModified; //FirmInstitutionAdviserBL.GetAdviserById(_adviserData.idFirmInstitutionAdviser).idUser;
                                currAdviser.HasReport = hasReport;
                                currAdviser.HasLAB = hasLab;
                                currAdviser.idFirmInstitutionParent = idCurrentFirm;

                                Business.Configuration.FirmInstitutionAdviserBL.CreateAdviserWithoutUser(f, currAdviser);
                            }
                        }
                    }
                    #endregion

                    /// License ---> User
                    User _user = UserBL.GetHeavyUserById(userModified.idUser);
                    bool updateLicenseLAB = false;
                    bool updateLicenseReport = false;
                    Guid? oldLabLicense = _user.IdLicenseLab;
                    Guid? oldReportLicense = _user.IdLicenseReport;
                    if (oldLabLicense != _adviserData.User.IdLicenseLab)
                    {
                        _user.IdLicenseLab = _adviserData.User.IdLicenseLab;
                        updateLicenseLAB = true;
                    }
                    if (oldReportLicense != _adviserData.User.IdLicenseReport)
                    {
                        _user.IdLicenseReport = _adviserData.User.IdLicenseReport;
                        updateLicenseReport = true;
                    }
                    if (updateLicenseLAB || updateLicenseReport)
                        UserBL.UpdateUser(_user);

                    //Update user in session if the user changed = user connected
                    var currentUser = SessionManager.GetUserSession();
                    if (currentUser.idUser == _user.idUser)
                        SessionManager.SetUserSession(_user);

                    /// Mise à jour de la date d'utilisation des licenses si modif
                    if (_user.IdLicenseLab.HasValue && updateLicenseLAB)
                    {
                        LicenseBL.UpdateUsedDate(_user.IdLicenseLab.Value);
                    }

                    if (_user.IdLicenseReport.HasValue && updateLicenseReport)
                    {
                        LicenseBL.UpdateUsedDate(_user.IdLicenseReport.Value);
                    }

                    if (!string.IsNullOrEmpty(Request.Params["ResetEmail"]))
                    {
                        string outputMsg = string.Empty;
                        UserBL.SendResetPasswordEmail(_adviserData.idUser, out outputMsg);
                    }
                }
                else
                {
                    return Content("<span id='spanError'>" + LanguageData.GetContent("FirmInst_UserMail_Exist") + "</span>");
                }
            }
            catch (Exception ex)
            {
                return Content("<span id='spanError'>" + ex.Message + "</span>");
            }
            return PartialView("UserPartial", GetUsers());
        }
        public ActionResult Create(FirmInstitutionAdviser _adviser)
        {

            string _FirmInstitutions = Request.Params["_firminstitutionIds"].ToString();
            string _UserToCreateEmail = Request.Params["_UserToCreateEmail"].ToString();
            string _UserToCreateMobile = Request.Params["_UserToCreateMobile"].ToString();
            string User_UserFirstName = Request.Params["_UserToCreateFirstName"].ToString();
            string User_UserName = Request.Params["_UserToCreateName"].ToString();
            bool _HasReport = Convert.ToBoolean(Request.Params["_HasReport"].ToString());
            bool _HasLab = Convert.ToBoolean(Request.Params["_HasLab"].ToString());
            int _UserProfilId = Convert.ToInt32(Request.Params["_UserProfil"]);

            Guid gIdLicenseReport = Guid.Empty;
            Guid gIdLicenseLab = Guid.Empty;

            string sIdLicenseReport = string.Empty;
            try { sIdLicenseReport = Request.Params["_UserLicenceReport"].ToString(); }
            catch { };

            string sIdLicenseLab = string.Empty;
            try { sIdLicenseLab = Request.Params["_UserLicenceLab"].ToString(); }
            catch { };

            if (!string.IsNullOrEmpty(sIdLicenseReport))
                Guid.TryParse(sIdLicenseReport, out gIdLicenseReport);

            if (!string.IsNullOrEmpty(sIdLicenseLab))
                Guid.TryParse(sIdLicenseLab, out gIdLicenseLab);

            // create user function here
            if (!string.IsNullOrEmpty(_UserToCreateEmail) && !UserBL.IsEmailUsed(_UserToCreateEmail))
            {
                /*
                 * il doit etre impossible d'initialiser un nouvel utilisateur si "Recuiel" ou bien "LAB" n'ont pas été coché (au moins une case) 
                 * ET une license correspondante affectée
                 */
                if ((_HasReport && gIdLicenseReport != Guid.Empty) || (_HasLab && gIdLicenseLab != Guid.Empty))
                {
                    User objUser = new User();
                    objUser.idUser = GuidHelper.GenerateGuid();
                    objUser.idUser = Business.Utility.GuidHelper.GenerateGuid();
                    // objUser.idUserProfile = UserProfileBL.GetAllUserProfiles().Where(up => up.UserProfileName.ToLower().Equals("adviser")).FirstOrDefault().idUserProfile;
                    objUser.idUserProfile = _UserProfilId;
                    objUser.DateCreated = DateTime.Now;
                    objUser.IsActive = true;
                    objUser.UserLogin = _UserToCreateEmail;
                    objUser.UserPassword = ""; //Temporary set
                    objUser.UserName = User_UserName;
                    objUser.UserFirstName = User_UserFirstName;
                    objUser.UserMobilePhone = _UserToCreateMobile; //Temporary set
                    objUser.UserEmail = _UserToCreateEmail;
                    
                    if (gIdLicenseReport == Guid.Empty)
                        objUser.IdLicenseReport = null;
                    else
                        objUser.IdLicenseReport = gIdLicenseReport;

                    if (gIdLicenseLab == Guid.Empty)
                        objUser.IdLicenseLab = null;
                    else
                        objUser.IdLicenseLab = gIdLicenseLab;

                    User userCreated = UserBL.CreateUser(objUser, "");

                    /// Mise à jour de la date d'utilisation des licenses si modif
                    if (gIdLicenseLab != Guid.Empty && objUser.IdLicenseLab.HasValue)
                    {
                        LicenseBL.UpdateUsedDate(objUser.IdLicenseLab.Value);
                    }

                    if (gIdLicenseReport != Guid.Empty && objUser.IdLicenseReport.HasValue)
                    {
                        LicenseBL.UpdateUsedDate(objUser.IdLicenseReport.Value);
                    }

                    //_adviser.User.idUser = Business.Utility.GuidHelper.GenerateGuid();
                    //_adviser.User.idUserProfile = UserProfileBL.GetAllUserProfiles().Where(up => up.UserProfileName.ToLower().Equals("adviser")).FirstOrDefault().idUserProfile;
                    //_adviser.User.DateCreated = DateTime.Now;
                    //_adviser.User.IsActive = true;
                    //_adviser.User.UserLogin = _adviser.User.UserEmail;

                    //_adviser.User.UserPassword = ""; //Temporary set
                    ////_adviser.User.DateExpired = DateTime.Now.AddYears(10);//get from License

                    #region Création des Adviser par rapport aux firminstitions séléctionnées
                    FirmInstitution currentFirm = SessionManager.GetFirmInstitutionSession();
                    Guid idCurrentFirm = currentFirm.idFirmInstitution;

                    if (!string.IsNullOrEmpty(_FirmInstitutions))
                    {
                        string[] firmIds = _FirmInstitutions.Trim(',').Split(',');

                        foreach (var item in firmIds)
                        {
                            Guid idF = Guid.Empty;

                            bool res = Guid.TryParse(item, out idF);
                            if (res)
                            {
                                FirmInstitution f = FirmInstitutionBL.GetFirmInstitutionByIdFirmInstitution(idF);
                                FirmInstitutionAdviser currAdviser = new FirmInstitutionAdviser();
                                currAdviser.User = userCreated; //FirmInstitutionAdviserBL.GetAdviserById(_adviserData.idFirmInstitutionAdviser).idUser;
                                currAdviser.HasReport = _HasReport;
                                currAdviser.HasLAB = _HasLab;
                                currAdviser.idFirmInstitutionParent = idCurrentFirm;

                                Business.Configuration.FirmInstitutionAdviserBL.CreateAdviserWithoutUser(f, currAdviser);
                            }
                        }
                    }
                    else // mettre currentFirm
                    {
                        FirmInstitutionAdviser currAdviser = new FirmInstitutionAdviser();
                        currAdviser.User = userCreated;
                        currAdviser.HasReport = _HasReport;
                        currAdviser.HasLAB = _HasLab;
                        Business.Configuration.FirmInstitutionAdviserBL.CreateAdviserWithoutUser(currentFirm, currAdviser);
                    }
                    #endregion

                    string outputMsg = string.Empty;
                    UserBL.SendDefinePasswordEmail(userCreated, out outputMsg);

                    //var _user = _adviser.User;
                    //UserBL.CreateUser(_user, _user.UserPassword);
                    //FirmInstitutionBL.AddUserToFirmInstitution(_user, Business.Utility.SessionManager.GetFirmInstitutionSession());

                    //return Json(_adviser, JsonRequestBehavior.AllowGet);

                }
                else
                {
                    return Content(LanguageData.GetContent("FirmInst_check_licence"));
                }
            }
            else
            {
                return Content(LanguageData.GetContent("FirmInst_UserMail_Exist"));
            }

            IList<FirmInstitutionAdviser> lstFA = GetUsers();
            return PartialView("UserPartial", lstFA);
        }
        private IList<FirmInstitutionAdviser> GetUsers()
        {
            var SessionInst = Upsilab.Business.Utility.SessionManager.GetFirmInstitutionSession();
            var firm = Business.Utility.SessionManager.GetFirmInstitutionSession();
            var currentUser = Business.Utility.SessionManager.GetUserSession();
            ViewBag.IsAdmin = currentUser.IsAdmin() ? 1 : 0;
            //Gestion de l'adviser correspondant à l'admin
            if (currentUser.IsAdmin() && !FirmInstitutionAdviserBL.AdminHasAdviser(currentUser))
            {
                FirmInstitutionAdviser _adv = new FirmInstitutionAdviser();

                _adv.idUser = currentUser.idUser;
                _adv.idFirmInstitution = firm.idFirmInstitution;
                _adv.DateCreated = DateTime.Now;
                //_adv.IsActive = true;
                Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, currentUser);
            }

            //var retVal = Business.Configuration.FirmInstitutionAdviserBL.GetAdvisers(firm, false);
            bool filterAdvisersByUserFirm = false;
            var retVal = Business.Configuration.FirmInstitutionAdviserBL.GetAdvisersByIdFirmParent(firm, currentUser, filterAdvisersByUserFirm, false);

            if (retVal != null)
            {
                retVal = retVal.GroupBy(a => a.idUser).Select(ad => ad.First()).ToList<FirmInstitutionAdviser>();
            }

            ViewBag.Firm = firm;
            ViewBag.CurrentUser = currentUser;

            ViewBag.TotalLABCount = 0;
            ViewBag.TotalLABUsedCount = 0;
            ViewBag.TotalReportCount = 0;
            ViewBag.TotalReportUsedCount = 0;

            IDictionary<string, int> dicoLicenseLAB = FirmInstitutionBL.NbLicenseCount(SessionManager.GetFirmInstitutionSession().idFirmInstitution, LicenseBL.LabId);
            IDictionary<string, int> dicoLicenseReport = FirmInstitutionBL.NbLicenseCount(SessionManager.GetFirmInstitutionSession().idFirmInstitution, LicenseBL.ReportId);

            if (dicoLicenseLAB.ContainsKey("Total") && dicoLicenseLAB.ContainsKey("Used"))
            {
                ViewBag.TotalLABCount = dicoLicenseLAB["Total"];
                ViewBag.TotalLABUsedCount = dicoLicenseLAB["Used"];
            }

            if (dicoLicenseReport.ContainsKey("Total") && dicoLicenseReport.ContainsKey("Used"))
            {
                ViewBag.TotalReportCount = dicoLicenseReport["Total"];
                ViewBag.TotalReportUsedCount = dicoLicenseReport["Used"];
            }

            string byLetter = Request.Form["letter"];
            string bySearchValue = Request.Form["keyword"];

            if (!string.IsNullOrEmpty(byLetter))
            {
                return retVal.Where(e => e.User.UserName.ToLower().StartsWith(byLetter.ToLower())).ToList();
            }
            else if (!string.IsNullOrEmpty(bySearchValue))
            {
                return retVal.Where(e => e.User.UserName.ToLower().Contains(bySearchValue.ToLower())).ToList();
            }
            return retVal;
        }
        private IList<FirmInstitutionAdviser> GetUsers(string SearchValue, bool isLetter)
        {
            var firm = Business.Utility.SessionManager.GetFirmInstitutionSession();
            var currentUser = Business.Utility.SessionManager.GetUserSession();
            ViewBag.IsAdmin = currentUser.IsAdmin() ? 1 : 0;
            //Gestion de l'adviser correspondant à l'admin
            if (currentUser.IsAdmin() && !FirmInstitutionAdviserBL.AdminHasAdviser(currentUser))
            {
                FirmInstitutionAdviser _adv = new FirmInstitutionAdviser();

                _adv.idUser = currentUser.idUser;
                if (firm != null)
                {
                    _adv.idFirmInstitution = firm.idFirmInstitution;
                }
                _adv.DateCreated = DateTime.Now;
                //_adv.IsActive = true;
                Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, currentUser);
            }

            //var retVal = Business.Configuration.FirmInstitutionAdviserBL.GetAdvisers(firm, false);
            bool filterAdvisersByUserFirm = (currentUser.IsAdministrativeAssistant()) ? true : false;
            var retVal = Business.Configuration.FirmInstitutionAdviserBL.GetAdvisersByIdFirmParent(firm, currentUser, filterAdvisersByUserFirm, false);

            if (retVal != null)
            {
                retVal = retVal.GroupBy(a => a.idUser).Select(ad => ad.First()).ToList<FirmInstitutionAdviser>();
            }

            ViewBag.Firm = firm;
            ViewBag.CurrentUser = currentUser;

            ViewBag.TotalLABCount = 0;
            ViewBag.TotalLABUsedCount = 0;
            ViewBag.TotalReportCount = 0;
            ViewBag.TotalReportUsedCount = 0;

            IDictionary<string, int> dicoLicenseLAB = FirmInstitutionBL.NbLicenseCount(SessionManager.GetFirmInstitutionSession().idFirmInstitution, LicenseBL.LabId);
            IDictionary<string, int> dicoLicenseReport = FirmInstitutionBL.NbLicenseCount(SessionManager.GetFirmInstitutionSession().idFirmInstitution, LicenseBL.ReportId);

            if (dicoLicenseLAB.ContainsKey("Total") && dicoLicenseLAB.ContainsKey("Used"))
            {
                ViewBag.TotalLABCount = dicoLicenseLAB["Total"];
                ViewBag.TotalLABUsedCount = dicoLicenseLAB["Used"];
            }

            if (dicoLicenseReport.ContainsKey("Total") && dicoLicenseReport.ContainsKey("Used"))
            {
                ViewBag.TotalReportCount = dicoLicenseReport["Total"];
                ViewBag.TotalReportUsedCount = dicoLicenseReport["Used"];
            }

            if (!string.IsNullOrEmpty(SearchValue) || !string.IsNullOrEmpty(this.SearchNameD))
            {
                if (isLetter)
                {
                    if (SearchValue.Length == 1)
                        return retVal.Where(e => e.User.UserName.ToLower().StartsWith(SearchValue.ToLower())).ToList();
                    else // -->showAll/ no pagination
                    {
                        ViewBag.ShowAll = "1";
                    }
                    this.SearchNameD = string.Empty;
                }
                else
                {
                    return retVal.Where(e => e.User.UserName.ToLower().Contains(this.SearchNameD.ToLower())).ToList();
                }

            }
            return retVal;
        }
        public static FirmInstitutionAdviser UpdateAdviser(FirmInstitutionAdviser _adviser)
        {
            if (!UserBL.IsEmailUsed(_adviser.User.UserEmail, _adviser.User))
            {
                var userToBeUpdated = User.UserBL.GetUserById(_adviser.idUser);
                userToBeUpdated.UserName = _adviser.User.UserName;
                userToBeUpdated.UserFirstName = _adviser.User.UserFirstName;
                userToBeUpdated.UserEmail = _adviser.User.UserEmail;
                userToBeUpdated.UserMobilePhone = _adviser.User.UserMobilePhone;

                User.UserBL.UpdateUser(userToBeUpdated);
                var adviserToBeUpdated = GetAdviserById(_adviser.idFirmInstitutionAdviser);
                adviserToBeUpdated.HasLAB = _adviser.HasLAB;
                adviserToBeUpdated.HasReport = _adviser.HasReport;
                using (UpsilabEntities updateContext = new UpsilabEntities())
                {
                    updateContext.FirmInstitutionAdviser.Attach(adviserToBeUpdated);
                    updateContext.ObjectStateManager.ChangeObjectState(adviserToBeUpdated, System.Data.EntityState.Modified);
                    updateContext.SaveChanges();
                }
            }
            return _adviser;
        }
 public static void DeleteAdviser(FirmInstitutionAdviser _adviser)
 {
     UserBL.DeleteUser(_adviser.User);
 }
        public static FirmInstitutionAdviser CreateSignatory(Guid idFirmInstitution, Data.Model.User user, bool isDefaultSignatory, UpsilabEntities context)
        {
            var adviser = new FirmInstitutionAdviser
            {
                idFirmInstitution = idFirmInstitution,
                idFirmInstitutionParent = idFirmInstitution,
                idUser = user.idUser,
                IsDefaultSignatory = isDefaultSignatory,
                DateCreated = DateTime.Now,                
            };

            context.FirmInstitutionAdviser.AddObject(adviser);
            context.SaveChanges();

            return adviser;
        }
        public ActionResult Configuration(UserConfigurationModel objUC)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var languageData = Upsilab.Business.Utility.PageLanguageHelper.GetLanguageContent("Public", "Configuration");

                    // si l'objet existe bien, et que les 2 mots de passe correspondent bien, on enregistre le USER
                    if (objUC != null && objUC.Password.CompareTo(objUC.PasswordConfirmation) == 0)
                    {
                        // Tester si l'email est deja existant
                        if (!UserBL.IsEmailUsed(objUC.Email)) //Ne pas tester l'email d'un client final
                        {
                            UserProfile objUserProfile = UserProfileBL.GetUserProfileByProfileName(UserProfileBL.Administrator);

                            if (objUserProfile != null)
                            {

                                if (UserBL.ValidatePassword(objUC.Password))
                                {
                                    if (!UserBL.IsEmailUsed(objUC.Email))
                                    {
                                        #region "Enregistrement de l'USER"
                                        Upsilab.Data.Model.User objUser = new Upsilab.Data.Model.User()
                                        {
                                            idUser = Guid.NewGuid(),
                                            idUserProfile = objUserProfile.idUserProfile,
                                            UserLogin = objUC.Email,
                                            UserPassword = objUC.Password,
                                            UserEmail = objUC.Email,
                                            UserName = objUC.UserName,
                                            UserFirstName = objUC.UserFirstName,
                                            UserMobilePhone = objUC.UserMobilePhone,
                                            DateCreated = DateTime.Now,
                                            IsActive = true
                                        };

                                        UserBL.CreateUser(objUser, objUC.Password);



                                        #endregion

                                        FirmInstitution objFI = FirmInstitutionBL.GetFirmInstitutionByIdFirmInstitution(objUC.IdFirmInstitution);

                                        #region Création de l'adviser correspondant à l'admin

                                        FirmInstitutionAdviser _adv = new FirmInstitutionAdviser()
                                        {

                                            idUser = objUser.idUser,
                                            idFirmInstitution = objFI.idFirmInstitution,
                                            idFirmInstitutionParent = objFI.idFirmInstitution,
                                            DateCreated = DateTime.Now,
                                        };

                                        Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, objUser);

                                        #endregion

                                        #region "Mise à jour de la FirmInstitution (ajout de IdUserCreated)"
                                        if (objFI != null)
                                        {
                                            objFI.idUserCreated = objUser.idUser;

                                            using (UpsilabEntities context = new UpsilabEntities())
                                            {
                                                context.FirmInstitution.Attach(objFI);
                                                context.ObjectStateManager.ChangeObjectState(objFI, System.Data.EntityState.Modified);
                                                context.SaveChanges();
                                            }
                                        }
                                        #endregion

                                        #region "Envoi de mail de remerciement"
                                        //Ne plus envoyer l'email #8072
                                        //if (objFI != null)
                                        //{
                                        //    Subscription objSubscription = db.Subscription.Where(sub => sub.IdSubscription == objUC.IdSubscription).FirstOrDefault();
                                        //    SouscriptionBL.SendInvoiceMail(objSubscription, false); //Send to Admin
                                        //}
                                        //else
                                        //{
                                        //    ViewBag.Info = languageData.GetContent("Config_MailError");
                                        //}
                                        #endregion

                                        ViewBag.Info = languageData.GetContent("Config_Saved");

                                        //If all is OK, log on the Admnistrator to the Extranet User
                                        if (SessionManager.Exists(UserBL.UserIdSessionKey))
                                        {
                                            SessionManager.Clear(UserBL.UserIdSessionKey);
                                        }

                                        SessionManager.Add<Guid>(objUser.idUser, UserBL.UserIdSessionKey);

                                        return RedirectToAction("AuthentificationExtranetUser", "Utilisateur");
                                    } // Fin test password
                                }
                                else
                                {

                                    ViewBag.Info = string.Format("{0}<br/>", languageData.GetContent("mot_de_passe_obligatoirement"));
                                    ViewBag.Info += string.Format("- {0}<br/>", languageData.GetContent("mot_de_passe_longueur_minimale"));
                                    ViewBag.Info += string.Format("- {0}<br/>", languageData.GetContent("mot_de_passe_uniquement_chiffre_et_lettres"));
                                    ViewBag.Info += string.Format("- {0}<br/>", languageData.GetContent("mot_de_passe_au_moins_2_chiffre"));
                                    ViewBag.Info += string.Format("{0}<br/>", languageData.GetContent("mot_de_passe_sensible_a_la_casse"));
                                }
                            } // Fin test profil
                            else
                            {
                                ViewBag.Info = languageData.GetContent("Config_ProfilError");
                            }
                        } //Fin test email existant
                        else
                        {
                            ViewBag.Info = languageData.GetContent("Config_UsedMail"); ;
                        }
                    }
                    else
                    {
                        ViewBag.Info = languageData.GetContent("Config_PwConfirmError");
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Info = "Erreur: " + ex.Message;
            }

            return View();
        }
        public ActionResult Configuration(UserSAConfigurationModel objUC)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var languageData = Upsilab.Business.Utility.PageLanguageHelper.GetLanguageContent("Public", "Configuration");

                    // Tester si l'email est deja existant
                    User user = UserBL.GetUserByEmail(objUC.Email);

                    if (user == null) //Si non existant
                    {
                        UserProfile objUserProfile = UserProfileBL.GetUserProfileByProfileName(UserProfileBL.Administrator);

                        if (objUserProfile != null)
                        {

                            if (!UserBL.IsEmailUsed(objUC.Email))
                            {
                                #region "Enregistrement de l'USER"
                                Upsilab.Data.Model.User objUser = new Upsilab.Data.Model.User()
                                {
                                    idUser = Guid.NewGuid(),
                                    idUserProfile = objUserProfile.idUserProfile,
                                    UserLogin = objUC.Email,
                                    UserPassword = string.Empty, //objUC.Password
                                    UserEmail = objUC.Email,
                                    UserName = objUC.UserName,
                                    UserFirstName = objUC.UserFirstName,
                                    UserMobilePhone = objUC.UserMobilePhone,
                                    DateCreated = DateTime.Now,
                                    IsActive = true
                                };

                                UserBL.CreateUser(objUser, objUser.UserPassword);
                                #endregion

                                FirmInstitution firmInstitution = FirmInstitutionBL.GetFirmInstitutionByIdFirmInstitution(objUC.IdFirmInstitution);

                                #region Création de l'adviser correspondant à l'admin

                                FirmInstitutionAdviser _adv = new FirmInstitutionAdviser()
                                {
                                    idUser = objUser.idUser,
                                    idFirmInstitution = firmInstitution.idFirmInstitution,
                                    idFirmInstitutionParent = firmInstitution.idFirmInstitution,
                                    DateCreated = DateTime.Now,
                                };

                                Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, objUser);

                                #endregion

                                if (firmInstitution != null)
                                {
                                    #region "Mise à jour de la FirmInstitution (ajout de IdUserCreated)"
                                    firmInstitution.idUserCreated = objUser.idUser;

                                    using (UpsilabEntities context = new UpsilabEntities())
                                    {
                                        context.FirmInstitution.Attach(firmInstitution);
                                        context.ObjectStateManager.ChangeObjectState(firmInstitution, System.Data.EntityState.Modified);
                                        context.SaveChanges();
                                    }

                                    SessionManager.SetSelectedFirmInstitutionBySuperAdmin(firmInstitution);

                                    #endregion

                                    Subscription currentSubscription = SouscriptionBL.GetSubscriptionsById(objUC.IdSubscription);

                                    #region "Envoi de mail"
                                    if (currentSubscription.IsPaid)
                                    {
                                        //Send mail
                                        try
                                        {
                                            //Ne plus envoyer d'email au contact facturation
                                            //bool sendToFirmInstituion = true;
                                            //SouscriptionBL.SendInvoiceMail(currentSubscription, sendToFirmInstituion); //Send to contact facturation (not to admin)

                                            ///Envoi mail de réinitalisation de mot de passe et de confirmation commande à l'admin
                                            ///+ set date envoi email
                                            //string returnMessage;
                                            //UserBL.SendResetPasswordEmail(objUser, out returnMessage);
                                            SouscriptionBL.SendAccessActivationEmail(currentSubscription);
                                        }
                                        catch (Exception ex)
                                        {
                                            Upsilab.Business.Log.Log.AppendException(ex);
                                        }

                                        //Set date send mail
                                        currentSubscription.DateSendEmail = DateTime.Now;
                                        SouscriptionBL.UpdateSubscription(currentSubscription);
                                    }
                                    #endregion
                                }

                                ViewBag.Info = languageData.GetContent("Config_Saved");

                                //Souscription OK : TODO
                                IDictionary<string, string> dicoRes = new Dictionary<string, string>();

                                dicoRes.Add("Page_title", LanguageData.GetContent("Page_title"));
                                dicoRes.Add("Title_h1", LanguageData.GetContent("Title_h1"));
                                dicoRes.Add("Title_h1_span", LanguageData.GetContent("Title_h1_span"));
                                dicoRes.Add("Table_Title", LanguageData.GetContent("Table_Title_ok"));
                                dicoRes.Add("Message", LanguageData.GetContent("Message_ok"));
                                dicoRes.Add("ProductType", SouscriptionBL.Product_Type_Recueil_lab);

                                TempData["DicoRetour"] = dicoRes;
                                return RedirectToAction("Retour");

                            }

                            else
                            {
                                ViewBag.Info = string.Format("{0}<br/>", languageData.GetContent("mot_de_passe_obligatoirement"));
                                ViewBag.Info += string.Format("- {0}<br/>", languageData.GetContent("mot_de_passe_longueur_minimale"));
                                ViewBag.Info += string.Format("- {0}<br/>", languageData.GetContent("mot_de_passe_uniquement_chiffre_et_lettres"));
                                ViewBag.Info += string.Format("- {0}<br/>", languageData.GetContent("mot_de_passe_au_moins_2_chiffre"));
                                ViewBag.Info += string.Format("{0}<br/>", languageData.GetContent("mot_de_passe_sensible_a_la_casse"));
                            }
                        } // Fin test profil
                        else
                        {
                            ViewBag.Info = languageData.GetContent("Config_ProfilError");
                        }
                    } //Fin test email existant
                    else
                    {
                        ViewBag.Info = languageData.GetContent("Config_UsedMail"); ;
                    }
                }

            }
            catch (Exception ex)
            {
                ViewBag.Info = "Erreur: " + ex.Message;
            }

            return View("UnLogiciel_Configuration", objUC);
        }
        public static bool CreateAdminAdviser(FirmInstitutionAdviser _adviser, Upsilab.Data.Model.User _user)
        {
            bool retVal = true;
            var licenseLAB = FirmInstitutionBL.GetAvailableLicensesByType(_adviser.idFirmInstitution, Upsilab.Business.Souscription.LicenseBL.LabId);
            var licenseRecueil = FirmInstitutionBL.GetAvailableLicensesByType(_adviser.idFirmInstitution, Upsilab.Business.Souscription.LicenseBL.ReportId);

            if (licenseLAB.Count > 0)
            {
                _user.IdLicenseLab = licenseLAB[0].idLicense;
                //  _adviser.User.IdLicenseLab = licenseLAB[0].idLicense;
                _adviser.HasLAB = true;
            }

            if (licenseRecueil.Count > 0)
            {
                _user.IdLicenseReport = licenseRecueil[0].idLicense;
                //_adviser.User.IdLicenseReport = licenseRecueil[0].idLicense;
                _adviser.HasReport = true;
            }

            using (Data.Model.UpsilabEntities context = new UpsilabEntities())
            {
                context.FirmInstitutionAdviser.AddObject(_adviser);
                context.SaveChanges();

                //Affectation license LAB et Recueil pour l'adviser
                context.User.Attach(_user);
                context.ObjectStateManager.ChangeObjectState(_adviser.User, System.Data.EntityState.Modified);
                context.SaveChanges();
            }
            return retVal;
        }
        public static Boolean AddUserToFirmInstitution(Data.Model.User user, Data.Model.FirmInstitution firmInstitution)
        {
            using (Data.Model.UpsilabEntities createContext = new UpsilabEntities())
            {
                Data.Model.FirmInstitutionAdviser adviser = new FirmInstitutionAdviser();
                adviser.idFirmInstitution = firmInstitution.idFirmInstitution;
                adviser.idUser = user.idUser;
                adviser.DateCreated = DateTime.Now;

                createContext.FirmInstitutionAdviser.AddObject(adviser);
                createContext.SaveChanges();
            }
            return true;
        }
        private IList<FirmInstitution> GetEtablissement(string SearchValue, bool isLetter)
        {
            var firm = Business.Utility.SessionManager.GetFirmInstitutionSession();
            var currentUser = Business.Utility.SessionManager.GetUserSession();
            ViewBag.IsAdmin = currentUser.IsAdmin() ? 1 : 0;

            #region Gestion de l'adviser correspondant à l'admin

            if (currentUser.IsAdmin() && !FirmInstitutionAdviserBL.AdminHasAdviser(currentUser))
            {
                FirmInstitutionAdviser _adv = new FirmInstitutionAdviser();

                _adv.idUser = currentUser.idUser;
                _adv.idFirmInstitution = firm.idFirmInstitution;
                _adv.DateCreated = DateTime.Now;
                //_adv.IsActive = true;
                Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, currentUser);
            }
            #endregion

            ViewBag.Firm = firm;
            ViewBag.CurrentUser = currentUser;
            List<FirmInstitution> retVal = new List<FirmInstitution>();
            if (currentUser.IsFirmAdmin())
            {
                //établissements rattachés à l'utilisateur
                IList<Guid> lstUsersFirm = Upsilab.Business.Configuration.FirmInstitutionAdviserBL.GetAdviserByUserId(currentUser.idUser).Select(f => f.idFirmInstitution).ToList();
                retVal = Business.Configuration.FirmInstitutionBL.GetAllFirmInstitutions().Where(f => lstUsersFirm.Contains(f.idFirmInstitution)).ToList();
            }
            else
            {
                retVal = Business.Configuration.FirmInstitutionBL.GetAllFirmInstitutions().Where(f => f.FirmInstitutionParent == firm.idFirmInstitution || f.idFirmInstitution == firm.idFirmInstitution).ToList();
            }
            if (!string.IsNullOrEmpty(SearchValue) || !string.IsNullOrEmpty(this.SearchNameD))
            {
                if (isLetter)
                {
                    if (SearchValue.Length == 1)
                        return retVal.Where(e => e.FirmInstitutionName.ToLower().StartsWith(SearchValue.ToLower())).ToList();
                    else // -->showAll/ no pagination
                    {
                        ViewBag.ShowAll = "1";
                    }
                    this.SearchNameD = string.Empty;
                }
                else
                {
                    return retVal.Where(e => e.FirmInstitutionName.ToLower().Contains(this.SearchNameD.ToLower())).ToList();
                }

            }
            return retVal;
        }
        private IList<FirmInstitution> GetEtablissement()
        {
            var firm = Business.Utility.SessionManager.GetFirmInstitutionSession();
            var currentUser = Business.Utility.SessionManager.GetUserSession();
            ViewBag.IsAdmin = currentUser.IsAdmin() ? 1 : 0;

            //Gestion de l'adviser correspondant à l'admin
            if (currentUser.IsAdmin() && !FirmInstitutionAdviserBL.AdminHasAdviser(currentUser))
            {
                FirmInstitutionAdviser _adv = new FirmInstitutionAdviser();

                _adv.idUser = currentUser.idUser;
                _adv.idFirmInstitution = firm.idFirmInstitution;
                _adv.DateCreated = DateTime.Now;
                //_adv.IsActive = true;
                Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, currentUser);
            }

            List<FirmInstitution> retVal = new List<FirmInstitution>();
            if (currentUser.IsFirmAdmin())
            {
                //établissements rattachés à l'utilisateur
                IList<Guid> lstUsersFirm = Upsilab.Business.Configuration.FirmInstitutionAdviserBL.GetAdviserByUserId(currentUser.idUser).Select(f => f.idFirmInstitution).ToList();
                retVal = Business.Configuration.FirmInstitutionBL.GetAllFirmInstitutions().Where(f => lstUsersFirm.Contains(f.idFirmInstitution)).ToList();
            }
            else
            {
                retVal = Business.Configuration.FirmInstitutionBL.GetAllFirmInstitutions().Where(f => f.FirmInstitutionParent == firm.idFirmInstitution || f.idFirmInstitution == firm.idFirmInstitution).ToList();
            }
            ViewBag.Firm = firm;
            ViewBag.CurrentUser = currentUser;

            string byLetter = Request.Form["letter"];
            string bySearchValue = Request.Form["keyword"];

            if (!string.IsNullOrEmpty(byLetter))
            {
                return retVal.Where(e => e.FirmInstitutionName.ToLower().StartsWith(byLetter.ToLower())).ToList();
            }
            else if (!string.IsNullOrEmpty(bySearchValue))
            {
                return retVal.Where(e => e.FirmInstitutionName.ToLower().Contains(bySearchValue.ToLower())).ToList();
            }
            return retVal;
        }
        public string ResetPassword(FirmInstitutionAdviser _adviserFromPost)
        {
            try
            {
                FirmInstitutionAdviser adviserFromDB = FirmInstitutionAdviserBL.GetAdviserById(_adviserFromPost.idFirmInstitutionAdviser);

                if (adviserFromDB.User != null)
                {
                    string outputMsg = string.Empty;

                    UserBL.SendResetPasswordEmail(adviserFromDB.User, out outputMsg);

                    return outputMsg;
                }
                else
                {
                    return LanguageData.GetContent("Impossible_réinitialiser_mdp");
                }
            }
            catch (Exception ex)
            {
                return LanguageData.GetContent("réinitialsation_mdp_échoué") + ex.Message;
            }

        }
        public static bool CreateAdviserWithoutUser(FirmInstitution _firmInstitution, FirmInstitutionAdviser _adviser)
        {
            bool retVal = true;

            using (Data.Model.UpsilabEntities createContext = new UpsilabEntities())
            {
                Data.Model.FirmInstitutionAdviser adviser = new FirmInstitutionAdviser();
                adviser.idFirmInstitution = _firmInstitution.idFirmInstitution;
                adviser.idUser = _adviser.User.idUser;
                adviser.DateCreated = DateTime.Now;

                adviser.HasLAB = _adviser.HasLAB;
                adviser.HasReport = _adviser.HasReport;
                adviser.idFirmInstitutionParent = _adviser.idFirmInstitutionParent;

                createContext.FirmInstitutionAdviser.AddObject(adviser);
                createContext.SaveChanges();
            }

            return retVal;
        }
        public ActionResult Configuration(UserConfigurationModel objUC)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var languageData = PageLanguageHelper.GetLanguageContent("Public", "Configuration");

                    // si l'objet existe bien, et que les 2 mots de passe correspondent bien, on enregistre le USER
                    if (objUC != null && objUC.Password.CompareTo(objUC.PasswordConfirmation) == 0)
                    {
                        // Tester si l'email est deja existant
                        User user = UserBL.GetUserByEmail(objUC.Email);

                        if (user == null) //Si non existant
                        {
                            UserProfile objUserProfile = UserProfileBL.GetUserProfileByProfileName(UserProfileBL.Administrator);

                            if (objUserProfile != null)
                            {

                                if (UserBL.ValidatePassword(objUC.Password))
                                {
                                    if (!UserBL.IsEmailUsed(objUC.Email))
                                    {
                                        #region "Enregistrement de l'USER"
                                        Upsilab.Data.Model.User objUser = new Upsilab.Data.Model.User()
                                        {
                                            idUser = Guid.NewGuid(),
                                            idUserProfile = objUserProfile.idUserProfile,
                                            UserLogin = objUC.Email,
                                            UserPassword = objUC.Password,
                                            UserEmail = objUC.Email,
                                            UserName = objUC.UserName,
                                            UserFirstName = objUC.UserFirstName,
                                            UserMobilePhone = objUC.UserMobilePhone,
                                            DateCreated = DateTime.Now,
                                            IsActive = true
                                        };

                                        UserBL.CreateUser(objUser, objUC.Password);



                                        #endregion

                                        FirmInstitution objFI = FirmInstitutionBL.GetFirmInstitutionByIdFirmInstitution(objUC.IdFirmInstitution);

                                        #region Création de l'adviser correspondant à l'admin

                                        FirmInstitutionAdviser _adv = new FirmInstitutionAdviser();

                                        _adv.idUser = objUser.idUser;
                                        _adv.idFirmInstitution = objFI.idFirmInstitution;
                                        _adv.DateCreated = DateTime.Now;
                                        Business.Configuration.FirmInstitutionAdviserBL.CreateAdminAdviser(_adv, objUser);

                                        #endregion

                                        #region "Mise à jour de la FirmInstitution (ajout de IdUserCreated)"
                                        if (objFI != null)
                                        {
                                            objFI.idUserCreated = objUser.idUser;

                                            using (UpsilabEntities context = new UpsilabEntities())
                                            {
                                                context.FirmInstitution.Attach(objFI);
                                                context.ObjectStateManager.ChangeObjectState(objFI, System.Data.EntityState.Modified);
                                                context.SaveChanges();
                                            }
                                        }
                                        #endregion

                                        #region "Envoi de mail de remerciement"
                                        if (objFI != null)
                                        {
                                            Subscription objSubscription = db.Subscription.Where(sub => sub.IdSubscription == objUC.IdSubscription).FirstOrDefault();
                                            SouscriptionBL.SendInvoiceMail(objSubscription, false); //Send to Admin
                                        }
                                        else
                                        {
                                            ViewBag.Info = languageData.GetContent("Config_MailError");
                                        }
                                        #endregion


                                        ViewBag.Info = "Enregistrement réussi.";

                                        //If all is OK, log on the Admnistrator to the Extranet User
                                        if (SessionManager.Exists(UserBL.UserIdSessionKey))
                                        {
                                            SessionManager.Clear(UserBL.UserIdSessionKey);
                                        }

                                        SessionManager.Add<Guid>(objUser.idUser, UserBL.UserIdSessionKey);

                                        return RedirectToAction("AuthentificationExtranetUser", "Utilisateur");
                                    } // Fin test password
                                }
                                else
                                {

                                    ViewBag.Info = languageData.GetContent("Config_PwFormatError");
                                }
                            } // Fin test profil
                            else
                            {
                                ViewBag.Info = languageData.GetContent("Config_ProfilError");
                            }
                        } //Fin test email existant
                        else
                        {
                            ViewBag.Info = "Cette adresse email est déjà enregistrée dans le système.";
                        }
                    }
                    else
                    {
                        ViewBag.Info = languageData.GetContent("Config_PwConfirmError");
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Info = "Erreur: " + ex.Message;
            }

            return View();
        }
        public static Guid CreateCgp(Guid idUserCreator, FirmInstitutionAdviser fiAdviser)
        {
            try
            {
                using (var ctx = new UpsilabEntities())
                {
                    if (fiAdviser != null)
                    {
                        /* if user already created, just create relationship */

                        var pvdGuid = Guid.NewGuid();
                        if (fiAdviser.idUser != Guid.Empty && fiAdviser.idFirmInstitution != Guid.Empty)
                        {
                            /* si la liaison n'existe pas encore */
                            if (!ctx.ProviderUserCGPUser.Any(
                                    p => p.IdUser == fiAdviser.idUser && p.IdUserCreator == idUserCreator))
                            {
                                var providerUserCgpUser = new ProviderUserCGPUser()
                                {
                                    Id = pvdGuid,
                                    IdUser = fiAdviser.idUser,
                                    IdUserCreator = idUserCreator,
                                    IsDeleted = false,
                                    DateCreated = DateTime.Now,
                                    
                                };
                                ctx.ProviderUserCGPUser.AddObject(providerUserCgpUser);
                            }
                       
                        }
                        else if (fiAdviser!=null && fiAdviser.idUser != Guid.Empty && fiAdviser.idFirmInstitution == Guid.Empty)
                        {
                            /* First step : Create institution */
                            var fi = new FirmInstitution();
                            fi.FirmInstitutionName = fiAdviser.FirmInstitution.FirmInstitutionName;
                            fi.idFirmInstitution = Guid.NewGuid();
                            fi.idUserCreated = null;//SessionManager.GetUserSession().idUser;
                            fi.DateCreated = DateTime.Now;
                            fi.PrefixCodeSponsorship = 0;
                            fi.IdFirmInstitutionType = 1;
                            fi.LeaderBirthDay = (DateTime?)null;
                            FirmInstitutionBL.CreateFirmInstition(fi);

                            
                            
                            var ui = fiAdviser.User;
                            var fiAdv = new FirmInstitutionAdviser();
                            fiAdv.idFirmInstitution = fi.idFirmInstitution;
                            fiAdv.idFirmInstitutionParent = fi.idFirmInstitution;
                            fiAdv.idUser = ui.idUser;
                            fiAdv.DateCreated = DateTime.Now;
                            fiAdv.HasLAB = false;
                            fiAdv.HasReport = false;
                            /* Third step : Create relationship between FirmInstitution and User */
                            ctx.FirmInstitutionAdviser.AddObject(fiAdv);

                            /* Final step : Create relationship between User and Creator */

                            var providerUserCgpUser = new ProviderUserCGPUser()
                            {
                                Id = pvdGuid,
                                IdUser = ui.idUser,
                                IdUserCreator = idUserCreator,
                                IsDeleted = false,
                                DateCreated = DateTime.Now,
                            };
                            ctx.ProviderUserCGPUser.AddObject(providerUserCgpUser);
                            
                        }
                        else
                        {
                            /* Second step : Create user */
                            var ui = new MUser();
                                ui.UserEmail = fiAdviser.User.UserEmail;
                                ui.UserFirstName = fiAdviser.User.UserFirstName;
                                ui.UserName = fiAdviser.User.UserName;
                                ui.UserMobilePhone = fiAdviser.User.UserMobilePhone;
                                ui.idUserProfile = fiAdviser.User.idUserProfile;
                                ui.idUser = Guid.NewGuid();
                                ui.IsActive = true;
                                ui.UserLogin = fiAdviser.User.UserEmail;
                                ui.UserPassword = string.Empty;
                                var userCreated = UserBL.CreateUser(ui, string.Empty, ctx);
     

                            /* First step : Create institution */
                            var fi = new FirmInstitution();
                            fi.FirmInstitutionName = fiAdviser.FirmInstitution.FirmInstitutionName;
                            fi.idFirmInstitution = Guid.NewGuid();
                            fi.idUserCreated = null;//SessionManager.GetUserSession().idUser;
                            fi.DateCreated = DateTime.Now;
                            fi.PrefixCodeSponsorship = 0;
                            fi.IdFirmInstitutionType = 1;
                            fi.LeaderBirthDay = (DateTime?)null;
                            FirmInstitutionBL.CreateFirmInstition(fi);


                

                            if (userCreated != null)
                            {
                                var fiAdv = new FirmInstitutionAdviser();
                                fiAdv.idFirmInstitution = fi.idFirmInstitution;
                                fiAdv.idFirmInstitutionParent = fi.idFirmInstitution;
                                fiAdv.idUser = ui.idUser;
                                fiAdv.DateCreated = DateTime.Now;
                                fiAdv.HasLAB = false;
                                fiAdv.HasReport = false;
                                /* Third step : Create relationship between FirmInstitution and User */
                                ctx.FirmInstitutionAdviser.AddObject(fiAdv);

                                /* Final step : Create relationship between User and Creator */

                                var providerUserCgpUser = new ProviderUserCGPUser()
                                {
                                    Id = pvdGuid,
                                    IdUser = userCreated.idUser,
                                    IdUserCreator = idUserCreator,
                                    IsDeleted = false,
                                    DateCreated = DateTime.Now,
                                    TypeUserCreator = TypeUserCreatorEnum.FOURNISSEUR.ToString()
                                };
                                ctx.ProviderUserCGPUser.AddObject(providerUserCgpUser);
                            }
                        }
                        ctx.SaveChanges();
                        return pvdGuid;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }
            return Guid.Empty;
        }