예제 #1
0
        public ActionResult Edit([Bind(Include = "Movie, Genres, SelectedGenres")] CreateMovieViewModel model)
        {
            //ViewBag.Genres = new SelectList(db.Genres, "Id", "Name");


            if (model.SelectedGenres != null)
            {
                var newList = new List <Genre>();
                foreach (int id in model.SelectedGenres)
                {
                    newList.Add(new Genre()
                    {
                        Id = id
                    });
                }
                model.Movie.Genres = newList;
            }
            if (ModelState.IsValid)
            {
                facade.GetMovieGateway().Update(model.Movie);
                return(RedirectToAction("Index"));
            }
            //facade.GetMovieRepository().Edit(movie);
            return(View(model.Movie));
        }
예제 #2
0
        public async Task <Response <GetMovieViewModel> > CreateMovie(CreateMovieViewModel movieViewModel)
        {
            var movie  = _mapper.Map <Movie>(movieViewModel);
            var result = await _movieRepository.AddAync(movie);

            return(new Response <GetMovieViewModel>(_mapper.Map <GetMovieViewModel>(result), "Opration Succesfully"));
        }
예제 #3
0
        public async Task <Movie> CreateMovieFromCreateViewModelAsync(CreateMovieViewModel model)
        {
            var newTitle = _mapper.Map <CreateTitleViewModel>(model);
            var title    = await _titleService.CreateTitleFromCreateViewModelAsync(newTitle);

            if (title == null)
            {
                return(null);
            }

            var videoInfo = new VideoInfo();

            var videos = model.VideoPaths.Select(path => new MovieVideo()
            {
                Id        = Path.GetFileNameWithoutExtension(path),
                Location  = path,
                VideoInfo = videoInfo
            }).ToList();

            var newMovie = new Movie
            {
                TitleId = title.Id
            };

            newMovie.Videos           = videos;
            newMovie.Location         = Path.GetDirectoryName(videos.First().Location);
            newMovie.ThumbnailsAmount = Directory.GetFiles(Path.Combine(wwwRoot, newMovie.Location, "Thumbnails"), "*", SearchOption.TopDirectoryOnly).Length;

            if (await CreateMovieAsync(newMovie))
            {
                return(newMovie);
            }

            return(null);
        }
예제 #4
0
 public ActionResult Create(CreateMovieViewModel movie)
 {
     if (!ModelState.IsValid)
     {
         return(View(movie));
     }
     foreach (var item in movie.DoubanID.Split('\n'))
     {
         if (item.Trim().Length == 0)
         {
             continue;
         }
         JObject json = HtmlDecoder.GetJson("https://api.douban.com/v2/movie/subject/" + item.Replace("https://movie.douban.com/subject/", "").Replace("/", ""));
         JToken  msg;
         if (json.TryGetValue("msg", out msg))
         {
             ModelState.AddModelError("", string.Format("{0} {1} {2}", "添加编号为", item, "的电影 失败"));
         }
         else
         {
             ModelState.AddModelError("", string.Format("{0} {1} {2}", "添加编号为", item, "的电影 成功"));
             MovieManager.CreateJson(json, Server.MapPath("~/Content/Movie/"), AccountManager.GetId(CookieHepler.GetCookie("user")));
         }
     }
     return(View());
 }
예제 #5
0
        public async Task <ActionResult <Movie> > PostMovie(CreateMovieViewModel model)
        {
            User user = await _context.Users.FindAsync(User.Claims.ToList()[0].Value);

            if (user == null)
            {
                return(Unauthorized());
            }

            Category category = _categoryRepository.GetCategory(User, model.CategoryID);

            if (category == null)
            {
                return(NotFound("Category: " + model.CategoryID + " not found"));
            }

            Movie movie = new Movie
            {
                Author      = model.Author,
                Title       = model.Title,
                Description = model.Description,
                Year        = model.Year,
                ImageURL    = model.ImageURL != null ? model.ImageURL : CommonFunctions.GetImageURL(model.Title),
                CategoryID  = category.Id
            };

            _context.Movies.Add(movie);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetMovie", new { id = movie.Id }, movie));
        }
예제 #6
0
        public ActionResult Edit(int?id)
        {
            //ViewBag.Genres = new SelectList(db.Genres, "Id", "Name");
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Movie movie        = facade.GetMovieGateway().Find(id);
            var   selectGenres = new List <int>();

            foreach (var item in movie.Genres)
            {
                selectGenres.Add(item.Id);
            }
            var model = new CreateMovieViewModel()
            {
                Movie          = movie,
                Genres         = new MultiSelectList(facade.GetGenreGateway().ReadAll(), "Id", "Name"),
                SelectedGenres = selectGenres
            };

            if (movie == null)
            {
                return(HttpNotFound());
            }
            return(View(model));
        }
        public ActionResult Create(CreateMovieViewModel model)
        {
            var userId = userManager.GetUserId(HttpContext.User);

            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photo != null)
                {
                    string UploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    uniqueFileName = GetUniqueFileName(model.Photo.FileName);
                    string filePath = Path.Combine(UploadsFolder, uniqueFileName);
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                context.Movies.Add(new Movie()
                {
                    Titel          = model.Titel,
                    ReleaseDate    = model.ReleaseDate,
                    Lenght         = model.Lenght,
                    PhotoPath      = uniqueFileName,
                    WantToWatch    = model.WantToWatch,
                    Watched        = model.Watched,
                    YoutubeTrailer = model.YoutubeTrailer
                });
                context.SaveChanges();
            }
            return(RedirectToAction(nameof(Index)));
        }
예제 #8
0
        public async Task given_services_returns_success_then_Create_awaits_resource_creation(
            CreateMovieViewModel model,
            ISendCreateMovieCommandService serviceStub,
            IResourceAwaiter awaiterSpy,
            Success <MovieLocation> success,
            [NoAutoProperties] MoviesController sut)
        {
            // Arrange
            Mock.Get(serviceStub)
            .Setup(
                x =>
                x.SendCreateMovieCommand(It.Is <CreateNewMovie>(
                                             p =>
                                             p.Title == model.Title)))
            .ReturnsAsync(success);

            // Act
            ActionResult actual = await
                                  sut.Create(model, serviceStub, awaiterSpy);

            // Assert
            Uri location = success.Value.Uri;

            Mock.Get(awaiterSpy).Verify(x => x.AwaitResource(location));
        }
        public IActionResult Details(int?id)
        {
            var review = context.Reviews.Include(m => m.Movie).FirstOrDefault(m => m.ID == id);
            var movie  = new CreateMovieViewModel()
            {
                ID          = review.Movie.ID,
                ReleaseDate = review.Movie.ReleaseDate,
                Lenght      = review.Movie.Lenght,
                Titel       = review.Movie.Titel,
            };
            var model = new MovieReviewDetailsViewModel()
            {
                ID      = review.ID,
                MovieID = review.MovieID,
                Rating  = review.Rating,
                Comment = review.Comment,
                Movie   = movie
            };

            if (movie == null)
            {
                return(NotFound());
            }
            return(View(model));
        }
예제 #10
0
        public ActionResult Create(CreateMovieViewModel model, HttpPostedFileBase imagefile = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var movie = Mapper.Map <CreateMovieViewModel, Movie>(model);

            if (imagefile != null)
            {
                movie.FileName    = imagefile.FileName;
                movie.ContentType = imagefile.ContentType;
                //movie.Image
                movie.Image = new byte[imagefile.ContentLength];
                imagefile.InputStream.Read(movie.Image, 0, imagefile.ContentLength);
            }
            var result = new Movie();

            using (var repo = new Repository <Movie>())
            {
                result = repo.InsertOrUpdate(movie);
            }

            return(RedirectToAction("Detail", new { id = result.Id }));
        }
예제 #11
0
        public async Task <Guid> Create(CreateMovieViewModel model)
        {
            var movie = new Movie()
            {
                Name        = model.Name,
                Description = model.Description,
                Trailer     = model.Trailer,
                Link1       = model.Link1,
                Link2       = model.Link2,
                Poster      = model.Poster,
                Rating      = model.Rating,
                ReleaseDate = model.ReleaseDate
            };

            IEnumerable <string> genres = model.Genre
                                          .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            IEnumerable <string> actors = model.Actors
                                          .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            await this._repository.Add(movie);

            await this._moviesCategoriesService.Create(movie.Id, genres);

            await this._moviesActorsService.Create(movie.Id, actors);

            await this._repository.SaveChangesAsync();

            return(movie.Id);
        }
예제 #12
0
        public async Task <MovieViewModel> EditMovie(CreateMovieViewModel movie, string movieId)
        {
            var client            = new Client <MovieViewModel>(outputHelper);
            var data              = JsonConvert.SerializeObject(movie).ToString();
            var movieEditResponse = await client.UpdateAsStringAsync(data, $"{Constants.BaseRoute}{Constants.Movies}{movieId}");

            return(movieEditResponse);
        }
예제 #13
0
        // GET: Movies/Create
        public ActionResult Create()
        {
            var model = new CreateMovieViewModel();

            model.Categories = _db.Categories.Select(c => new SelectListItem {
                Text = c.Name, Value = c.Id.ToString()
            });
            return(View(model));
        }
예제 #14
0
        public async Task <MovieViewModel> CreateMovie(CreateMovieViewModel movie)
        {
            var client        = new Client <MovieViewModel>(outputHelper);
            var body          = JsonConvert.SerializeObject(movie).ToString();
            var url           = $"{Constants.BaseRoute}{Constants.Movies}";
            var movieResponse = await client.CreateAsStringAsync(body, url);

            return(movieResponse);
        }
예제 #15
0
        public async Task <IActionResult> AddMovie()
        {
            var viewModel = new CreateMovieViewModel
            {
                Genres = await this.genresRepository.All().To <GenresViewModel>().ToListAsync(),
            };

            return(this.View(viewModel));
        }
예제 #16
0
        public ActionResult Create()
        {
            var viewModel = new CreateMovieViewModel
            {
                Genres = this.context.Genres.ToList()
            };

            return(this.View(viewModel));
        }
예제 #17
0
        /// <summary>
        /// Сохранение фильма в БД
        /// </summary>
        /// <param name="model">Данные фильма</param>
        /// <param name="userName">Имя пользователя</param>
        /// <returns></returns>
        public async Task <long> CreateAsync(CreateMovieViewModel model, string userName)
        {
            // Проверка, имеется ли данный режиссер в БД, если нет - сохраняется
            var director = await _context.Directors
                           .FirstOrDefaultAsync(d => d.Name.ToLower().Trim() == model.DirectorName.ToLower().Trim());

            if (director == null)
            {
                director = new Director()
                {
                    Name = model.DirectorName.FormatAsName()
                };
                _context.Directors.Add(director);
                await _context.SaveChangesAsync();
            }

            // Поиск фильма по названию
            var movie = await _context.Movies
                        .FirstOrDefaultAsync(m => m.Name.Trim().ToLower() == model.Name.ToLower().Trim());

            if (movie != null)
            {
                throw new Exception("Фильм уже существует в БД");
            }

            // Проверка наличия пользователя в БД
            var user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == userName);

            if (user == null)
            {
                throw new Exception("Пользователь не найден");
            }

            // Перевод файла постера в набор байт
            byte[] poster = new byte[model.Poster.ContentLength];
            using (var stream = model.Poster.InputStream)
            {
                stream.Read(poster, 0, (int)stream.Length);
            }

            // Добавление фильма в БД
            movie = new Movie()
            {
                Name        = model.Name.FormatAsName(),
                Description = model.Description,
                ReleaseDate = model.ReleaseYear,
                Director    = director,
                Uploader    = user,
                Poster      = poster
            };

            _context.Movies.Add(movie);
            await _context.SaveChangesAsync();

            return(movie.Id);
        }
예제 #18
0
        public ActionResult Create([Bind(Include = "Name,Year,Plot,Image,ProducerId,ActorIDs,TmdbId")] CreateMovieViewModel model)
        {
            if (ModelState.IsValid)
            {
                Movie movie = new Movie
                {
                    Id     = new int(),
                    Name   = model.Name,
                    Year   = model.Year,
                    Plot   = model.Plot,
                    Image  = model.Image,
                    TmdbId = model.TmdbId
                };

                var producerId = int.Parse(model.ProducerId);
                //Producer producer = db.Producers.Find(ProducerId);
                Producer producer = _producerRepository.GetProducerById(producerId);
                movie.Producer = producer;

                if (model.ActorIDs != null)
                {
                    foreach (var id in model.ActorIDs)
                    {
                        var actorId = int.Parse(id);
                        var actor   = _actorRepository.GetActorById(actorId);
                        try
                        {
                            movie.Actors.Add(actor);
                        }
                        catch (Exception ex)
                        {
                            return(View("Error", new HandleErrorInfo(ex, "Movies", "Index")));
                        }
                    }
                }
                try
                {
                    _movieRepository.InsertMovie(movie);
                    _movieRepository.Save();
                }
                catch (Exception ex)
                {
                    return(View("Error", new HandleErrorInfo(ex, "Movies", "Index")));
                }

                //return RedirectToAction("Details", new { id=movie.ID});
                TempData["Name"]   = movie.Name;
                TempData["Method"] = "Create";
                TempData["Exists"] = "true";
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", "Something Failed.");
            return(View(model));
        }
예제 #19
0
        public async Task <IActionResult> AddMovie(CreateMovieViewModel inputModel)
        {
            if (this.ModelState.IsValid)
            {
                var movieId = await this.moviesService.CreateMovie(inputModel.Title, inputModel.ReleaseDate, inputModel.ImageUrl, inputModel.GenreId, inputModel.Description, inputModel.Country, inputModel.Runtime, inputModel.TrailerUrl);

                return(this.Redirect($"/Movies/ById/{movieId}"));
            }

            return(this.View());
        }
예제 #20
0
        public async Task <IActionResult> CreateMovie([FromBody] CreateMovieViewModel model, CancellationToken cancellationToken)
        {
            var result = await PublishAsync(new CreateMovieCommand.Command(model.Title, model.Year), cancellationToken);

            var id = result.AggregateRoot.GetIdentity();

            return(Ok(new
            {
                Id = id.Value
            }));
        }
예제 #21
0
        public ActionResult Create()
        {
            //IEnumerable<Genre> genres = facade.GetGenreGateway().ReadAll();

            var model = new CreateMovieViewModel()
            {
                Genres = new MultiSelectList(facade.GetGenreGateway().ReadAll(), "Id", "Name")
            };

            return(View(model));
        }
예제 #22
0
        public ActionResult CreateNewMovie(CreateMovieViewModel movieModel, HttpPostedFileBase picture)
        {
            if (!ModelState.IsValid)
            {
                return(View(movieModel));
            }
            string path     = getPicturePath(picture);
            var    newMovie = _mapper.Map <CreateMovieViewModel, CreateMovieModel>(movieModel);

            _movieService.CreateMovie(newMovie, path);
            return(RedirectToAction("Index", "Home"));
        }
예제 #23
0
        public async Task <IActionResult> Create(CreateMovieViewModel model)
        {
            try
            {
                var movieId = await this._moviesService.Create(model);

                return(this.Redirect("/home"));
            }
            catch (Exception e)
            {
                return(this.View("NameError"));
            }
        }
예제 #24
0
        public ActionResult CreateNewMovie()
        {
            var genresList    = getGenresList();
            var actorsList    = getActorsList();
            var producersList = getProducersList();
            var infoForSelect = new CreateMovieViewModel
            {
                Actors    = actorsList,
                Genres    = genresList,
                Producers = producersList
            };

            return(View(infoForSelect));
        }
        public IActionResult CreateMovie()
        {
            var movie = new CreateMovieViewModel();

            List <MovieGenreTagViewModel> tags = new List <MovieGenreTagViewModel>();

            foreach (var item in _applicationDbContext.Genres)
            {
                tags.Add(new MovieGenreTagViewModel {
                    Id = item.Id, Name = item.Name
                });
            }

            movie.MovieGenreTags = tags;
            return(View(movie));
        }
예제 #26
0
        public async Task <IActionResult> CreateAsync(CreateMovieViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uploadFolder  = _hostEnvironment.WebRootPath;
                string filename      = Path.GetFileNameWithoutExtension(model.img.FileName);
                string fileextension = Path.GetExtension(model.img.FileName);
                filename = filename + DateTime.Now.ToString("yymmssfff") + fileextension;
                string path = Path.Combine(uploadFolder + "/img/", filename);

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    model.img.CopyTo(fileStream);
                }

                string filename2      = Path.GetFileNameWithoutExtension(model.video.FileName);
                string fileextension2 = Path.GetExtension(model.video.FileName);
                filename2 = filename2 + DateTime.Now.ToString("yymmssfff") + fileextension2;
                string path2 = Path.Combine(uploadFolder + "/videos/", filename2);


                using (var fileStream = new FileStream(path2, FileMode.Create))
                {
                    model.video.CopyTo(fileStream);
                }

                Models.Movie movie = new Models.Movie();
                movie.title        = model.title;
                movie.video        = "videos/" + filename2;
                movie.release_date = model.release_date;
                movie.img          = "img/" + filename;
                movie.active       = model.active;
                movie.duration     = model.duration;
                movie.description  = model.description;
                movie.date_added   = DateTime.Now;
                _context.Movies.Add(movie);
                await _context.SaveChangesAsync();

                TempData["SuccesMessage"] = "Filmul a fost adaugat cu succes!";
                return(RedirectToAction("List"));
            }

            else
            {
                return(View(model));
            }
        }
예제 #27
0
 public ActionResult Create(CreateMovieViewModel model)
 {
     if (model.SelectedGenres != null)
     {
         var newList = new List <Genre>();
         foreach (int id in model.SelectedGenres)
         {
             newList.Add(new Genre()
             {
                 Id = id
             });
         }
         model.Movie.Genres = newList;
     }
     facade.GetMovieGateway().Add(model.Movie);
     return(RedirectToAction("Index", "Movie"));
 }
예제 #28
0
        public async Task <IActionResult> Create(CreateMovieViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var trailer = viewModel.Trailer.UrlToEmbedCode();
                if (trailer == null)
                {
                    return(View(viewModel));
                }
                var movie = this._mapper.Map <CreateMovieViewModel, Movie>(viewModel);
                movie.Trailer = trailer;
                _dbContext.Add(movie);
                await _dbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(viewModel));
        }
예제 #29
0
        public async Task <ActionResult> AddMovie(CreateMovieViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var id = await _movieService.CreateAsync(model, User.Identity.Name);

                    return(RedirectToActionPermanent("GetMovie", new { id }));
                }
                catch (Exception e)
                {
                    ViewData["Error"] = e.Message;
                    return(View("MovieError"));
                }
            }
            return(View());
        }
        public async Task <IActionResult> CreateMovie(CreateMovieViewModel movieModel)
        {
            if (!TryValidateModel(movieModel))
            {
                return(View(movieModel));
            }

            using (var memoryStream = new MemoryStream())
            {
                try
                {
                    await movieModel.Cover.CopyToAsync(memoryStream);
                }
                catch {}

                var createMovie = new Movie()
                {
                    Title       = movieModel.Title,
                    Cover       = memoryStream.ToArray(),
                    Releas      = movieModel.Releas,
                    Director    = movieModel.Director,
                    Description = movieModel.Description,
                    Duration    = movieModel.Duration,
                    UrlTrailer  = movieModel.UrlTrailer
                };

                List <MovieGenresMovie> selectedTags = new List <MovieGenresMovie>();
                foreach (var item in movieModel.MovieGenreTags)
                {
                    if (item.Checked == true)
                    {
                        selectedTags.Add(new MovieGenresMovie {
                            MovieGenreId = item.Id, MovieId = createMovie.Id
                        });
                    }
                }
                createMovie.Genre = selectedTags;

                _applicationDbContext.Movies.Add(createMovie);
                _applicationDbContext.SaveChanges();

                return(RedirectToAction("DetailMovie", new { Id = createMovie.Id }));
            }
        }