public ActionResult Create(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                BOMembershipUser membershipUser = new BOMembershipUser();
                Mapper.Map<UserViewModel, BOMembershipUser>(model, membershipUser);
                SaveResult result = _userService.Save(membershipUser, Common.User);

                if (result == SaveResult.Success)
                {
                    _cacheService.Remove<MenuStructure>(CacheKeys.MenuStructure);
                    return RedirectToAction("Index");
                }

                else
                {
                    switch (result)
                    {
                        case SaveResult.DuplicateEmailExists:
                            ModelState.AddModelError("Message", GlobalResource(GlobalResourceUser.DuplicateEmailExists));
                            break;
                        case SaveResult.CannotReusePassword:
                            ModelState.AddModelError("Message", GlobalResource(GlobalResourceUser.CannotReusePassword));
                            break;
                        case SaveResult.DuplicateUserNameExists:
                            ModelState.AddModelError("Message", GlobalResource(GlobalResourceUser.DuplicateUserNameExists));
                            break;
                        case SaveResult.FailedToChangeUserName:
                            ModelState.AddModelError("Message", GlobalResource(GlobalResourceUser.InvalidUserName));
                            break;
                        case SaveResult.InvalidPassword:
                            ModelState.AddModelError("Message", GlobalResource(GlobalResourceUser.InvalidPassword));
                            break;
                        default:
                            ModelState.AddModelError("Message", GlobalResource(GlobalResourceUser.Unknown));
                            break;
                    }
                }

            }
            var companies = _companyService.GetAllCompanies();
            var roles = _roleService.GetAllRoles();

            model.CompanyList = new SelectList(companies, SelectLists.DataValueField, SelectLists.DataTextField, model.Company);
            model.UserRoleList = new SelectList(roles, SelectLists.DataValueField, SelectLists.DataTextField);
            model.PasswordValidationMessage = BOUser.PasswordValidationMessage;

            return View(model);
        }
        public RegisterResult Register(BOMembershipUser membershipUser, HttpContext httpContext)
        {
            var addressRepository = _repositoryFactory.GetRepository<BOAddress, BOAddressCollection>();
            var contactRepository = _repositoryFactory.GetRepository<BOContact, BOContactCollection>();
            var passwordHistoryRepository = _repositoryFactory.GetRepository<BOPasswordHistory, BOPasswordHistoryCollection>();

            try
            {
                MembershipCreateStatus createStatus;
                BOUser newUser = membershipUser.User;

                if (_userService.IsAlreadyRegisteredEmail(membershipUser))
                {

                    return RegisterResult.DuplicateEmail;
                }
                BOUser.ValidatePasswordResult result = newUser.ValidatePassword(membershipUser.Password.Trim());
                if (result != BOUser.ValidatePasswordResult.Success)
                {
                    switch (result)
                    {
                        case BOUser.ValidatePasswordResult.CannotReusePassword:
                            return RegisterResult.CannotReusePassword;
                        case BOUser.ValidatePasswordResult.InvalidPassword:
                            return RegisterResult.InvalidPassword;
                    }
                }

                membershipUser.PasswordHistory.Password = MD5.Md5Hash(membershipUser.Password);

                Membership.CreateUser(membershipUser.UserName.Trim(), membershipUser.Password.Trim(), membershipUser.Email.Trim(), null, null, true, null, out createStatus);

                switch (createStatus)
                {
                    case MembershipCreateStatus.Success:
                        {
                            FormsAuthentication.SetAuthCookie(membershipUser.UserName, false);
                            httpContext.Session["LoggedInUser"] = membershipUser.UserName;

                            Guid userFKey;
                            MembershipUser mu = Membership.GetUser(membershipUser.UserName);
                            userFKey = (Guid)mu.ProviderUserKey;

                            newUser.GUID = userFKey.ToString();
                            membershipUser.PasswordHistory.User = newUser;
                            membershipUser.Contact.User = newUser;

                            _userRepository.Save(newUser);

                            passwordHistoryRepository.Save(membershipUser.PasswordHistory);
                            addressRepository.Save(membershipUser.Address);
                            contactRepository.Save(membershipUser.Contact);

                            Roles.AddUserToRole(membershipUser.UserName.Trim(), membershipUser.UserRole);
                            return RegisterResult.Success;
                        }
                    case MembershipCreateStatus.DuplicateEmail:
                        return RegisterResult.DuplicateEmail;
                    case MembershipCreateStatus.DuplicateProviderUserKey:
                        return RegisterResult.DuplicateEmail;
                    case MembershipCreateStatus.DuplicateUserName:
                        return RegisterResult.DuplicateUserName;
                    case MembershipCreateStatus.InvalidAnswer:
                        return RegisterResult.InvalidAnswer;
                    case MembershipCreateStatus.InvalidEmail:
                        return RegisterResult.InvalidEmail;
                    case MembershipCreateStatus.InvalidPassword:
                        return RegisterResult.InvalidPassword;
                    case MembershipCreateStatus.InvalidProviderUserKey:
                        return RegisterResult.InvalidProviderUserKey;
                    case MembershipCreateStatus.InvalidQuestion:
                        return RegisterResult.InvalidQuestion;
                    case MembershipCreateStatus.InvalidUserName:
                        return RegisterResult.InvalidUserName;
                    case MembershipCreateStatus.ProviderError:
                        return RegisterResult.ProviderError;
                    case MembershipCreateStatus.UserRejected:
                        return RegisterResult.UserRejected;
                    default:
                        return RegisterResult.Failed;

                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("Unable to create account", ex);
                return RegisterResult.Failed;
            }
        }
        private ModifyExistingUserResult ModifyExistingUser(BOMembershipUser membershipUser, MembershipUser membership)
        {
            BOUser user = membershipUser.User;

            if (!string.IsNullOrEmpty(membershipUser.Password))
            {
                if (membership.IsLockedOut)
                    membership.UnlockUser();
                BOUser.ChangePasswordResult result = user.ChangePassword(membershipUser.Password.Trim());
                if (result != BOUser.ChangePasswordResult.Success)
                {
                    switch (result)
                    {
                        case BOUser.ChangePasswordResult.CannotReusePassword:
                            return ModifyExistingUserResult.CannotReusePassword;
                        case BOUser.ChangePasswordResult.InvalidPassword:
                            return ModifyExistingUserResult.InvalidPassword;
                        default:
                            return ModifyExistingUserResult.Failed;
                    }
                }
            }
            if (membership.Email != membershipUser.Email)
            {
                membership.Email = membershipUser.Email;
                Membership.UpdateUser(membership);
            }
            return ModifyExistingUserResult.Success;
        }
 private void UpdateMembershipUser(BOMembershipUser membershipUser, MembershipUser membership)
 {
     if (membership.IsApproved != !membershipUser.IsApproved)
     {
         membership.IsApproved = !membershipUser.IsApproved;
         Membership.UpdateUser(membership);
     }
 }
        private CreateNewUserResult CreateNewUser(BOMembershipUser membershipUser, ref MembershipUser membership, BOUser currentUser)
        {
            var passwordHistoryRepository = _repositoryFactory.GetRepository<BOPasswordHistory, BOPasswordHistoryCollection>();

            BOUser user = membershipUser.User;
            MembershipCreateStatus createStatus;

            if (IsAlreadyRegisteredEmail(membershipUser))
            {
                return CreateNewUserResult.DuplicateEmailExists;
            }
            BOUser.ValidatePasswordResult validatePasswordResult = user.ValidatePassword(membershipUser.Password.Trim());
            if (validatePasswordResult != BOUser.ValidatePasswordResult.Success)
            {
                switch (validatePasswordResult)
                {
                    case BOUser.ValidatePasswordResult.CannotReusePassword:
                        return CreateNewUserResult.CannotReusePassword;
                    case BOUser.ValidatePasswordResult.InvalidPassword:
                        return CreateNewUserResult.InvalidPassword;
                }
            }
            if (Membership.GetUser(membershipUser.UserName) != null)
                return CreateNewUserResult.DuplicateUserNameExists;

            membershipUser.PasswordHistory.Password = MD5.Md5Hash(membershipUser.Password);

            Membership.CreateUser(membershipUser.UserName, membershipUser.Password, membershipUser.Email, null, null, true, null, out createStatus);
            if (createStatus == MembershipCreateStatus.Success)
            {
                try
                {
                    membership = Membership.GetUser(membershipUser.UserName);
                    user.GUID = ((Guid)membership.ProviderUserKey).ToString();
                    membershipUser.PasswordHistory.User = user;

                    _userRepository.Save(user);

                    passwordHistoryRepository.Save(membershipUser.PasswordHistory);
                    BOUserAudit.CreateAudit(currentUser, "User Created", string.Format("User account for '{0}'", membershipUser.UserName));

                    return CreateNewUserResult.Success;
                }
                catch
                {
                    return CreateNewUserResult.Failed;
                }
            }
            else
            {
                return CreateNewUserResult.Failed;
            }
        }
        private ChangeUsernameResult ChangeUserName(BOMembershipUser membershipUser, MembershipUser membership)
        {
            if (membership.UserName.ToLower() != membershipUser.UserName.Trim().ToLower())
            {
                if (!BOUser.CheckForDuplicateUser(membership.UserName, membershipUser.UserName.Trim()))
                {
                    bool results = false;

                    using (SqlConnection connection = new SqlConnection(BOBase.GetConnectionString()))
                    {
                        connection.Open();

                        string newUserName = membershipUser.UserName.Trim();

                        SqlParameter[] parameters =
                        {
                            new SqlParameter("@OldUsername", membership.UserName),
                            new SqlParameter("@NewUsername", newUserName),
                            new SqlParameter("@LoweredNewUsername", newUserName.ToLower())
                        };

                        results = _userRepository.ExecuteNonQuery(StoredProcedures.UserChangeUserName, CommandType.StoredProcedure, connection, null, parameters) > 0;
                    }

                    return (results) ? ChangeUsernameResult.Success : ChangeUsernameResult.UsernameAlreadyExists;
                }
                else
                {
                    return ChangeUsernameResult.UsernameAlreadyExists;
                }
            }

            return ChangeUsernameResult.Success;
        }
        private void AddRoles(BOMembershipUser membershipUser, MembershipUser membership)
        {
            string[] roles = Roles.GetAllRoles();
            foreach (string role in roles)
            {
                if (Roles.IsUserInRole(membership.UserName, role))
                {
                    Roles.RemoveUserFromRole(membership.UserName, role);
                }
            }

            string[] userRole = membershipUser.UserRole.Trim(',').Split(',');

            foreach (string r in userRole)
            {
                if (!string.IsNullOrEmpty(r))
                {
                    foreach (string role in roles)
                    {
                        if (r.ToUpper() == role.ToUpper())
                        {
                            Roles.AddUserToRole(membership.UserName, role);
                        }
                    }
                }
            }
        }
        public SaveResult Save(BOMembershipUser membershipUser, BOUser currentUser)
        {
            var contactRepository = _repositoryFactory.GetRepository<BOContact, BOContactCollection>();

            MembershipUser membership = null;
            BOUser user = membershipUser.User;

            if (IsAlreadyRegisteredEmail(membershipUser))
                return SaveResult.DuplicateEmailExists;

            if (user != null && user.GUID != null && !string.IsNullOrEmpty(user.GUID.ToString()))
            {
                membership = Membership.GetUser(Guid.Parse(user.GUID));
                ModifyExistingUserResult result = ModifyExistingUser(membershipUser, membership);
                if (result != ModifyExistingUserResult.Success)
                {
                    switch (result)
                    {
                        case ModifyExistingUserResult.CannotReusePassword:
                            return SaveResult.CannotReusePassword;
                        case ModifyExistingUserResult.InvalidPassword:
                            return SaveResult.InvalidPassword;
                        default:
                            return SaveResult.Failed;
                    }
                }
                BOUserAudit.CreateAudit(currentUser, "User Updated", string.Format("Changes made to user account for '{0}'", membershipUser.UserName));
            }
            else
            {
                CreateNewUserResult result = CreateNewUser(membershipUser, ref membership, currentUser);
                if (result != CreateNewUserResult.Success)
                {
                    switch (result)
                    {
                        case CreateNewUserResult.CannotReusePassword:
                            return SaveResult.CannotReusePassword;
                        case CreateNewUserResult.DuplicateEmailExists:
                            return SaveResult.DuplicateEmailExists;
                        case CreateNewUserResult.DuplicateUserNameExists:
                            return SaveResult.DuplicateUserNameExists;
                        case CreateNewUserResult.InvalidPassword:
                            return SaveResult.InvalidPassword;
                        default:
                            return SaveResult.Failed;
                    }
                }
            }

            membershipUser.Contact.User = membershipUser.User;

            contactRepository.Save(membershipUser.Contact);

            AddRoles(membershipUser, membership);

            ChangeUsernameResult changeUserNameResult = ChangeUserName(membershipUser, membership);

            if (changeUserNameResult != ChangeUsernameResult.Success)
            {
                switch (changeUserNameResult)
                {
                    case ChangeUsernameResult.UsernameAlreadyExists:
                        return SaveResult.DuplicateUserNameExists;
                    default:
                        return SaveResult.Failed;
                }
            }

            UpdateMembershipUser(membershipUser, membership);

            _userRepository.Save(user);

            return SaveResult.Success;
        }
        public bool IsAlreadyRegisteredEmail(BOMembershipUser userToBeSaved)
        {
            MembershipUser userInDatabase = userToBeSaved.User.MembershipUser;

            bool emailChanged =
                userInDatabase == null ||                                  // New User
                !string.Equals(userInDatabase.Email, userToBeSaved.Email); // User has changed their email

            return (emailChanged) ? BOUser.IsAlreadyRegisteredEmail(userToBeSaved.UserName, userToBeSaved.Email) : false;
        }