Beispiel #1
0
        public static dynamic ToUpdateUserCommand(this UpdateUserProfileViewModel user)
        {
            if (user == null)
            {
                return(null);
            }

            return(new
            {
                UserId = user.Id,
                user.CompanyName,
                user.FirstName,
                user.LastName,
                user.AlternativeEmail,
                user.CompanyId,
                user.JobTitle,
                user.DisplayName,
                user.PhoneNumber,
                user.StreetAddress,
                user.City,
                user.ZipCode,
                user.State,
                user.Country,
                user.CountryCode,
                user.ProfilePicture,
                user.UserStatus
            });
        }
Beispiel #2
0
        public async Task <IActionResult> UpdateProfileInfo(int userId, [FromForm] UpdateUserProfileViewModel userInfo)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            if (userInfo.File != null)
            {
                if (userInfo.File.Length > _photoSettings.MaxBytes)
                {
                    return(BadRequest("Maximum file size exceeded"));
                }

                if (!_photoSettings.IsSupported(userInfo.File.FileName))
                {
                    return(BadRequest("Invalid file type"));
                }
            }
            var userInfoForUpdate = _mapper.Map <UpdateUserProfileDTO>(userInfo);
            var user = await _profile.UpdateProfileInfo(int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value), userInfoForUpdate);

            if (user == null)
            {
                return(BadRequest("Something went wrong"));
            }
            return(Ok(_mapper.Map <UserViewModel>(user)));
        }
        public ActionResult UpdateProfile()
        {
            var name = Convert.ToString(Session["Username"]);
            UpdateUserProfileViewModel updateUserProfileViewModel = accountService.UpdateProfile(name);

            return(View(updateUserProfileViewModel));
        }
Beispiel #4
0
        public async Task <ActionResult> UpdateUserProfile()
        {
            // Get the current user
            var currentUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            // Get the account associated with this user
            UserProfile profile = db.UserProfiles.Where(x => x.UserID.Equals(currentUser.Id)).FirstOrDefault();

            // ONLY proceed if the value wasn't null (i.e., we found the user in the database)
            if (profile != null)
            {
                // Create an instance of the update model and populate the values
                UpdateUserProfileViewModel user = new UpdateUserProfileViewModel
                {
                    FirstName = currentUser.FirstName,
                    LastName  = currentUser.LastName,
                    UserName  = profile.UserName,
                    Email     = profile.Email,
                    Avatar    = profile.Avatar,
                    SiteTheme = profile.SiteTheme
                };

                // Load the view with the update model using the above information
                return(View(user));
            }

            // We should never get here, but if we do, just load the view without the model information
            return(View());
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserProfileView"/> class.
        /// </summary>
        public UserProfileView(UpdateUserProfileViewModel updateUserProfileViewModel, ManageUserOrganizationViewModel manageUserOrganizationViewModel)
        {
            InitializeComponent();

            this.ViewModel = updateUserProfileViewModel;
            this.ManageUserOrganizationViewModel = manageUserOrganizationViewModel;
        }
        public void UpdateProfile(UpdateUserProfileViewModel updateUserProfileViewModel)
        {
            var  config = new MapperConfiguration(cfg => cfg.CreateMap <UpdateUserProfileViewModel, User>());
            var  mapper = new Mapper(config);
            User user   = mapper.Map <User>(updateUserProfileViewModel);

            accountRepository.UpdateProfile(user);
        }
        public ActionResult UpdateProfile(UpdateUserProfileViewModel updateUserProfile)
        {
            var updateUserProfileDto = Mapper.Map <UpdateUserProfileDto>(updateUserProfile);

            _accountService.UpdateUserProfile(updateUserProfileDto);

            return(RedirectToAction("ShowProfile"));
        }
        public UpdateUserProfileViewModel UpdateProfile(string name)
        {
            User user   = accountRepository.UpdateProfile(name);
            var  config = new MapperConfiguration(cfg => cfg.CreateMap <User, UpdateUserProfileViewModel>());
            var  mapper = new Mapper(config);
            UpdateUserProfileViewModel updateUserProfileViewModel = mapper.Map <UpdateUserProfileViewModel>(user);

            return(updateUserProfileViewModel);
        }
Beispiel #9
0
        public async Task <IActionResult> UpdateUserProfileAsync([FromBody] UpdateUserProfileViewModel updateUserViewModel)
        {
            var updateUserDto = _mapper.Map <UpdateUserProfileDto>(updateUserViewModel);

            var userDto = await _userService.UpdateUserProfileAsync(updateUserDto);

            var userViewModel = _mapper.Map <UserViewModel>(userDto);

            return(Ok(userViewModel));
        }
 public ActionResult UpdateProfile(UpdateUserProfileViewModel updateUserProfileViewModel)
 {
     if (ModelState.IsValid)
     {
         accountService.UpdateProfile(updateUserProfileViewModel);
         TempData["Success"] = "Profile Updated";
         return(RedirectToAction("DisplayProduct", "Product"));
     }
     else
     {
         return(View());
     }
 }
Beispiel #11
0
        public async Task <IHttpActionResult> UpdateUserProfile(UpdateUserProfileViewModel model)
        {
            model.ProfilePicture = _imageHelper.SaveProfilePicture(model.AvatarBase64);

            var createUserQueue = UserServiceConstants.QueueUpdateUser;

            await _messageBroker.GetSendEndpoint(createUserQueue)
            .Send <IUpdateUserCommand>(
                model.ToUpdateUserCommand()
                );

            return(Ok());
        }
        public void Test_UpdateUserProfile_Email_Validation(
            string testCaseDisplayName,
            string invalidEmail)
        {
            // Arrange
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_UpdateUserProfileViewModel(email: invalidEmail);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsFalse(result, testCaseDisplayName);
        }
        public void Test_UpdateUserProfile_Email_Validation()
        {
            // Arrange
            string testCaseDisplayName = "Email property was given value that is of " +
                                         "correct length and of valid email format. Validation should be successful.";
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_Valid_UpdateUserProfileViewModel(email: _defaultValidEmail);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsTrue(result, testCaseDisplayName);
        }
        public void Test_UpdateUserProfile_UserGender_Validation(
            string testCaseDisplayName,
            UserGender?validUserGender)
        {
            // Arrange
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_Valid_UpdateUserProfileViewModel(
                    email: _defaultValidEmail,
                    userGender: validUserGender);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsTrue(result, testCaseDisplayName);
        }
        public void Test_UpdateUserProfile_BirthDate_Validation(
            string testCaseDisplayName,
            DateTimeOffset?validBirthDate)
        {
            // Arrange
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_Valid_UpdateUserProfileViewModel(
                    email: _defaultValidEmail,
                    birthDate: validBirthDate);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsTrue(result, testCaseDisplayName);
        }
        public void Test_UpdateUserProfile_AboutMe_Validation(
            string testCaseDisplayName,
            string validAboutMe)
        {
            // Arrange
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_Valid_UpdateUserProfileViewModel(
                    email: _defaultValidEmail,
                    aboutMe: validAboutMe);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsTrue(result, testCaseDisplayName);
        }
        public void Test_UpdateUserProfile_AboutMe_Validation()
        {
            // Arrange
            string invalidAboutMe      = new string('*', 301);
            string testCaseDisplayName = "AboutMe property was given invalid " +
                                         "string value that exceeds the max length of 300. Validation should be failed.";
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_UpdateUserProfileViewModel(
                    email: _defaultValidEmail,
                    aboutMe: invalidAboutMe);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsFalse(result, testCaseDisplayName);
        }
        public void Test_UpdateUserProfile_Gender_Validation()
        {
            // Arrange
            UserGender invalidGender       = (UserGender)999;
            string     testCaseDisplayName = "Gender property was given invalid " +
                                             "value which is not defined in the UserGender Enum. Validation should be failed.";
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_UpdateUserProfileViewModel(
                    email: _defaultValidEmail,
                    gender: invalidGender);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsFalse(result, testCaseDisplayName);
        }
Beispiel #19
0
        public async Task <UpdateUserProfileViewModel> GetPersonalInfoDetails([FromBody] UpdateUserProfileViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UpdateUserCommandResult result = await _commandSender.Send <UpdateUserCommand, UpdateUserCommandResult>(new UpdateUserCommand { UserProfile = model.UserProfile }, new TimeSpan(2, 0, 0));

                    // Update Mailchimp Contact
                    try
                    {
                        await _mailChimpProvider.AddFILMemberAdditionalDetails(new MailChimp.Models.MCUserAdditionalDetailModel
                        {
                            FirstName   = result.UserProfile.FirstName,
                            LastName    = result.UserProfile.LastName,
                            Gender      = result.UserProfile.Gender,
                            DOB         = result.UserProfile.DOB,
                            PhoneCode   = result.UserProfile.PhoneCode,
                            PhoneNumber = result.UserProfile.PhoneNumber
                        });
                    }
                    catch (Exception ex)
                    {
                        _logger.Log(Logging.Enums.LogCategory.Error, ex);
                    }

                    return(new UpdateUserProfileViewModel
                    {
                        UserProfile = result.UserProfile
                    });
                }
                catch (Exception e)
                {
                    return(new UpdateUserProfileViewModel {
                    });
                }
            }
            else
            {
                return(new UpdateUserProfileViewModel {
                });
            }
        }
        public void Test_UpdateUserProfile_BirthDate_Validation()
        {
            // Arrange
            DateTimeOffset invalidBirthDate = new DateTimeOffset(
                day: 1, month: 1, year: 9999, hour: 0, minute: 1, second: 1,
                offset: TimeSpan.Zero);
            string testCaseDisplayName = "BirthDate property was given invalid " +
                                         "value which is later or equals the current time. Validation should be failed.";
            UpdateUserProfileViewModel updateUserProfileViewModel =
                Get_UpdateUserProfileViewModel(
                    email: _defaultValidEmail,
                    birthDate: invalidBirthDate);

            // Act
            bool result = ModelValidator.IsValid(updateUserProfileViewModel);

            // Assert
            Assert.IsFalse(result, testCaseDisplayName);
        }
Beispiel #21
0
        public async Task <ActionResult> UpdateUserProfile(UpdateUserProfileViewModel model, HttpPostedFileBase file)
        {
            // Find the profile associated with this user
            var profile = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            UserProfile userProfile = db.UserProfiles.Where(x => x.UserID.Equals(profile.Id)).FirstOrDefault();

            // If the model state is valid and there's a profile associated with this ID, proceed
            if (ModelState.IsValid && userProfile != null)
            {
                #region Profile Picture
                /////////////////////////////////////////////////////////////////////////
                //                                                                     //
                // This section handles uploading and storing a user's profile picture //
                //                                                                     //
                /////////////////////////////////////////////////////////////////////////

                // Only proceed if the file passed in isn't null and has content
                if (file != null && file.ContentLength > 0)
                {
                    // Don't allow files over 50KB
                    if (file.ContentLength > 5000000)
                    {
                        ViewBag.Message = "The size of the file should not exceed 5 MB";
                        return(View());
                    }

                    // Limit the file types we allow for images
                    var supportedTypes = new[] { "jpg", "jpeg", "png", "gif", "bmp" };

                    // Make sure the uploaded image is one of those types
                    var fileExt = Path.GetExtension(file.FileName.ToLower()).Substring(1);
                    if (!supportedTypes.Contains(fileExt))
                    {
                        ViewBag.Message = "Invalid file type. Only the following types (jpg, jpeg, png, gif, bmp) are supported.";
                        return(View());
                    }

                    // Set the bucket, region identifier, and URL prefix
                    string         bucketName   = "dialogistic-uploads";
                    RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
                    string         prefix       = "https://s3-us-west-2.amazonaws.com/dialogistic-uploads/images/";

                    // Instantiate a connection to the bucket via an S3 client, and assign the transfer utility
                    var             credentials         = new BasicAWSCredentials(ConfigurationManager.AppSettings["S3_ACCESS_KEY"], ConfigurationManager.AppSettings["S3_SECRET_KEY"]);
                    IAmazonS3       s3Client            = new AmazonS3Client(credentials, bucketRegion);
                    TransferUtility fileTransferUtility = new TransferUtility(s3Client);

                    // Initialize the key and string to hold the complete URL in
                    string keyName   = "images/" + file.FileName;
                    string avatarURL = null;

                    // Attempt to upload the image to the S3 bucket
                    try
                    {
                        // Instantiate a file transfer request, setting the storage and ACL parameters
                        TransferUtilityUploadRequest fileTransferUtilityRequest = new
                                                                                  TransferUtilityUploadRequest
                        {
                            StorageClass = S3StorageClass.Standard, // Standard access is what we want for these images
                            CannedACL    = S3CannedACL.PublicRead   // Images must have public read access to view in the application
                        };

                        // Convert the image to an input stream so we can upload it
                        MemoryStream fileToUpload = new MemoryStream();
                        file.InputStream.CopyTo(fileToUpload);

                        // Upload the image to the S3 bucket in the images directory
                        fileTransferUtility.Upload(fileToUpload, bucketName, keyName);
                    }
                    catch (AmazonS3Exception amazonS3Exception) // Amazon S3 specific exceptions
                    {
                        Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", amazonS3Exception.Message);
                    }
                    catch (Exception e) // All other exceptions
                    {
                        Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                    }

                    // If the upload was successful, update the user's avatar
                    avatarURL          = prefix + file.FileName;
                    userProfile.Avatar = avatarURL;

                    // Update the model's avatar as well -- it's overwritten as an empty string otherwise
                    model.Avatar    = userProfile.Avatar;
                    ViewBag.Message = "Image uploaded successfully!";
                }
                // There wasn't a file that needed to be uploaded -- set the model avatar to the user's existing value
                else
                {
                    model.Avatar = userProfile.Avatar;
                }
                #endregion

                #region Profile Information
                /////////////////////////////////////////////////////////////////////////////
                //                                                                         //
                // This section handles updating and storing a user's personal information //
                //                                                                         //
                /////////////////////////////////////////////////////////////////////////////

                // Get the current user from the AspNetUsers table and update their
                ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

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

                // Attempt to update the user's information
                var updateResult = await UserManager.UpdateAsync(user);

                if (updateResult.Succeeded)
                {
                    // If the update succeeded, update their information in our UserProfiles table
                    userProfile.FullName = user.FirstName + " " + user.LastName;
                    db.Entry(userProfile).CurrentValues.SetValues(model);
                    db.SaveChanges();

                    return(View(model));
                }
                #endregion

                // Add any errors found to the model state for displaying
                foreach (var error in updateResult.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            // There were issues with the model state-- return the view with any errors found above
            return(View(model));
        }