Example #1
0
        public async Task <IActionResult> ChangeAvatar(string userId, AvatarEditInputModel model)
        {
            if (this.userManager.GetUserId(this.User) != userId &&
                !this.User.IsInRole(Socialley.Common.GlobalConstants.AdministratorRoleName))
            {
                return(this.Redirect("/Home/Index"));
            }

            if (!this.ModelState.IsValid)
            {
                return(this.Redirect("/Identity/Account/Manage/ChangeAvatar"));
            }

            try
            {
                await this.usersService.ChangeAvatar(userId, model, $"{this.environment.WebRootPath}/images");
            }
            catch (Exception ex)
            {
                this.ModelState.AddModelError(string.Empty, ex.Message);
                this.TempData["Message"] = "This format is not supproted. Please try again.";
                return(this.Redirect("/Identity/Account/Manage/ChangeAvatar"));
            }

            this.TempData["Message"] = "Successfully updated your profile!";
            return(this.Redirect("/Identity/Account/Manage/ChangeAvatar"));
        }
        public async Task ChangeAvatar(string userId, AvatarEditInputModel input, string imagePath)
        {
            var user = this.usersRepository.All().FirstOrDefault(x => x.Id == userId);

            Directory.CreateDirectory($"{imagePath}/users/");
            if (input.NewProfileImage != null)
            {
                var image     = input.NewProfileImage;
                var extension = Path.GetExtension(image.FileName).TrimStart('.');
                if (!this.allowedExtensions.Any(x => extension.EndsWith(x)))
                {
                    throw new ArgumentException($"Invalid image extension {extension}");
                }

                var oldProfileImage = this.userImagesRepository.All().FirstOrDefault(x => x.UserId == userId && x.IsProfileImage);
                if (oldProfileImage != null)
                {
                    oldProfileImage.IsProfileImage = false;
                }

                var dbImage = new UserImage
                {
                    UserId         = userId,
                    Extension      = extension,
                    IsProfileImage = true,
                };
                user.UserImages.Add(dbImage);
                var physicalPath = $"{imagePath}/users/{dbImage.Id}.{extension}";
                using Stream fileStream = new FileStream(physicalPath, FileMode.Create);
                await image.CopyToAsync(fileStream);

                await this.userImagesRepository.SaveChangesAsync();
            }
        }