Пример #1
0
        public async Task ValidateForUpdate(int id, FilmForUpdateDto filmForUpdate)
        {
            Validate(filmForUpdate);

            var film = await _uow.Repository <Film>().FindByIdAsync(id);

            if (film == null)
            {
                throw new NotFoundException(nameof(Film));
            }

            ValidateType(filmForUpdate.TypeId);

            await ValidateCountry(filmForUpdate.CountryId);

            await ValidateLanguage(filmForUpdate.LanguageId);

            await ValidateGenre(filmForUpdate.GenreIds);

            await ValidateParticipants(filmForUpdate.ParticipantsRoles.Select(x => x.ParticipantId).ToList());

            await ValidateFilmRoles(filmForUpdate.ParticipantsRoles.Select(x => x.RoleId).ToList());

            ThrowValidationErrorsIfNotEmpty();
        }
Пример #2
0
        public async Task <IActionResult> Update(int id, FilmForUpdateDto filmForUpdate)
        {
            await _filmValidatorService.ValidateForUpdate(id, filmForUpdate);

            var film = await _filmService.Update(id, filmForUpdate);

            return(Ok(film));
        }
Пример #3
0
        public async Task <FilmForDetailedDto> Update(int id, FilmForUpdateDto filmForUpdate)
        {
            var film = await _uow.Repository <Film>().FindOneAsync(new FilmWithParticipantsAndGenresSpecification(id));

            _mapper.Map(filmForUpdate, film);

            await _uow.SaveAsync();

            return(await GetOne(film.Id));
        }
Пример #4
0
        public async Task <int> UpdateFilmAsync(FilmForUpdateDto filmForUpdateDto)
        {
            var film = await _repositoryManager.Films.GetAsync(filmForUpdateDto.Id);

            if (film == null)
            {
                throw new ValidationException("Фильм не найден", "");
            }

            filmForUpdateDto.UpdateEntity(film);

            _repositoryManager.Films.Update(film);
            return(await _repositoryManager.SaveChanges());
        }
Пример #5
0
        private void HandleFilmGenres(FilmForUpdateDto src, Film dest)
        {
            // remove genres
            var genresToRemove = dest.Genres.Where(x => !src.GenreIds.Contains(x.GenreId)).ToList();

            foreach (var genreToRemove in genresToRemove)
            {
                dest.Genres.Remove(genreToRemove);
            }

            // add genres
            var genresToAdd = src.GenreIds.Where(id => !dest.Genres.Any(x => x.GenreId == id)).ToList()
                              .Select(id => new FilmGenre {
                GenreId = id
            });

            foreach (var genreToAdd in genresToAdd)
            {
                dest.Genres.Add(genreToAdd);
            }
        }
Пример #6
0
        private void HandleFilmParticipants(FilmForUpdateDto src, Film dest)
        {
            /// remove film participants
            var participantsToRemove = dest.Participants
                                       .Where(x => !src.ParticipantsRoles.Select(x => new { x.ParticipantId, x.RoleId })
                                              .Any(y => y.ParticipantId == x.PersonId && y.RoleId == x.FilmRoleId)).ToList();

            foreach (var participantToRemove in participantsToRemove)
            {
                dest.Participants.Remove(participantToRemove);
            }

            // add film participants
            var participantsToAdd = src.ParticipantsRoles
                                    .Where(x => !dest.Participants.Any(y => y.PersonId == x.ParticipantId && y.FilmRoleId == x.RoleId)).ToList()
                                    .Select(x => new FilmParticipant {
                PersonId = x.ParticipantId, FilmRoleId = x.RoleId
            });

            foreach (var participantToAdd in participantsToAdd)
            {
                dest.Participants.Add(participantToAdd);
            }
        }
Пример #7
0
        public async Task <ActionResult> UpdateFilm(UpdateFilmVM updateFilmModel)
        {
            try
            {
                var    imageName    = "";
                string alertMessage = "";

                if (!ModelState.IsValid)
                {
                    return(View(updateFilmModel));
                }

                var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (userId == null)
                {
                    ModelState.AddModelError(string.Empty, "Пользователь не найден");
                    return(View(updateFilmModel));
                }

                // Если обновляется постер для фильма
                if (updateFilmModel.ImageFile != null)
                {
                    if (!ImageHelper.IsImage(updateFilmModel.ImageFile))
                    {
                        ModelState.AddModelError(string.Empty, "Неверный формат изображения ");
                        return(View(updateFilmModel));
                    }

                    imageName = ImageHelper.UploadImage(updateFilmModel.ImageFile, _webHostEnvironment);

                    // Удаляем старый файл
                    var filmDto = await _filmService.GetFilmAsync(updateFilmModel.Id);

                    string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");
                    string filePath      = Path.Combine(uploadsFolder, filmDto.ImgName);
                    if (!string.IsNullOrEmpty(filmDto.ImgName))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }

                var filmForUpdateDto = new FilmForUpdateDto
                {
                    Id          = updateFilmModel.Id,
                    Name        = updateFilmModel.Name,
                    Description = updateFilmModel.Description,
                    ReleaseYear = updateFilmModel.ReleaseYear,
                    Director    = updateFilmModel.Director,
                    ImgName     = imageName,
                    UserId      = userId
                };

                try
                {
                    var result = await _filmService.UpdateFilmAsync(filmForUpdateDto);

                    if (result == 0)
                    {
                        alertMessage = $"Обновить фильм не удалось !";
                        return(RedirectToAction("Index", "Film", new { message = alertMessage, messageType = MessageTypeEnum.Success }));
                    }
                }
                catch (ValidationException ex)
                {
                    return(RedirectToAction("Index", "Film", new { message = ex.Message, messageType = MessageTypeEnum.Danger }));
                }

                alertMessage = $"Фильм \"{updateFilmModel.Name}\" успешно обновлен!";
                return(RedirectToAction("Index", "Film", new { message = alertMessage, messageType = MessageTypeEnum.Success }));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("ShowError", "Error", new { message = ex.Message }));
            }
        }