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 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);
        }
        /// <summary>
        /// Check if current user can view page
        /// </summary>
        /// <returns></returns>
        private bool CanViewPage(User pUser)
        {
            bool canViewPage = true;
            UserProfile currentUserProfile = null;
            if (pUser != null)
            {
                currentUserProfile = UserProfileBL.GetUserProfile(pUser);
            }
            if (currentUserProfile == null)
            {
                canViewPage = false;
            }
            else
            {
                //Only administrator can access to the page
                if (!currentUserProfile.UserProfileName.Contains(UserProfileBL.Administrator))
                {
                    canViewPage = false;
                }
            }

            return canViewPage;
        }
        public static FirmInstitutionAdviser CreateSignatory(Guid idFirminstitution, Guid idUsercreated, string civility, string name, string firstname, string email, string mobilePhone)
        {
            using (Data.Model.UpsilabEntities context = new UpsilabEntities())
            {
                context.Connection.Open();
                using (var dbContextTransaction = context.Connection.BeginTransaction())
                {
                    try
                    {
                        //
                        //User profile
                        //
                        var idProfileCGPClient = 12; //"cgp_client" dans UserProfile
                        //
                        //User
                        //
                        var user = new Upsilab.Data.Model.User
                        {
                            idUser = Guid.NewGuid(),
                            idUserProfile = idProfileCGPClient,
                            UserLogin = email,
                            Civility = civility,
                            DateCreated = DateTime.Now,
                            UserEmail = email,
                            UserName = name,
                            UserFirstName = firstname,
                            UserMobilePhone = mobilePhone,
                            IsActive = true,
                            IsDeleted = false
                        };

                        user = UserBL.CreateUser(user, user.UserFirstName, context);
                        //
                        //Firm Adviser
                        //
                        var defaultSignatory = FirmInstitutionAdviserBL.GetDefaultSignatory(idFirminstitution);
                        var isDefaultSignatory = false;

                        if (defaultSignatory == null)
                        {
                            isDefaultSignatory = true;
                        }

                        var signatory = FirmInstitutionAdviserBL.CreateSignatory(idFirminstitution, user, isDefaultSignatory, context);

                        dbContextTransaction.Commit();
                        return signatory;
                    }
                    catch (Exception e)
                    {
                        dbContextTransaction.Rollback();
                        Log.Log.AppendException(e);
                        throw new Exception("SavingError");
                    }
                }
            }
        }
        /// <summary>
        /// Needs refactoring later. Never cathc Exception here, ALWAYSSSSS THROW
        /// </summary>
        /// <param name="row"></param>
        /// <param name="isUpdate"></param>
        private void ProcessRow_old(DataRow row, ImportO2SModel model, bool isUpdate, bool isUsedByManymore = false, Dictionary<string, Guid> fieldsMatching = null)
        {
            //if (!model.IsUpdateMode) // utiliser plutôt le param
            if (!isUpdate) //--> cas de l'initialisation
            {
                this.InsertProcess(row, model, isUsedByManymore, fieldsMatching);
            }
            else
            {
                string nom = this.GetNomClient(row, model.Nom);
                string prenom = this.GetPrenomClient(row, model.Prenom);
                string email = this.GetEmailClient(row, model.Email);
                string mobilePhone = this.GetPhoneClient(row, model.TelephoneMobile); //TODO: Verifier format du numero phone
                bool isPersonnePhysique = this.IsPersonnePhysique(row, model.TypePersonne);
                bool isCustomer = Convert.ToBoolean(model.IsCustomer);// this.IsCustomer(row, model.IsCustomer);
                string dateNaissance = this.GetDate(row, model.DateNaissance);
                string weddingDate = this.GetDate(row, model.WeddingDate);
                string PrivatePhone = this.GetPhoneClient(row, model.Telephone); //TODO: Verifier format du numero phone
                string ProfessionalPhone = this.GetPhoneClient(row, model.TelephoneProfessionnel); //TODO: Verifier format du numero phone
                string fax = !string.IsNullOrEmpty(model.Fax) ? this.CleanString(row[model.Fax].ToString()) : string.Empty;
                // string nationality = this

                if (string.IsNullOrEmpty(email))
                    email = string.Empty;//string.Format("{0}@{1}", (nom + prenom).Replace(" ", ""), User.DEFAULT_MAIL_DOMAIN);//supprimer espace

                //mobile phone
                if (string.IsNullOrEmpty(mobilePhone))
                    mobilePhone = User.DEFAULT_MOBILEPHONE;


                CustomerProspect pCustomerProspect = CustomerProspectBL.GetCustomerProspectByName(model.FirmInstitution.idFirmInstitution, prenom, nom);

                if (pCustomerProspect == null) //TODO
                {
                    this.InsertProcess(row, model, isUsedByManymore, fieldsMatching);
                }

                else
                {
                    User CustomerProspectCreator = new User();

                    Guid idUserCreator = Guid.Empty;

                    //Conseiller principal for Admin User
                    if (fieldsMatching != null && fieldsMatching.Count > 0)
                    {
                        string conseiller = this.CleanString(row[CONSEILLER_PRINCIPAL].ToString());
                        if (!string.IsNullOrEmpty(conseiller) && fieldsMatching.ContainsKey(conseiller))
                            idUserCreator = fieldsMatching[conseiller];
                    }
                    //Conseiller principal for Not Manymore
                    //markage
                    else if (/*isUsedByManymore && */!string.IsNullOrEmpty(model.ColumnConseillerPrincipal) && !String.IsNullOrEmpty(row[model.ColumnConseillerPrincipal].ToString()))
                    {
                        string conseiller = row[model.ColumnConseillerPrincipal].ToString().Trim();

                        CustomerProspectCreator = this.GetAdviser(conseiller, model.FirmInstitution);

                        if (CustomerProspectCreator != null)
                            idUserCreator = CustomerProspectCreator.idUser;
                    }
                    //Conseiller principal Manymore simple User or Not Manymore with non specified Adviser
                    //Or Take current User as Default Adviser if userCreated is empty
                    if (pCustomerProspect.idUserCreated == Guid.Empty)
                        idUserCreator = SessionManager.GetUserSession().idUser;


                    //check the owner
                    if (pCustomerProspect.idUserCreated == SessionManager.GetUserSession().idUser || pCustomerProspect.idUserCreated == idUserCreator)
                    {
                        if (idUserCreator != Guid.Empty)
                            pCustomerProspect.idUserCreated = idUserCreator;

                        //common parts from import
                        pCustomerProspect.User.UserName = nom;
                        pCustomerProspect.User.UserFirstName = prenom;
                        pCustomerProspect.User.UserEmail = email;//can change mail rght now                           
                        pCustomerProspect.User.UserMobilePhone = mobilePhone;
                        pCustomerProspect.ProfessionalPhone = ProfessionalPhone;
                        pCustomerProspect.PrivatePhone = PrivatePhone;
                        pCustomerProspect.Fax = fax;

                        //Default value personne physique if model.TypePersonne is null 
                        pCustomerProspect.IsCorporation = false;


                        if (!string.IsNullOrEmpty(model.TypePersonne))
                        {
                            pCustomerProspect.IsCorporation = !isPersonnePhysique;
                            //IF PM, set companyName = UserName
                            if (!isPersonnePhysique)
                                pCustomerProspect.CompanyName = nom;
                        }


                        pCustomerProspect.IsCustomer = isCustomer;

                        if (!string.IsNullOrEmpty(dateNaissance))
                        {
                            pCustomerProspect.DateOfBirth = Convert.ToDateTime(dateNaissance);
                            pCustomerProspect.User.DateOfBirth = Convert.ToDateTime(dateNaissance);
                        }

                        if (!string.IsNullOrEmpty(weddingDate))
                        {
                            pCustomerProspect.WeddingDate = Convert.ToDateTime(weddingDate);
                        }

                        pCustomerProspect.MobilePhone = mobilePhone;

                        try
                        {
                            pCustomerProspect.Title = this.CleanString(row[model.Title].ToString());
                        }
                        catch { }

                        try
                        {
                            pCustomerProspect.PlaceOfBirth = this.CleanString(row[model.LieuNaissance].ToString());
                        }
                        catch { }
                        try
                        {
                            string adress2 = !string.IsNullOrEmpty(model.Adresse2) ? this.CleanString(row[model.Adresse2].ToString()) : string.Empty;
                            pCustomerProspect.Adress = this.CleanString(row[model.Adresse].ToString());
                            if (!string.IsNullOrEmpty(adress2))
                            {
                                pCustomerProspect.Adress += Environment.NewLine + adress2;
                            }
                        }
                        catch { }
                        try
                        {
                            string resident = this.CleanString(row[model.Resident].ToString()).ToLower().Replace("é", "e").Replace("ç", "c");
                            if (resident == "francais" || resident == "resident" || resident == "r")
                            {
                                pCustomerProspect.IsResident = true;
                            }

                            if (resident == "non resident" || resident == "resident" || resident.ToLower() == "non r")
                            {
                                pCustomerProspect.IsResident = false;
                            }

                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.RefExtConjoint = this.CleanString(row[model.RefExtConjoint].ToString());
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.MarriageSettlement = this.CleanString(row[model.MarriageSettlement].ToString());
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.Liberality = this.CleanString(row[model.Liberalites].ToString());
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.MaidenName = this.CleanString(row[model.MaidenName].ToString());
                        }
                        catch { }


                        try
                        {
                            pCustomerProspect.City = this.CleanString(row[model.Ville].ToString());

                        }
                        catch { }
                        try
                        {
                            string country = this.CleanString(row[model.Pays].ToString());
                            if (country.ToUpper() == "FR")
                                country = "France";
                            pCustomerProspect.Country = country;
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.ZipCode = this.CleanString(row[model.CodePostal].ToString());
                        }
                        catch { }
                        try
                        {
                            string maritalStatus = this.CleanString(row[model.MaritalStatus].ToString());
                            pCustomerProspect.MaritalStatus = maritalStatus;
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.Nationality = this.CleanString(row[model.Nationality].ToString());
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.NumSIREN = this.CleanString(row[model.NumSIREN].ToString());
                        }
                        catch { }
                        try
                        {
                            if (pCustomerProspect.IsCorporation == true)
                            {
                                //Cabinet
                                //SC - Société civile
                                //Non définie
                                //SAS - Société anonyme par actions simplifiée
                                //SC - Société civile
                                //SARL - Société à responsabilité limitée

                                string legalForm = this.CleanString(row[model.LegalForm].ToString()).ToUpper();
                                string fiscalPlan = model.FiscalPlan == null ? string.Empty : this.CleanString(row[model.FiscalPlan].ToString()).ToUpper();

                                if (legalForm.Contains("EURL"))
                                    pCustomerProspect.LegalForm = "EURL";

                                else if (legalForm.Contains("SARL") || legalForm.Contains("S.A.R.L."))
                                    pCustomerProspect.LegalForm = "SARL";

                                else if (legalForm.Contains("SAS") || legalForm.Contains("S.A.S."))
                                    pCustomerProspect.LegalForm = "SAS";

                                else if (legalForm.Contains("SA") || legalForm.Contains("S.A."))
                                    pCustomerProspect.LegalForm = "SA";

                                else if (legalForm.Contains("ASSOCIATION"))
                                {
                                    if (fiscalPlan.Contains("IR"))
                                        pCustomerProspect.LegalForm = "Association_IR"; //Association - IR
                                    else if (fiscalPlan.Contains("IS"))
                                        pCustomerProspect.LegalForm = "Association_IS";//Association - IS
                                    else
                                        pCustomerProspect.LegalForm = "Association";
                                }

                                else if ((legalForm.Contains("SC") || legalForm.Contains("S.C.")) && !legalForm.Contains("S.C.I."))
                                {
                                    //#4303
                                    if (fiscalPlan.Contains("IR"))
                                        pCustomerProspect.LegalForm = "SC_IR"; //societe civile - impot sur le revenu
                                    else if (fiscalPlan.Contains("IS"))
                                        pCustomerProspect.LegalForm = "SC_IS";//societe civile - IS
                                    else
                                        pCustomerProspect.LegalForm = "SC";

                                }
                                //Autre
                                else
                                {
                                    if (fiscalPlan.Contains("IR"))
                                        pCustomerProspect.LegalForm = "Autre_IR"; //Autre - IR
                                    else if (fiscalPlan.Contains("IS"))
                                        pCustomerProspect.LegalForm = "Autre_IS";//Autre - IS
                                    else
                                        pCustomerProspect.LegalForm = "Autre";

                                    pCustomerProspect.LegalForm_Autre = this.CleanString(row[model.LegalForm].ToString()); //legalForm is upper :)
                                }
                            }
                        }
                        catch { }
                        try
                        {
                            string date = this.GetDate(row, model.RelationshipBeginingDate);
                            if (!string.IsNullOrEmpty(date))
                                pCustomerProspect.RelationshipBeginingDate = Convert.ToDateTime(date);
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.RiskProfile = this.CleanString(row[model.RiskProfile].ToString());
                        }
                        catch { }
                        try
                        {
                            string legalCapacity = this.CleanString(row[model.LegalCapacity].ToString());
                            pCustomerProspect.LegalCapacity = legalCapacity;
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.Profession = this.CleanString(row[model.Profession].ToString());
                        }
                        catch { }
                        try
                        {
                            pCustomerProspect.RefExt = this.CleanString(row[model.RefExt].ToString());
                        }
                        catch { }
                        UserBL.UpdateUser(pCustomerProspect.User);
                        CustomerProspectBL.Update(pCustomerProspect);


                    }
                    else
                    {
                        //throw new Exception(string.Format("{0} {1} - User existant et appartenant à un autre CGP ", nom, prenom));
                        //Update : A customer may be assigned to many Advisors, so insert it ?
                        this.InsertProcess(row, model, isUsedByManymore, fieldsMatching);
                    }
                }

            }

        }
        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 ActionResult ImportClientAgregateur(ImportClientAgregateur model)
        {
            try
            {
                int clientimporte = 0;
                int clientAimporte = 0;
                model.IsEndImport = true;
                Guid idCgpAgreg = SessionManager.GetUserSession().idAgregCGP.Value;
                if (Request.Form["chkClient"] != null)
                {
                    string[] clientIdList = Request.Form["chkClient"].ToString().Split(',');
                    clientAimporte = clientIdList.Count();
                    string ImportMode = Request.Form["ImportMode"].ToString();
                    List<ImportErrorModel> lsterror = new List<ImportErrorModel>();
                    using (UpsilabEntities context = new UpsilabEntities())
                    {
                        //cas d'initialisation
                        if (ImportMode == "0")
                        {
                            List<CustomerProspect> listecustomer = context.CustomerProspect.Where(c => c.User1.idAgregCGP == idCgpAgreg).ToList();
                            if (listecustomer.Count > 0)
                            {
                                foreach (CustomerProspect customer in listecustomer)
                                {
                                    var user = customer.User;
                                    user.IsDeleted = true;
                                    user.IsActive = false;
                                    user.DateDeleted = DateTime.Now;
                                    user.DateExpired = DateTime.Now;
                                    customer.isDeleted = true;
                                }
                            }
                        }
                        //fin

                        foreach (string sId in clientIdList)
                        {
                            Guid clientId = new Guid(sId);
                            //get client agreg
                            ag_upsideo_client currentClientAgreg = context.ag_upsideo_client.Where(c => c.idclient == clientId && c.deleted != "o").FirstOrDefault();
                            //get client recueil/lab si existe
                            if (currentClientAgreg != null)
                            {
                                string nomclient = string.IsNullOrEmpty(currentClientAgreg.nomclient) ? "" : currentClientAgreg.nomclient.ToLower();
                                string prenomclient = string.IsNullOrEmpty(currentClientAgreg.prenomclient) ? "" : currentClientAgreg.prenomclient.ToLower();
                                CustomerProspect currentcustomer = context.CustomerProspect.Where(c => c.User1.idAgregCGP == idCgpAgreg && c.User.UserName.ToLower() == nomclient && c.User.UserFirstName.ToLower() == prenomclient && (!c.isDeleted.HasValue || (c.isDeleted.HasValue && !c.isDeleted.Value))).FirstOrDefault();
                                switch (ImportMode)
                                {
                                    case "0":
                                        try
                                        {
                                            /*if (currentcustomer != null )
                                            {
                                                //supprimer
                                                currentcustomer.isDeleted = true;
                                                currentcustomer.User.IsDeleted = true;                                            
                                            }*/
                                            User usernow = new User()
                                            {
                                                idUser = Guid.NewGuid(),
                                                idUserProfile = 8,
                                                UserPassword = "",
                                                UserName = currentClientAgreg.nomclient,
                                                UserFirstName = currentClientAgreg.prenomclient,
                                                IsActive = true,
                                                DateCreated = DateTime.Now,
                                                IsDeleted = false,
                                                CGVOk = true,
                                                HasReadMessage = false,
                                                ReceiveLicenseRemind = false,
                                            };

                                            context.User.AddObject(usernow);

                                            CustomerProspect customernow = new CustomerProspect()
                                            {
                                                idCustomer = Guid.NewGuid(),
                                                idFirmInstitution = model.idFirmInstitution.Value,
                                                DateCreated = DateTime.Now,
                                                IdUser = usernow.idUser,
                                                IsCustomer = model.IsCustomer,
                                                idUserCreated = SessionManager.GetUserSession().idUser,
                                                IsAlertRecipientClient = false,
                                                Adress = currentClientAgreg.adr,
                                                ZipCode = currentClientAgreg.cp,
                                                City = currentClientAgreg.ville,
                                                DateOfBirth = currentClientAgreg.ddn,
                                                FiscalAddrress = currentClientAgreg.adr2,
                                                Title = currentClientAgreg.titre,
                                                idAgregClient = currentClientAgreg.idclient,
                                                IsCorporation = false,
                                                isDeleted = false,
                                            };

                                            context.CustomerProspect.AddObject(customernow);

                                            clientimporte = clientimporte + 1;
                                        }
                                        catch (Exception ex)
                                        {
                                            ImportErrorModel err = new ImportErrorModel()
                                            {
                                                Name = currentClientAgreg.nomclient,
                                                FirstName = currentClientAgreg.prenomclient,
                                                Error = ex.Message
                                            };
                                            lsterror.Add(err);
                                        }
                                        break;
                                    case "1":
                                        try
                                        {
                                            if (currentcustomer != null)
                                            {
                                                currentcustomer.idAgregClient = currentClientAgreg.idclient;
                                                /*currentcustomer.Adress = currentClientAgreg.adr;
                                                currentcustomer.ZipCode = currentClientAgreg.cp;
                                                currentcustomer.City = currentClientAgreg.ville;                                           
                                                currentcustomer.FiscalAddrress = currentClientAgreg.adr2;*/

                                            }
                                            else
                                            {
                                                User usernow1 = new User()
                                                {
                                                    idUser = Guid.NewGuid(),
                                                    idUserProfile = 8,
                                                    UserPassword = "",
                                                    UserName = currentClientAgreg.nomclient,
                                                    UserFirstName = currentClientAgreg.prenomclient,
                                                    IsActive = true,
                                                    DateCreated = DateTime.Now,
                                                    IsDeleted = false,
                                                    CGVOk = true,
                                                    HasReadMessage = false,
                                                    ReceiveLicenseRemind = false
                                                };

                                                context.User.AddObject(usernow1);

                                                CustomerProspect customernow1 = new CustomerProspect()
                                                {
                                                    idCustomer = Guid.NewGuid(),
                                                    idFirmInstitution = model.idFirmInstitution.Value,
                                                    DateCreated = DateTime.Now,
                                                    IdUser = usernow1.idUser,
                                                    IsCustomer = model.IsCustomer,
                                                    idUserCreated = SessionManager.GetUserSession().idUser,
                                                    IsAlertRecipientClient = false,
                                                    Adress = currentClientAgreg.adr,
                                                    ZipCode = currentClientAgreg.cp,
                                                    City = currentClientAgreg.ville,
                                                    DateOfBirth = currentClientAgreg.ddn,
                                                    FiscalAddrress = currentClientAgreg.adr2,
                                                    Title = currentClientAgreg.titre,
                                                    idAgregClient = currentClientAgreg.idclient,
                                                    isDeleted = false

                                                };
                                                context.CustomerProspect.AddObject(customernow1);
                                            }
                                            clientimporte = clientimporte + 1;
                                        }
                                        catch (Exception ex)
                                        {
                                            ImportErrorModel err = new ImportErrorModel()
                                            {
                                                Name = currentClientAgreg.nomclient,
                                                FirstName = currentClientAgreg.prenomclient,
                                                Error = ex.Message
                                            };
                                            lsterror.Add(err);
                                        }
                                        break;
                                    case "2":
                                        try
                                        {
                                            if (currentcustomer == null)
                                            {
                                                User usernow2 = new User()
                                                {
                                                    idUser = Guid.NewGuid(),
                                                    idUserProfile = 8,
                                                    UserPassword = "",
                                                    UserName = currentClientAgreg.nomclient,
                                                    UserFirstName = currentClientAgreg.prenomclient,
                                                    IsActive = true,
                                                    DateCreated = DateTime.Now,
                                                    IsDeleted = false,
                                                    CGVOk = true,
                                                    HasReadMessage = false,
                                                    ReceiveLicenseRemind = false
                                                };

                                                context.User.AddObject(usernow2);

                                                CustomerProspect customernow2 = new CustomerProspect()
                                                {
                                                    idCustomer = Guid.NewGuid(),
                                                    idFirmInstitution = model.idFirmInstitution.Value,
                                                    DateCreated = DateTime.Now,
                                                    IdUser = usernow2.idUser,
                                                    IsCustomer = model.IsCustomer,
                                                    idUserCreated = SessionManager.GetUserSession().idUser,
                                                    IsAlertRecipientClient = false,
                                                    Adress = currentClientAgreg.adr,
                                                    ZipCode = currentClientAgreg.cp,
                                                    City = currentClientAgreg.ville,
                                                    DateOfBirth = currentClientAgreg.ddn,
                                                    FiscalAddrress = currentClientAgreg.adr2,
                                                    Title = currentClientAgreg.titre,
                                                    idAgregClient = currentClientAgreg.idclient,
                                                    isDeleted = false

                                                };
                                                context.CustomerProspect.AddObject(customernow2);

                                                clientimporte = clientimporte + 1;
                                            }
                                            else
                                            {
                                                ImportErrorModel err = new ImportErrorModel()
                                                {
                                                    Name = currentClientAgreg.nomclient,
                                                    FirstName = currentClientAgreg.prenomclient,
                                                    Error = "Le client existe déjà"
                                                };
                                                lsterror.Add(err);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            ImportErrorModel err = new ImportErrorModel()
                                            {
                                                Name = currentClientAgreg.nomclient,
                                                FirstName = currentClientAgreg.prenomclient,
                                                Error = ex.Message
                                            };
                                            lsterror.Add(err);
                                        }
                                        break;
                                    default:
                                        break;
                                }

                            }
                        }
                        context.SaveChanges();
                        model.Message = string.Format("{0} client(s) importé(s) sur {1}", clientimporte.ToString(), clientAimporte.ToString());
                        model.ListeErreur = lsterror;
                    }

                }
                else
                {
                    model.Message = "Pas de client importé.";
                }

                return View("Agregateur", model);

            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
                model.Message = ex.Message;
            }
            return View("Agregateur", model);
        }
        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 static Guid UpdateCgp(MUser user, FirmInstitution firmInstitution)
 {
     try
     {
         // TODO
     }
     catch (Exception ex)
     {
         Log.Log.AppendException(ex);
     }
     return Guid.Empty;
 }
        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;
        }
Esempio n. 11
0
        private static void ProcessUser(User user)
        {


            try
            {

                string statusInProgress = LABStudy.StatusEnum.InProgress.ToString();
                string statusCompleted = LABStudy.StatusEnum.Completed.ToString();
                string statusSentToCoffreFort = LABStudy.StatusEnum.SentToCoffreFort.ToString();
                bool isSendTocoffreOk = false;




                ////////            


                {

                    //     System.Console.WriteLine("\nTraitement de l'utilisateur : {0} {1}", user.UserName, user.UserFirstName);

                    //     int randomNumber = Rand();
                    _Log.Trace("Starting thread  for {0} {1} from  iteration {2} Thread count : {3} ", user.UserName, user.UserFirstName, _IterationId, _countThread);

                    //     Thread.Sleep(randomNumber);

                    //     _LstOfCommand.Enqueue(new GuidAction() { guid = user.idUser, action = "remove" });
                    //   autoEvent.Set();
                    // _Log.Trace("Ending thread  for {0} {1} from  iteration {2}", user.UserName, user.UserFirstName, _IterationId);

                }
                //  return;

                //////

                //liste des CustomerProspectLABModel par utilisateur
                List<CustomerProspectLABModel> lstCustomerLABModels = new List<CustomerProspectLABModel>();
                lstCustomerLABModels = LABStudyBL.GetCustomerLABModelInProgress(user.idUser);

                //boucle sur liste customer
                LABModel labModelNow = null;
                LABStudy labStudyNow = null;

                List<Guid> lstFailingGuid = new List<Guid>();


                foreach (CustomerProspectLABModel customerLabModel in lstCustomerLABModels)
                {
                    try
                    {
                        using (UpsilabEntities db = new UpsilabEntities())
                        {
                            //LABModel d'un utilisateur en cour  
                            labModelNow = new LABModel();
                            labModelNow = db.LABModel.Where(l => l.idUser == user.idUser && l.idLABModel == customerLabModel.idLABModel).FirstOrDefault();

                            //copy LABModel vers LABStudy
                            labStudyNow = new LABStudy()
                            {
                                idLABStudy = GuidHelper.GenerateGuid(),
                                idCustomer = customerLabModel.idCustomerProspect,
                                DateCreated = DateTime.Now,
                                DateUpdated = DateTime.Now,
                                Status = statusInProgress,
                                idRisk = labModelNow.idRisk,
                                idVigilance = labModelNow.idVigilance
                            };

                            db.LABStudy.AddObject(labStudyNow);
                            _Log.Trace("\nApplication du modele LAB : {0} au client : {1} {2}", labModelNow.Name, customerLabModel.CustomerProspect.Name, customerLabModel.CustomerProspect.User.UserFirstName);

                            //liste des question/reponse (LABAnswerModel)
                            List<LABAnswerModel> lstanswermodel = new List<LABAnswerModel>();
                            lstanswermodel = db.LABAnswerModel.Where(lam => lam.idLABModel == labModelNow.idLABModel).ToList();
                            //copy LABAnswerModel vers LABAnswer
                            foreach (LABAnswerModel lam in lstanswermodel)
                            {
                                LABAnswer LABAnswerNow = new LABAnswer()
                                {
                                    idLABAnswer = GuidHelper.GenerateGuid(),
                                    idLABStudy = labStudyNow.idLABStudy,
                                    idLABQuestion = lam.idLABQuestion,
                                    idResponse = lam.idResponse,
                                    idRisk = lam.idRisk,
                                    idVigilance = lam.idVigilance,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = DateTime.Now
                                };

                                db.LABAnswer.AddObject(LABAnswerNow);
                            }

                            labStudyNow.idElectronicSafeDocument = null;
                            labStudyNow.Status = statusCompleted;

                            //envoie la transaction
                            db.SaveChanges();
                        }

                        if (labStudyNow != null)
                        {
                            _Log.Trace("Début envoi de la LAB au coffre-fort");
                            //ElectronicSafeDocument
                            Guid idElectronicSafeDocument = Guid.Empty;
                            idElectronicSafeDocument = LABStudyBL.SendToCoffreFort(labStudyNow.idCustomer, labStudyNow.idLABStudy);

                            if (idElectronicSafeDocument != Guid.Empty)
                            {
                                isSendTocoffreOk = true;
                                using (UpsilabEntities db = new UpsilabEntities())
                                {
                                    //update 
                                    CustomerProspectLABModel customerLAbModeltoupdate = db.CustomerProspectLABModel.Where(c => c.idCustomerProspectLABModel == customerLabModel.idCustomerProspectLABModel).FirstOrDefault();
                                    customerLAbModeltoupdate.Status = statusCompleted;
                                    customerLAbModeltoupdate.DateUpdated = DateTime.Now;

                                    //update customerprospect
                                    CustomerProspect customerToUpdate = db.CustomerProspect.Where(c => c.idCustomer == customerLabModel.idCustomerProspect).FirstOrDefault();
                                    customerToUpdate.CurrentLabStatus = statusSentToCoffreFort;
                                    //envoie la transaction
                                    db.SaveChanges();
                                }
                                _Log.Trace("Envoi au coffre-fort OK");
                            }
                            else
                            {
                                lstFailingGuid.Add(customerLabModel.CustomerProspect.IdUser);
                                _Log.Trace("Erreur envoi au coffre-fort");
                            }

                        }
                    }
                    catch (Exception exc)
                    {

                        lstFailingGuid.Add(customerLabModel.CustomerProspect.IdUser);
                        _Log.Trace("Erreur pour le customer : {0}", customerLabModel.CustomerProspect.IdUser.ToString());

                    }
                    if (_CancelToken.IsCancellationRequested)
                        break;

                }

                //ajout nouveau message pour un utilisateur quand l'affectation LAB est fini  
                if (lstFailingGuid.Count == 0)
                {
                    using (UpsilabEntities db = new UpsilabEntities())
                    {
                        Message msg = new Message()
                        {
                            idUser = user.idUser,
                            NameKey = LABStudyBL.MessageNamekey,
                            Read = false,
                            DateCreated = DateTime.Now,
                            DateUpdated = DateTime.Now,
                            idLABModel = labModelNow.idLABModel,
                            From = LABStudyBL.FromLABModel
                        };

                        db.Message.AddObject(msg);
                        //envoie la transaction
                        db.SaveChanges();
                    }


                    _Log.Trace("\n Aucun incident pour l'utilisateur");
                }
                else
                {
                    using (UpsilabEntities db = new UpsilabEntities())
                    {
                        Message msg = new Message()
                        {
                            idUser = user.idUser,
                            NameKey = LABStudyBL.MessageNamekeyKO,
                            Read = false,
                            DateCreated = DateTime.Now,
                            DateUpdated = DateTime.Now,
                            idLABModel = labModelNow.idLABModel,
                            From = LABStudyBL.FromLABModel,
                            AdditionnalContent = String.Join(";", lstFailingGuid.ToArray())
                        };

                        db.Message.AddObject(msg);
                        //envoie la transaction
                        db.SaveChanges();
                    }
                    _Log.Trace("\n Erreur survenue pour l'utilisateur");
                }



            }
            catch (Exception ex)
            {
                _Log.Trace("Exception : {0}", ex.Message);
                Log.AppendException(ex);
            }

            finally
            {
                _LstOfCommand.Enqueue(new GuidAction() { guid = user.idUser, action = "remove" });
                autoEvent.Set();
                _Log.Trace("Ending thread  for {0} {1} from  iteration {2}", user.UserName, user.UserFirstName, _IterationId);
            }
            //  RemoveItemToLstOfProcessingUser(user);

        }
        public ActionResult MotDePasseOublie(User objUser)
        {
            var LanguageData = PageLanguageHelper.GetLanguageContent("Public", "UserCtrl/MdpOublie");

            try
            {
                if (objUser != null)
                {
                    Upsilab.Data.Model.User objUserRecupere = UserBL.GetUserByEmail(objUser.UserEmail);

                    // Tester si l'utilisateur existe et qu'il est active
                    if (objUserRecupere != null && objUserRecupere.IsActive)
                    {
                        // la chaine à crypter
                        string sTokenConcatene = string.Concat(objUserRecupere.UserEmail, System.Diagnostics.Stopwatch.GetTimestamp(), System.Configuration.ConfigurationManager.AppSettings["ClePriveToken"].ToString());

                        // cryptage du 
                        byte[] data = new System.Text.ASCIIEncoding().GetBytes(sTokenConcatene);
                        string sToken = Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(data));

                        // L'url de récupération de mdp
                        string sUrl = System.Configuration.ConfigurationManager.AppSettings["UrlInitialiserMDP"].ToString() + sToken;

                        #region "Envoi du mail"
                        // Envoi du mail
                        string sFrom = System.Configuration.ConfigurationManager.AppSettings["EmailFrom"].ToString();
                        string sTo = objUser.UserEmail;
                        string sSujet = LanguageData.GetContent("umo_sujet_mail");
                        string sMessage = LanguageData.GetContent("umo_contenu_mail") + "<a href='" + sUrl + "'>" + sUrl + "</a>";

                        EmailManager.SendEmail(sFrom, sTo, null, sSujet, sMessage);

                        //Log mail
                        EmailLogBL.Log(null, sFrom, objUser.idUser, sTo, EmailLogBL.TypeDestinataire.Client, System.Reflection.MethodBase.GetCurrentMethod().Name);

                        #endregion

                        #region "Enregistrement dans la base de données"
                        using (var db = new UpsilabEntities())
                        {
                            UserAuthentication objUserAuth = new UserAuthentication()
                            {
                                UserAuthToken = sToken,
                                IsValid = true,
                                DateCreated = DateTime.Now,
                                idUser = objUserRecupere.idUser
                            };

                            db.UserAuthentication.AddObject(objUserAuth);
                            db.SaveChanges();
                        }
                        #endregion

                        ViewBag.Info = LanguageData.GetContent("umo_mail_envoye"); 
                    }
                }
                else
                {
                    ViewBag.Info = LanguageData.GetContent("umo_user_inconnu");
                }
            }
            catch(Exception ex)
            {
                ViewBag.Info = LanguageData.GetContent("umo_catch_erreur") + ex.Message;
            }

            return View();
        }