Exemple #1
0
 public bool UpdateProfile(CyberSparrow user, UpdateProfileModel model)
 {
     user.Biography   = model.Biography;
     user.PhoneNumber = model.PhoneNumber;
     db.Users.Update(user);
     return(SaveChanges());
 }
        public ActionResult UpdateProfile([FromBody] UpdateProfileModel model)
        {
            if (model != null)
            {
                using (var ctx = new COMMERCEContext())
                {
                    var foundUser = ctx.CustumerUser
                                    .Where(_ => _.CustumerId == model.Id)
                                    .FirstOrDefault();
                    if (foundUser == null)
                    {
                        return(Ok(-1));
                    }

                    foundUser.CustumerId       = model.Id;
                    foundUser.Customerlogin    = model.LoginName;
                    foundUser.CustumerLastName = model.LastName;
                    foundUser.CustumerName     = model.FirstName;
                    foundUser.Custumerpassword = model.Password.Equals(string.Empty) ? foundUser.Custumerpassword : model.Password;


                    ctx.CustumerUser.Update(foundUser);
                    ctx.SaveChanges();
                    return(Ok(1));
                }
            }
            return(Ok(-1));
        }
Exemple #3
0
        public override async Task <UpdateProfileResponse> UpdateProfile(UpdateProfileRequest request, ServerCallContext context)
        {
            var updateProfileModel = new UpdateProfileModel
            {
                ProfileId     = Guid.Parse(request.ProfileId),
                FirstName     = request.FirstName,
                LastName      = request.LastName,
                PhotoThumbUrl = request.PhotoThumbUrl
            };

            var updateProfileCommand = new UpdateProfileCommand(updateProfileModel);

            var result = await _commandBus.TransactionSendAsync(updateProfileCommand);

            if (result.IsOk)
            {
                var response = result.Value as dynamic;

                return(new UpdateProfileResponse
                {
                    ProfileId = response.ProfileId,
                    FirstName = response.FirstName,
                    LastName = response.LastName,
                    PhotoThumbUrl = response.PhotoThumbUrl,
                });
            }

            var statusCode = (StatusCode)result.StatusCode;

            throw new RpcException(new Status(statusCode, result.Value?.ToString()));
        }
Exemple #4
0
        public ActionResult Edit(UpdateProfileModel Model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (Session["PublicImageUrl"] != null)
                    {
                        Model.ProfilePictureUrl = Session["PublicImageUrl"].ToString();
                    }

                    if (Model.RolesId == (int)UserRoles.Admin)
                    {
                        AdminLogic.UpdateAdmin(Model);
                        Session["UserSession"] = SessionData;
                    }
                    Session["PublicImageUrl"] = "";
                    return(RedirectToAction("Index", new { roleId = Model.RolesId }));
                }
                catch (Exception e)
                {
                    LogsLogic.InsertLog(new Log()
                    {
                        Message    = e.Message,
                        StackTrace = e.StackTrace,
                        StoryName  = "MoreHolidays/Users/Edit(Post)",
                    });
                    Session["PublicImageUrl"] = "";
                    return(View(Model));
                }
            }

            return(View(User));
        }
        public IActionResult Update(UpdateProfileModel model)
        {
            byte[] fileBytes = null;
            string fileExt   = null;

            if (model.Image != null && model.Image.Length != 0)
            {
                using (var ms = new MemoryStream())
                {
                    model.Image.CopyTo(ms);
                    fileBytes = ms.ToArray();
                }

                fileExt = model.Image.FileName.Substring(model.Image.FileName.LastIndexOf('.'));
            }

            var updatedAccount = _accountService.UpdateAccount(
                model.FirstName,
                model.MiddleName,
                model.LastName,
                model.DateOfBirth,
                model.Email,
                model.Mobile,
                model.Address,
                model.CompanyName,
                model.CompanyAddress,
                model.CompanyEmail,
                model.CompanyPhone,
                fileBytes,
                fileExt
                );

            return(Ok());
        }
Exemple #6
0
        public ActionResult UpdateProfile()
        {
            try
            {
                var userEntity = this.GetUserEntityBySecurityUserKey(Guid.Parse(this.User.Identity.GetUserId()));

                if (userEntity.SecurityUser == null)
                {
                    userEntity.SecurityUser = this.AmiClient.GetUser(userEntity.SecurityUserKey.ToString())?.User;
                }

                var model = new UpdateProfileModel(userEntity);

                model = BuildUpdateModelMetaData(model, userEntity);

                return(View(model));
            }
            catch (Exception e)
            {
                Trace.TraceError($"Unable to display update profile view: {e}");
            }

            TempData["error"] = Locale.UnableToRetrieveProfile;

            return(Redirect(Request.UrlReferrer.ToString()));
        }
Exemple #7
0
        public async Task <IActionResult> UpdateProfile(UpdateProfileModel model)
        {
            var user = await _context.Users
                       .FirstOrDefaultAsync(u => u.Id == CurrentUserId);

            if (user == null || user.IsLockedOut)
            {
                return(Generate(HttpStatusCode.NotFound, "User not found."));
            }


            if (!model.EmailAddress.Equals(user.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
            {
                var existing = await _context.Users
                               .FirstOrDefaultAsync(u => u.EmailAddress == model.EmailAddress);

                if (existing != null)
                {
                    return(Generate(HttpStatusCode.BadRequest, $"User name \"{model.EmailAddress}\" is already taken."));
                }
            }

            user.EmailAddress = model.EmailAddress;
            user.FirstName    = model.FirstName;
            user.LastName     = model.LastName;
            user.DateOfBirth  = model.DateOfBirth.Value.ToUniversalTime();

            await _context.SaveChangesAsync();

            return(Generate(HttpStatusCode.OK, "Your profile has been updated."));
        }
        public async Task <IActionResult> Index([FromBody] UpdateProfileModel updateProfileModel)
        {
            var user = await _userManager.FindByNameAsync(updateProfileModel.CurrentUserName);

            if (user == null)
            {
                return(NotFound("User not found"));
            }

            user.Email    = updateProfileModel.Email;
            user.UserName = updateProfileModel.NewUserName;

            var result = await _userManager.UpdateAsync(user);

            //TODO - In a production env you would have a flow where your would confirme the password change via email/SMS

            if (result.Succeeded)
            {
                //update the name claim
                var claims = await _userManager.GetClaimsAsync(user);

                var removeClaims = claims.Where(f => f.Type == JwtClaimTypes.Name);

                await _userManager.RemoveClaimsAsync(user, removeClaims);

                await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Name, updateProfileModel.Name));

                return(Ok(updateProfileModel));
            }

            return(BadRequest(result.Errors.Select(s => s.Description)));
        }
Exemple #9
0
        public async Task <IActionResult> UpdateProfile([FromBody] UpdateProfileModel model)
        {
            var user = await _userRepository.GetUserById(HttpContext.User.Identity.Name);

            if (user == null)
            {
                return(_responseService.GenerateResponse(HttpStatusCode.NotFound, "User could not be found."));
            }

            if (!model.EmailAddress.Equals(user.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
            {
                var existing = await _userRepository.GetUserByEmailAddress(model.EmailAddress);

                if (existing != null)
                {
                    return(_responseService.GenerateResponse(HttpStatusCode.BadRequest, $"User name \"{model.EmailAddress}\" is already taken."));
                }

                user.EmailConfirmed   = false;
                user.VerifyEmailToken = null;
            }

            user.EmailAddress = model.EmailAddress;
            user.FirstName    = model.FirstName;
            user.LastName     = model.LastName;
            user.DateOfBirth  = model.DateOfBirth.GetValueOrDefault();
            await _userRepository.UpdateUser(user);

            return(_responseService.GenerateResponse(HttpStatusCode.OK, "Your profile has been updated."));
        }
 internal object UpdateProfile(UpdateProfileModel model)
 {
     try
     {
         User old_user = _dbContext.Users.Find(model.UserId);
         if (old_user != null)
         {
             old_user.FullName = model.Name;
             old_user.Gender   = model.Gender;
             old_user.Address  = model.Address;
             old_user.Contact  = model.Contact;
             old_user.DOB      = model.Dob;
             old_user.About    = model.About;
             _dbContext.Entry(old_user).State = EntityState.Modified;
             _dbContext.SaveChanges();
             return(new Response {
                 Success = true, Message = "Details Updated"
             });
         }
         else
         {
             return(new Response {
                 Success = false, Message = "Update Failed"
             });
         }
     }
     catch (Exception ex)
     {
         return(new Response {
             Success = false, Message = "Update Failed"
         });
     }
 }
Exemple #11
0
        public async Task <IActionResult> UpdateProfile([FromBody] UpdateProfileModel model)
        {
            var userId = this.UserId();

            var(IsDone, Message) = await _accountService.UpdateProfileAsync(userId, model);

            return(IsDone ? (IActionResult)Ok(Message) : BadRequest(Message));
        }
        public bool UpdateProfile(UpdateProfileModel model)
        {
            var inId = new SqlParameter
            {
                ParameterName = "Id",
                Value         = model.Id,
                DbType        = System.Data.DbType.Int64,
                Direction     = System.Data.ParameterDirection.Input
            };
            var inFirstName = new SqlParameter
            {
                ParameterName = "FirstName",
                Value         = model.FirstName,
                DbType        = System.Data.DbType.String,
                Direction     = System.Data.ParameterDirection.Input
            };
            var inLastName = new SqlParameter
            {
                ParameterName = "LastName",
                Value         = model.LastName,
                DbType        = System.Data.DbType.String,
                Direction     = System.Data.ParameterDirection.Input
            };
            var inPatronymic = new SqlParameter
            {
                ParameterName = "Patronymic",
                Value         = model.Patronymic,
                DbType        = System.Data.DbType.String,
                Direction     = System.Data.ParameterDirection.Input
            };
            var inPhoneNumber = new SqlParameter
            {
                ParameterName = "PhoneNumber",
                Value         = model.PhoneNumber,
                DbType        = System.Data.DbType.String,
                Direction     = System.Data.ParameterDirection.Input
            };
            var outResult = new SqlParameter
            {
                ParameterName = "Result",
                DbType        = System.Data.DbType.Boolean,
                Direction     = System.Data.ParameterDirection.Output
            };

            var sql = "exec UpdateProfile @Id, @FirstName, @LastName, @Patronymic, @PhoneNumber, @Result OUT";

            using (var dbContext = new PersonsContext())
            {
                _ = dbContext.Database.ExecuteSqlCommand(sql, inId, inFirstName, inLastName, inPatronymic, inPhoneNumber, outResult);
            }

            if (!Boolean.TryParse(outResult.Value.ToString(), out bool result))
            {
                return(false);
            }

            return(result);
        }
Exemple #13
0
        public ViewResult UpdateProfile(UpdateProfileModel viewModel)
        {
            var currentUser = CookieHelper.GetCookie <string>("CurrentUser");

            var updateProfileModel = WebApiCaller.PostAsync <UpdateProfileModel>("WebApi:Authenticate:FindUserProfile", new FindUserRequestModel {
                Username = currentUser
            });

            return(View("ChangePassword", updateProfileModel));
        }
Exemple #14
0
        /// <summary>
        /// Populates the UpdateProfileModel.
        /// </summary>
        /// <param name="model">The UpdateProfileModel instance </param>
        /// <param name="userEntity">The UserEntity object</param>
        /// <returns>Returns an <see cref="UpdateProfileModel"/> model instance.</returns>
        private UpdateProfileModel BuildUpdateModelMetaData(UpdateProfileModel model, UserEntity userEntity)
        {
            model.CreateLanguageList();

            var facilityRelationship = userEntity.Relationships.FirstOrDefault(r => r.RelationshipTypeKey == EntityRelationshipTypeKeys.DedicatedServiceDeliveryLocation);

            var place = facilityRelationship?.TargetEntity as Place;

            if (facilityRelationship?.TargetEntityKey.HasValue == true && place == null)
            {
                place = this.ImsiClient.Get <Place>(facilityRelationship.TargetEntityKey.Value, null) as Place;
            }

            if (place != null)
            {
                var facility = new List <FacilityModel>
                {
                    new FacilityModel(string.Join(" ", place.Names.SelectMany(n => n.Component).Select(c => c.Value)), place.Key?.ToString())
                };

                model.FacilityList.AddRange(facility.Select(f => new SelectListItem {
                    Text = f.Name, Value = f.Id, Selected = f.Id == place.Key?.ToString()
                }));
                model.Facility = place.Key?.ToString();
            }

            var phoneTypes = this.GetPhoneTypeConceptSet().Concepts.ToList();

            Guid phoneType;

            model.PhoneTypeList = this.IsValidId(model.PhoneType) && Guid.TryParse(model.PhoneType, out phoneType) ? phoneTypes.ToSelectList(this.HttpContext.GetCurrentLanguage(), p => p.Key == phoneType).ToList() : phoneTypes.ToSelectList(this.HttpContext.GetCurrentLanguage()).ToList();

            if (userEntity.Telecoms.Any())
            {
                //can have more than one contact - default to show mobile
                if (userEntity.Telecoms.Any(t => t.AddressUseKey == TelecomAddressUseKeys.MobileContact))
                {
                    model.PhoneNumber = userEntity.Telecoms.First(t => t.AddressUseKey == TelecomAddressUseKeys.MobileContact).Value;
                    model.PhoneType   = TelecomAddressUseKeys.MobileContact.ToString();
                }
                else
                {
                    model.PhoneNumber = userEntity.Telecoms.FirstOrDefault()?.Value;
                    model.PhoneType   = userEntity.Telecoms.FirstOrDefault()?.AddressUseKey?.ToString();
                }
            }
            else
            {
                //Default to Mobile - requirement
                model.PhoneType = TelecomAddressUseKeys.MobileContact.ToString();
            }

            return(model);
        }
        public async Task <Result <GetProfileModel> > UpdateProfile([FromBody] UpdateProfileModel profileModel)
        {
            if (User.Identity.IsAuthenticated)
            {
                var settings = new UpdateProfileSettings
                {
                    Mode = (string.IsNullOrWhiteSpace(profileModel.OldPassword) &&
                            string.IsNullOrWhiteSpace(profileModel.NewPassword) &&
                            string.IsNullOrWhiteSpace(profileModel.ConfirmNewPassword))
                                ? UpdateProfileMode.Default
                                : UpdateProfileMode.WithPassword
                };
                if (!Validate(profileModel, settings))
                {
                    return(null);
                }
                int             id;
                ApplicationUser user = null;

                if (int.TryParse(_userManager.GetUserId(User), out id))
                {
                    user = await _userService.FindAsync(id);
                }
                if (user == null)
                {
                    throw new AppValidationException(ErrorMessagesLibrary.Data[ErrorMessagesLibrary.Keys.CantFindUser]);
                }

                var oldEmail = user.Email;

                user.FirstName = profileModel.FirstName;
                user.LastName  = profileModel.LastName;
                user.Email     = profileModel.Email;
                user.UserName  = profileModel.Email;

                user = profileModel.Mode.Mode == UpdateProfileMode.WithPassword ? await _userService.UpdateWithPasswordChangeAsync(user, profileModel.OldPassword, profileModel.NewPassword)
                                    : await _userService.UpdateAsync(user);

                if (oldEmail != user.Email)
                {
                    await _userService.RefreshSignInAsync(user);
                }

                return(new GetProfileModel()
                {
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    AgentId = user.Profile.AgentId,
                    Email = user.Email
                });
            }

            return(null);
        }
        public async Task <bool> UpdateProfile([FromBody] UpdateProfileModel value)
        {
            var user = await userHandler.GetUserByEmail(HttpContext.User.Identity.Name);

            user.Biography   = value.Biography;
            user.PhoneNumber = value.PhoneNumber;
            if (value.Password.Length > 7)
            {
                await userManager.ChangePasswordAsync(user, user.PasswordHash, value.Password);
            }
            return(userHandler.UpdateProfile(user, value));
        }
 public ProfileViewModel()
 {
     IsEditMode        = false;
     ButtonTitle       = "Edit";
     _IAllDataServices = new AllDataServices();
     ProfileModel      = new UpdateProfileModel()
     {
         ChannelPartnerid   = CPSettings.ChannelPartnerid,
         ChannelPartnerName = CPSettings.ChannelPartnerName, email = CPSettings.EmailId,
         MobileNumber       = CPSettings.MobileNumber
     };
 }
        public async Task <IActionResult> UpdateProfile([FromBody] UpdateProfileModel model)
        {
            var updateCommand = new UpdateProfileCommand
            {
                FirstName = model.FirstName,
                LastName  = model.LastName,
                UserId    = HttpContext.GetLoggedUserId()
            };

            var response = await _mediator.Send(updateCommand);

            return(Ok(BaseResponse.Ok(response)));
        }
Exemple #19
0
        public ActionResult UpdateProfile()
        {
            var userEntity = _userRepository.GetUserObjByUserID(GetUserId());
            var model      = new UpdateProfileModel
            {
                UserDisplayName  = userEntity.UserDisplayName,
                UserEmailAddress = userEntity.UserEmailAddress,
                Title            = SettingsRepository.BlogName,
                UserSite         = userEntity.UserSite
            };

            return(View(model));
        }
Exemple #20
0
        /// <summary>
        /// cập nhật thông tin của người dùng
        /// </summary>
        /// <param name="model">model client truyền lên khi gọi api</param>
        /// <returns>null nếu model không có dữ liệu, không tồn tại tài khoản</returns>
        /// <returns>user sau update nếu thành công</returns>
        public async Task <User> UpdateUserAsync(UpdateProfileModel model)
        {
            if (model == null)
            {
                throw new AppException("Không có dữ liệu update");
            }

            var user = _context.Users.FirstOrDefault(u => u.Id == model.Id);

            if (user == null)
            {
                throw new AppException("Người dùng không tồn tại");
            }
            else
            {
                if (user.Email != model.Email)
                {
                    //kiểm tra xem đã có tài khoản nào dùng email này chưa
                    if (_context.Users.Any(x => x.Email == model.Email))
                    {
                        throw new AppException("Email \"" + model.Email + "\" đã tồn tại");
                    }
                }

                if (user.FullName != model.FullName)
                {
                    //kiểm tra xem đã có tài khoản nào dùng tên này chưa
                    if (_context.Users.Any(x => x.FullName == model.FullName))
                    {
                        throw new AppException("Tên \"" + model.FullName + "\" đã tồn tại");
                    }
                }
            }

            user.Email    = model.Email;
            user.FullName = model.FullName;
            user.ImageUrl = model.ImageUrl;
            user.Phone    = model.Phone;

            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw new AppException("Cập nhật thất bại!");
            }
            return(user);
        }
Exemple #21
0
        public ResponseModel UpdateProfile(UpdateProfileModel model)
        {
            var response = new ResponseModel
            {
                Success  = false,
                Messages = new List <string>()
            };

            if (ModelState.IsValid)
            {
                try
                {
                    var user = UserManager.FindById(model.UserId);
                    if (user != null)
                    {
                        user.FirstName = model.FirstName;
                        user.LastName  = model.LastName;

                        var status = UserManager.Update(user);
                        if (status.Succeeded)
                        {
                            response.Success = true;
                            response.Messages.Add("Profile updated");
                        }
                        else
                        {
                            response.Success = false;
                            response.Messages.AddRange(status.Errors);
                        }
                    }
                    else
                    {
                        response.Messages.Add("User not found");
                    }
                }
                catch (Exception error)
                {
                    response.Messages.Add(error.InnerException.Message);
                }
            }
            else
            {
                foreach (var error in ModelState.Values.SelectMany(obj => obj.Errors))
                {
                    response.Messages.Add(error.ErrorMessage);
                }
            }
            return(response);
        }
Exemple #22
0
        public async Task <IActionResult> UpdateProfileData([FromBody] UpdateProfileModel upm)
        {
            var user = await _userRepository.GetUserByLogin(upm.Username);

            if (upm.Phone != null)
            {
                user.PhoneNumber = upm.Phone;
            }
            if (upm.Email != null)
            {
                user.Login = upm.Email;
            }
            await _userRepository.UpdateAsync(user);

            return(Ok());
        }
        public async Task <string?> UpdateProfile(UpdateProfileModel profile, User user)
        {
            var save = false;

            if (!string.IsNullOrWhiteSpace(profile.Email))
            {
                if (await context.Users.AnyAsync(x => x.Id != user.Id && x.Email == profile.Email))
                {
                    return("That email address is already being used");
                }
                user.Email = profile.Email;
                save       = true;
            }
            if (profile.Tagline != null)
            {
                user.Tagline = profile.Tagline;
                save         = true;
            }

            if (profile.Bio != null)
            {
                user.Bio = profile.Bio;
                save     = true;
            }

            if (profile.BackgroundColor != null)
            {
                user.BackgroundColor = profile.BackgroundColor;
                save = true;
            }

            if (profile.DarkText != null)
            {
                user.isStandTextDark = profile.DarkText.Value;
                save = true;
            }
            if (profile.AutoRefill != null)
            {
                user.Repurchase = profile.AutoRefill.Value;
                save            = true;
            }
            if (save)
            {
                await context.SaveChangesAsync();
            }
            return(null);
        }
        public static void UpdateAdmin(UpdateProfileModel Model)
        {
            UserProfile admin = new UserProfile()
            {
                Address           = Model.Address,
                BirthDate         = Model.BirthDate,
                Email             = Model.Email,
                FirstName         = Model.FirstName,
                LastName          = Model.LastName,
                Name              = Model.Name,
                Phone1            = Model.Phone1,
                Phone2            = Model.Phone2,
                ProfilePictureUrl = Model.ProfilePictureUrl,
                UserId            = Model.UserId
            };

            AdminRepositories.UpdateAdmin(admin);
        }
Exemple #25
0
        public async Task <IdentityResult> UpdateUser(string userId, UpdateProfileModel updateProfileModel)
        {
            var user = await _userManager.FindByIdAsync(userId);

            user.Name       = updateProfileModel.name;
            user.Surname    = updateProfileModel.surname;
            user.about      = updateProfileModel.about;
            user.headline   = updateProfileModel.headline;
            user.provinceId = updateProfileModel.provinceId;
            user.districtId = updateProfileModel.districtId;
            user.industryId = updateProfileModel.industryId;
            user.ZIPCode    = updateProfileModel.zipCode;
            user.address    = updateProfileModel.address;
            user.webSite    = updateProfileModel.website;
            user.birthDate  = updateProfileModel.birthDate;

            return(await _userManager.UpdateAsync(user));
        }
Exemple #26
0
        public IActionResult UpdateProfile(int id, [FromBody] UpdateProfileModel model)
        {
            // map model to entity and set id
            var user = _mapper.Map <User>(model);

            user.Id = id;

            try
            {
                // update user
                _userService.Update(user, model.Password);
                return(Ok());
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
Exemple #27
0
        public async Task <IActionResult> UpdateProfileData(UpdateProfileModel upm)
        {
            if (AddAuthorizationHeader())
            {
                var str = new StringContent(System.Text.Json.JsonSerializer.Serialize(upm).ToString(), Encoding.UTF8, "application/json");

                var response = await _client.PostAsync("https://localhost:44336/api/account/updateProfileData", str);

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    return(Ok());

                case HttpStatusCode.InternalServerError:
                    return(StatusCode(500));
                }
            }
            return(BadRequest());
        }
Exemple #28
0
        private UserEntity GetUserEntity(UpdateProfileModel model)
        {
            var userEntity = new UserEntity
            {
                UserID           = GetUserId(),
                UserDisplayName  = model.UserDisplayName,
                UserEmailAddress = model.UserEmailAddress,
                UserSite         = model.UserSite
            };

            if (!string.IsNullOrEmpty(model.NewPassword) && !string.IsNullOrEmpty(model.ConfirmPassword))
            {
                var randomCode = RandomStringGenerator.RandomString();
                userEntity.Password = PasswordHelper.GenerateHashedPassword(model.NewPassword, randomCode);
                userEntity.UserCode = TripleDES.EncryptString(randomCode);
            }

            return(userEntity);
        }
Exemple #29
0
        public ActionResult UpdateProfile(UpdateProfileModel model)
        {
            if (ModelState.IsValid)
            {
                var userEntity = GetUserEntity(model);
                var status     = _userRepository.UpdateProfile(userEntity);
                if (!status)
                {
                    ModelState.AddModelError("__FORM", "Unable to update the profile. Please try again later or contact the administrator");
                }
                else
                {
                    model.UpdateStatus = true;
                }
            }

            model.Title = SettingsRepository.BlogName;
            return(View(model));
        }
Exemple #30
0
        public async Task <JsonResult> UpdateProfile(UpdateProfileModel profile)

        {
            if (profile.Email == String.Empty)
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }

            var result = await _profileOrchestrator.UpdateProfile(new ProfileViewModel
            {
                Email       = profile.Email,
                FirstName   = profile.FirstName,
                Gender      = profile.Gender,
                LastName    = profile.LastName,
                PhoneNumber = profile.PhoneNumber
            });

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public virtual ActionResult ChangePassword(UpdateProfileModel model)
        {
            if (ModelState.IsValid) {
                var userName = this.UserName();
                var user = new User() { UserName = userName, Password = model.OldPassword };
                if (AccountService.ChangePassword(user, model.NewPassword)) {
                    //_acctService.UpdateCurrentUserInSession();
                    UserEventLogService.LogUserEvent(UserActions.ChangePassword);

                    return RedirectToAction(Actions.ChangePasswordSuccess());
                } else {
                    ModelState.AddModelError("", SystemErrors.PasswordChangeFailed);
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = AccountService.MinPasswordLength;
            this.FeedbackError("There was an error changing your password...");

            model.NavigationLocation = new string[] { "Account", "ChangePassword" };
            return View(model);
        }
        public virtual ActionResult UpdateProfile()
        {
            try {
                ViewData["PasswordLength"] = AccountService.MinPasswordLength;

                var user = Account.User();// SessionService.Session().User(User.Identity.Name);
                var vm = new UpdateProfileModel() {
                    NavigationLocation = new string[] { "Account", "UpdateProfile" },
                    Email = this.UserName(),
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    ShowSignatureField = user.IsAtLeastInCatalogRole(Roles.Plugger),
                    ShowContactInfo = user.PricingPlan.CustomContactUs && user.IsAtLeastInCatalogRole(Roles.Admin),
                    HasAllowedCommunication = user.HasAllowedCommunication,
                    PageTitle = "Update Profile",
                    PageMessage= "My Profile"

                };
                if (vm.ShowSignatureField){
                    vm.AppendSignatureToTitle = user.AppendSignatureToTitle;
                    vm.Signature = user.Signature;
                }
                if (vm.ShowContactInfo){
                    vm.Contact = user.GetContactInfo(false) ?? new Contact() { Email = user.UserName, IsDefault = true } ;
                }

                return View(vm);
            }
            catch (Exception ex){
                Log.Error(ex);
                this.FeedbackError("There was an error loading the Update Profile page. Please try again in a bit.");
                return RedirectToAction(MVC.Home.Index());
            }
        }
        public virtual ActionResult UpdateProfile(UpdateProfileModel model, Contact contact)
        {
            var userModel = new User() {
                UserName = this.UserName(),
                FirstName = model.FirstName,
                LastName = model.LastName,
                Signature = model.Signature,
                AppendSignatureToTitle = model.AppendSignatureToTitle,
                HasAllowedCommunication = model.HasAllowedCommunication
            };

            //var contact = model.Contact;

            //var session = SessionService.Session();
            var currentUser = Account.User();//session.User(User.Identity.Name);
            model.ShowSignatureField = currentUser.IsAtLeastInCatalogRole(Roles.Plugger);
            model.ShowContactInfo = currentUser.PricingPlan.CustomContactUs && currentUser.IsAtLeastInCatalogRole(Roles.Admin);

            //update the user's profile in the database
            try {
                var contactList = AccountService.UpdateProfile(userModel, new List<Contact>() { contact });

                UserEventLogService.LogUserEvent(UserActions.UpdateProfile);

                // UpdateModelWith the user dataSession cached in dataSession
                SessionService.Session().InitializeSession(true);
                CacheService.CacheUpdate(CacheService.CacheKeys.SiteProfile);

                var friendly = userModel.FullName();
                SetFriendlyNameCookie(friendly);

                this.FeedbackInfo("Successfully updated your profile");

                model.Contact = contactList.FirstOrDefault();

                ViewData["PasswordLength"] = AccountService.MinPasswordLength;

            }
            catch (Exception ex){
                Log.Error(ex);
                //model.ShowSignatureField = user.IsAtLeastInCatalogRole(Roles.Plugger);

                ModelState.AddModelError("",
                    SystemErrors.PasswordChangeFailed);
                this.FeedbackError("There was an error updating your profile");
            }

            model.NavigationLocation = new string[] { "Account", "Profile" };
            model.PageTitle = "Update Profile";
            model.PageMessage = "My Profile";
            return View(model);
        }