/// <summary>
        /// return value is user token for email confirmation of created user
        /// </summary>
        /// <param name="userModel"></param>
        /// <returns></returns>
        public string CreateUser(UserViewModel userModel)
        {
            try
            {
                ExceptionManager.WriteToEventLog(userModel.ToString(), "Application", System.Diagnostics.EventLogEntryType.Error);
                var addressId = addressRepository.AddNewAddress(userModel.AddressModel);
                userModel.AddressID = addressId;

                // store hashed and salted password
                string passwordHist = PasswordHash.CreateHash(userModel.Password);
                ExceptionManager.WriteToEventLog("passwordHist:" + passwordHist, "Application", System.Diagnostics.EventLogEntryType.Error);
                string userToken = WebSecurity.CreateUserAndAccount(userModel.UserName, userModel.Password,
                                                 propertyValues: new
                                                 {
                                                     FirstName = userModel.FirstName,
                                                     LastName = userModel.LastName,
                                                     AddressID = userModel.AddressID,
                                                     PreferredTimeZone = userModel.SelectedTimezone,
                                                     ModifiedBy = UserPrincipal.Current.UserId,
                                                     ModifiedOn = DateTime.UtcNow,
                                                     PasswordHist = passwordHist,
                                                     IsRegisterComplete = false
                                                 },
                                                 requireConfirmationToken: true);
                ExceptionManager.WriteToEventLog("usertoken:" + userToken, "Application", System.Diagnostics.EventLogEntryType.Error);
                //Roles.AddUsersToRole(new string[] { userModel.UserName }, userModel.SelectedRole);

                // retrieve roles from session and save update user roles
                var newRoles = SessionHelper.SessionExtract<List<string>>(SessionHelper.SESSION_KEY_NEW_ROLES);
                if (newRoles.Count > 0)
                    Roles.AddUserToRoles(userModel.UserName, newRoles.ToArray());                
                // retrieve lenders assigned to servicer if user is in role of servicer
                List<int> lenderIdsAssigned = new List<int>();
                List<string> FhasAssigned = new List<string>();
                if(newRoles.Contains("Servicer"))
                {
                    var lendersAssigned = SessionHelper.SessionExtract<IDictionary<int, string>>(SessionHelper.SESSION_KEY_NEW_LENDERS);
                    if (lendersAssigned != null)
                        lendersAssigned.ToList().ForEach(p => lenderIdsAssigned.Add(p.Key));
                }
                if(newRoles.Contains("LenderAccountRep"))
                {
                    var fhasSelected = SessionHelper.SessionExtract<IDictionary<string, string>>(SessionHelper.SESSION_KEY_LAR_FHA_LINKS);
                    if (fhasSelected != null)
                        fhasSelected.ToList().ForEach(p => FhasAssigned.Add(p.Key));
                }

                unitOfWork.Save();
                return userToken;
            }
            catch(Exception e)
            {
                throw new InvalidOperationException("Error happened while creating new user", e.InnerException);
            }            
        }
 public void UpdateUser(UserViewModel model)
 {
         addressRepository.UpdateAddress(model.AddressModel);
         userRepository.UpdateUser(model);
         ExceptionManager.WriteToEventLog(model.ToString(), "Application", System.Diagnostics.EventLogEntryType.Error);  
         unitOfWork.Save();         
 }
 public ActionResult SaveEditUser(UserViewModel model)
 {
     accountMgr.UpdateUser(model);
     return RedirectToAction("ListUsers");
 }
 public ActionResult RegisterUserStep1(UserViewModel model)
 {          
     
     return View(model);
 }
        public ActionResult Register(UserViewModel model)
        {
            if (webSecurity.UserExists(model.UserName))
            {
                ModelState.AddModelError("UserExistsErr", "User with same user name already exists.");
                TempData["UserExists"] = true;
            }
            if (ModelState.IsValid)
            { 
                // Attempt to register the user
                try
                {
                    // randomly generate strong password, 9 characters long
                    model.Password = RandomPassword.Generate(9); 
                    string userToken = accountMgr.CreateUser(model);
                    int userId = webSecurity.GetUserId(model.UserName);
                    accountMgr.InitForceChangePassword(userId);
                    // save encrypted password history
                    accountMgr.SavePasswordHist(model.UserName, model.Password);
                    var emailMgr = new EmailManager();
                    string confirmLink = this.Url.Action("AgreementConfirm", "Account", new { id = userToken }, this.Request.Url.Scheme);
                    //emailMgr.SendRegisterUserEmail(model, confirmLink);
                    return RedirectToAction("ListUsers"); 
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        ExceptionManager.WriteToEventLog(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                            eve.Entry.Entity.GetType().Name, eve.Entry.State), "Application", System.Diagnostics.EventLogEntryType.Error);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            ExceptionManager.WriteToEventLog(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                ve.PropertyName, ve.ErrorMessage), "Application", System.Diagnostics.EventLogEntryType.Error);
                        }
                    }
                    throw;
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException(string.Format("Error from creating user: {0}", e.InnerException.ToString()), e.InnerException);
                }
            }

            // If we got this far, something failed, redisplay form
            model = new UserViewModel();
            ModelState.Clear();

            //Roles.GetAllRoles().ToList().ForEach(p => model.AllRoles.Add(new SelectListItem() { Text = p, Value = p }));

            // get all time zone
            model.AllStates.Add(new SelectListItem() { Text = "Select State", Value = "Select" });
            accountMgr.GetAllStates().ToList().ForEach(p => model.AllStates.Add(new SelectListItem() { Text = p.Value, Value = p.Key }));
            return View(model);
        }
 public ActionResult Register()
 {
     var model = new UserViewModel();
     //model.AllRoles.Add(new SelectListItem() { Text = "Select Role", Value = "Select Role" });
     //Roles.GetAllRoles().ToList().ForEach(p => model.AllRoles.Add(new SelectListItem() { Text = p, Value = p }));
     
     var newRoles = SessionHelper.SessionGet<List<string>>(SessionHelper.SESSION_KEY_NEW_ROLES);
        
     model.AllStates.Add(new SelectListItem() { Text = "Select State", Value = "Select" });
     accountMgr.GetAllStates().ToList().ForEach(p => model.AllStates.Add(new SelectListItem() { Text = p.Value, Value = p.Key }));
     return View(model);
 }