Ejemplo n.º 1
0
        public ActionResult <InputActorViewModel> PostActor(InputActorViewModel inputModel)
        {
            var actor = _context.Add(_mapper.Map <Actor>(inputModel)).Entity;

            _context.SaveChanges();
            return(CreatedAtAction("GetActorById", new { id = actor.Id }, _mapper.Map <InputMovieViewModel>(inputModel)));
        }
Ejemplo n.º 2
0
        public Movie AddData(Movie movie)
        {
            _context.Movies.Add(movie);
            _context.SaveChanges();

            return(movie);
        }
Ejemplo n.º 3
0
        public ActionResult <Movie> PostMovie(Movie movie)
        {
            _context.Movies.Add(movie);
            _context.SaveChanges();

            return(CreatedAtAction(nameof(GetMovie), new { id = movie.Id }, movie));
        }
Ejemplo n.º 4
0
        public ActorDto UpdateActor(ActorDto actorDto)
        {
            if (actorDto.Id == null)
            {
                //упрощение для примера
                //лучше всего генерировать ошибки и обрабатывать их на уровне конроллера
                return(null);
            }

            try
            {
                var actor = _mapper.Map <Actor>(actorDto);

                _context.Update(actor);
                _context.SaveChanges();

                return(_mapper.Map <ActorDto>(actor));
            }
            catch (DbUpdateException)
            {
                if (!ActorExists((int)actorDto.Id))
                {
                    //упрощение для примера
                    //лучше всего генерировать ошибки и обрабатывать их на уровне конроллера
                    return(null);
                }
                else
                {
                    //упрощение для примера
                    //лучше всего генерировать ошибки и обрабатывать их на уровне конроллера
                    return(null);
                }
            }
        }
Ejemplo n.º 5
0
        public IActionResult CreateMovie(Movie movie)
        {
            _movieContext.Movies.Add(movie);
            _movieContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 6
0
        public MovieDto UpdateMovie(MovieDto movieDto)
        {
            if (movieDto.Id == null)
            {
                //упрощение для примера
                //лучше всего генерировать ошибки и обрабатывать их на уровне конроллера
                return(null);
            }

            try
            {
                var movie = _mapper.Map <Movie>(movieDto);

                _context.Update(movie);
                _context.SaveChanges();

                return(_mapper.Map <MovieDto>(movie));
            }
            catch (DbUpdateException)
            {
                if (!MovieExists((int)movieDto.Id))
                {
                    //упрощение для примера
                    //лучше всего генерировать ошибки и обрабатывать их на уровне конроллера
                    return(null);
                }
                else
                {
                    //упрощение для примера
                    //лучше всего генерировать ошибки и обрабатывать их на уровне конроллера
                    return(null);
                }
            }
        }
Ejemplo n.º 7
0
        public IHttpActionResult PutActor(int id, ActorModel actorModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != actorModel.Id)
            {
                return(BadRequest());
            }

            var actor = Mapper.Map <Actor>(actorModel);

            db.Entry(actor).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ActorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 8
0
        public IHttpActionResult PutMovie(int id, MovieModel movieModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != movieModel.Id)
            {
                return(BadRequest());
            }

            var movie = Mapper.Map <Movie>(movieModel);

            db.Entry(movie).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MovieExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 9
0
        private static void InitializeUsers( )
        {
            if (!context.Users.Any( ))
            {
                User user1 = new User {
                    Name = "Jaxon Glazier"
                };
                User user2 = new User {
                    Name = "Dory Ramsey"
                };
                User user3 = new User {
                    Name = "Laurel Harlan"
                };
                User user4 = new User {
                    Name = "Delroy Statham"
                };
                User user5 = new User {
                    Name = "Suzanne Siddall"
                };
                User user6 = new User {
                    Name = "Suz Truman"
                };

                context.Users.Add(user1);
                context.Users.Add(user2);
                context.Users.Add(user3);
                context.Users.Add(user4);
                context.Users.Add(user5);
                context.Users.Add(user6);

                context.SaveChanges( );
            }
        }
Ejemplo n.º 10
0
        public ActorDto AddActor(ActorDto actorDto)
        {
            var actor = _context.Add(_mapper.Map <Actor>(actorDto)).Entity;

            _context.SaveChanges();
            return(_mapper.Map <ActorDto>(actor));
        }
Ejemplo n.º 11
0
        public IHttpActionResult PutReview(int id, ReviewModel reviewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != reviewModel.Id)
            {
                return(BadRequest());
            }

            var review = Mapper.Map <Review>(reviewModel);

            db.Entry(review).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ReviewExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 12
0
        public ActionResult Create(DirectorsCreateViewModel directorsCreateViewModel)
        {
            if (ModelState.IsValid)
            {
                if (directorsCreateViewModel != null)
                {
                    directorsCreateViewModel.DirectorEntity.MovieDirectors = directorsCreateViewModel.MovieIds.Select(movieId => new MovieDirectors()
                    {
                        DirectorId = directorsCreateViewModel.DirectorEntity.Id,
                        MovieId    = movieId
                    }).ToList();
                }
                db.Directors.Add(directorsCreateViewModel.DirectorEntity);
                db.SaveChanges();
                TempData["Successful"] = "Director created successfully";
                return(RedirectToAction("Index"));
            }

            List <Movies>            moviesEntity          = db.Movies.ToList();
            MultiSelectList          moviesMultiSelectList = new MultiSelectList(moviesEntity, "Id", "Name");
            DirectorsCreateViewModel viewModel             = new DirectorsCreateViewModel()
            {
                DirectorEntity        = new Directors(),
                MoviesMultiSelectList = moviesMultiSelectList
            };

            return(View(directorsCreateViewModel));
        }
Ejemplo n.º 13
0
        public ActionResult CreateNew()
        {
            var director = new Director()
            {
                Name    = Request.Form["Name"],
                Surname = Request.Form["Surname"],
                //Retired = Convert.ToBoolean(Request.Form["Retired"])
            };

            director.Retired = true;
            if (Request.Form["Retired"].Equals("false"))
            {
                director.Retired = false;
            }


            if (ModelState.IsValid)
            {
                db.Directors.Add(director);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(director));
        }
Ejemplo n.º 14
0
        public ActorDto UpdateActor(ActorDto actorDto)
        {
            if (actorDto.Id == null)
            {
                return(null);
            }

            try
            {
                var actor = _mapper.Map <Actor>(actorDto);

                _context.Update(actor);
                _context.SaveChanges();

                return(_mapper.Map <ActorDto>(actor));
            }
            catch (DbUpdateException)
            {
                if (!ActorExists((int)actorDto.Id))
                {
                    return(null);
                }
                return(null);
            }
        }
Ejemplo n.º 15
0
        public RedirectToRouteResult Add(string Name, int ProductionYear, string BoxOfficeReturn, List <int> Directors, HttpPostedFileBase Image)
        {
            string filePath = CreateFilePath(Name, Image);
            var    entity   = new Movie()
            {
                Id              = 0,
                Name            = Name,
                ProductionYear  = ProductionYear.ToString(),
                BoxOfficeReturn = Convert.ToDouble(BoxOfficeReturn.Replace(",", "."), CultureInfo.InvariantCulture),
                FilePath        = filePath
                                  //MovieDirectors = new List<MovieDirector>()
            };

            entity.MovieDirectors = Directors.Select(e => new MovieDirector()
            {
                MovieId    = entity.Id,
                DirectorId = e
            }).ToList();
            db.Movies.Add(entity);
            db.SaveChanges();
            if (filePath != null)
            {
                Image.SaveAs(Server.MapPath("~/" + filePath));
            }
            Debug.WriteLine("Added Entity Id: " + entity.Id);
            TempData["Info"] = "Record successfully saved to database.";
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 16
0
        public IActionResult Edit(int id, [Bind("Name,FirstName,DateOfBirth")] EditActorViewModel editModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var actor = new Actor
                    {
                        Id          = id,
                        Name        = editModel.Name,
                        FirstName   = editModel.FirstName,
                        DateOfBirth = editModel.DateOfBirth
                    };
                    _context.Update(actor);
                    _context.SaveChanges();
                }
                catch (DbUpdateException)
                {
                    if (!ActorExists(id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(RedirectToAction(nameof(Index)));
            }

            return(View(editModel));
        }
Ejemplo n.º 17
0
 public void Add(MovieModel model)
 {
     try
     {
         // 1:
         //if (model.DirectorIds == null)
         //    model.DirectorIds = new List<int>();
         Movie entity = new Movie()
         {
             Name            = model.Name,
             BoxOfficeReturn = model.BoxOfficeReturn,
             ProductionYear  = model.ProductionYear,
             // 2:
             //MovieDirectors = (model.DirectorIds == null ? new List<int>() : model.DirectorIds).Select(dId => new MovieDirector()
             //{
             //    DirectorId = dId
             //}).ToList()
             // 3:
             MovieDirectors = (model.DirectorIds ?? new List <int>()).Select(dId => new MovieDirector()
             {
                 DirectorId = dId
             }).ToList()
         };
         _db.Movies.Add(entity);
         _db.SaveChanges();
     }
     catch (Exception exc)
     {
         throw exc;
     }
 }
Ejemplo n.º 18
0
        [HttpPost] // POST: api/movies
        public ActionResult <InputMovieViewModel> PostMovie(InputMovieViewModel inputModel)
        {
            var movie = _context.Add(_mapper.Map <Movie>(inputModel)).Entity;

            _context.SaveChanges();

            return(CreatedAtAction("GetById", new { id = movie.Id }, _mapper.Map <InputMovieViewModel>(inputModel)));
        }
Ejemplo n.º 19
0
 public IActionResult AddMovie(MoviesDb newMovie)
 {
     if (ModelState.IsValid)
     {
         _context.MoviesDb.Add(newMovie);
         _context.SaveChanges();
     }
     return(RedirectToAction("ListMovies"));
 }
Ejemplo n.º 20
0
 public IActionResult Create([Bind("Title,ReleaseDate,Genre,Price")] InputMovieViewModel inputModel)
 {
     if (ModelState.IsValid)
     {
         _context.Add(_mapper.Map <Movie>(inputModel));
         _context.SaveChanges();
     }
     return(View(inputModel));
 }
        //public ActionResult CreateNew()   //1
        public ActionResult CreateNew(FormCollection formCollection, List <int> Movies)    //2
        {
            var director = new Director()
            {
                //Name = Request.Form["Name"],  //1
                //Surname = Request.Form["Surname"]    //1
                Name    = formCollection["Name"],    //2
                Surname = formCollection["Surname"], //2
            };

            /*var retired = Request.Form["Retired"];*/      //1
            var retired  = formCollection["Retired"];
            var movieIds = formCollection["movieIds"].Split(',');

            director.Retired = true;
            if (retired.Equals("false"))
            {
                director.Retired = false;
            }
            if (String.IsNullOrWhiteSpace(director.Name))
            {
                ModelState.AddModelError("Name", "Director Name is required!");
            }
            if (String.IsNullOrWhiteSpace(director.Surname))
            {
                ModelState.AddModelError("Surname", "Director Surname is required!");
            }
            if (director.Name.Length > 100)
            {
                ModelState.AddModelError("Name", "Director Name must be maximum 100 characters!");
            }
            if (director.Surname.Length > 100)
            {
                ModelState.AddModelError("Name", "Director Surname must be maximum 100 characters!");
            }
            if (ModelState.IsValid)
            {
                db.Directors.Add(director);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            if (ModelState.IsValid)
            {
                director.MovieDirectors = Movies.Select(e => new MovieDirector()
                {
                    DirectorId = director.Id,
                    MovieId    = Convert.ToInt32(e),
                }).ToList();
                db.Directors.Add(director);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(director));
        }
Ejemplo n.º 22
0
        public ActionResult Create([Bind(Include = "Id,Title,Release,Kind,Price")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(movie));
        }
Ejemplo n.º 23
0
        public ActionResult Create([Bind(Include = "ActorID,LastName,FirstName")] Actor actor)
        {
            if (ModelState.IsValid)
            {
                db.Actors.Add(actor);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(actor));
        }
Ejemplo n.º 24
0
        public ActionResult Create([Bind(Include = "show_id,show_name,runtime,rating,image_path")] Show show)
        {
            if (ModelState.IsValid)
            {
                db.Shows.Add(show);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(show));
        }
Ejemplo n.º 25
0
        public IActionResult Create([Bind("Id,Name,LastName,Birthday")] InputActorViewModel inputModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(_mapper.Map <InputActorViewModel, Actor>(inputModel));
                _context.SaveChanges();
                return(RedirectToAction(nameof(Index)));
            }

            return(View(inputModel));
        }
Ejemplo n.º 26
0
        public ActionResult Create(Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(movie));
        }
Ejemplo n.º 27
0
        public ActionResult Create([Bind(Include = "Id,MovieName,MovieGenere,MovieReleaseYear,MovieCollectionAmount")] MoviesClass moviesClass)
        {
            if (ModelState.IsValid)
            {
                Db.MoviesClasses.Add(moviesClass);
                Db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(moviesClass));
        }
Ejemplo n.º 28
0
        public ActionResult Create([Bind(Include = "Id,Name,Img,ReleaseDate,ReviewScore")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                _context.Movies.Add(movie);
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(movie));
        }
Ejemplo n.º 29
0
        public ActionResult Create([Bind(Include = "id_bilet,cena,e_mail,vreme_na_rezervacija,id_proekcija,id_film,broj_sala,broj_sediste,broj_red")] Bilet bilet)
        {
            if (ModelState.IsValid)
            {
                db.Bilets.Add(bilet);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(bilet));
        }
Ejemplo n.º 30
0
        public ActionResult Create([Bind(Include = "card_id,card_num,card_type,card_name,card_expiry,card_cvv")] CreditCard creditCard)
        {
            if (ModelState.IsValid)
            {
                db.CreditCards.Add(creditCard);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(creditCard));
        }
Ejemplo n.º 31
0
        public HttpResponseMessage AddComment(string sessionKey, string movieTitle, CommentModel comment)
        {
            try
            {
                var context = new MoviesContext();
                var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new ArgumentException("Invalid authentication!");
                }
                var movie = context.Movies.FirstOrDefault(m => m.Title == movieTitle);
                if (movie == null)
                {
                    throw new ArgumentException("Movie not found!");
                }

                var newComment = new Comment()
                                     {
                                        Text = comment.Text,
                                        UserName = user.Username
                                     };
                movie.Comments.Add(newComment);
                context.SaveChanges();
                var response = this.Request.CreateResponse(HttpStatusCode.OK, newComment);
                return response;
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest,
                                             ex.Message);
                return response;
            }
        }
Ejemplo n.º 32
0
        public HttpResponseMessage PostLoginUser(UserModel model)
        {
            try
            {
                ValidateUsername(model.Username);

                var context = new MoviesContext();
                using (context)
                {
                    var user = context.Users.FirstOrDefault(u => u.Username == model.Username
                        && u.AuthCode == model.AuthCode);

                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid username or password");
                    }
                    if (user.SessionKey == null)
                    {
                        user.SessionKey = this.GenerateSessionKey(user.Id);
                        context.SaveChanges();
                    }

                    var loggedModel = new LoggedUserModel()
                    {
                        Username = model.Username,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        IsAdmin = user.IsAdmin,
                        SessionKey = user.SessionKey
                    };

                    var response = this.Request.CreateResponse(HttpStatusCode.Created,
                                        loggedModel);
                    return response;
                }
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest,
                                         ex.Message);
                return response;
            }
        }
Ejemplo n.º 33
0
        public HttpResponseMessage Vote(string sessionKey, int movieId, int vote)
        {
            try
            {
                var context = new MoviesContext();
                var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new ArgumentException("Invalid authentication!");
                }
                var movie = context.Movies.FirstOrDefault(m => m.Id == movieId);
                if (movie == null)
                {
                    throw new ArgumentException("Movie not found!");
                }

                if(vote<1 || vote>10)
                {
                    throw  new ArgumentException("Invalid vote!");
                }
                if(movie.Votes.Any(v=>v.User.Id==user.Id && v.Movie.Id==movieId))
                {
                    throw new Exception("You have voted for this movie!");
                }

                if(movie.Rating==null || movie.Rating==0)
                {
                    movie.Rating = vote;
                    movie.Votes.Add(new Vote()
                                        {
                                            Movie = movie,
                                            User = user,
                                            Rate = vote
                                        });
                }
                else
                {
                    movie.Rating = (movie.Rating + vote)/2;
                    movie.Votes.Add(new Vote()
                    {
                        Movie = movie,
                        User = user,
                        Rate = vote
                    });
                }

                context.SaveChanges();
                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                return response;
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest,
                                             ex.Message);
                return response;
            }
        }
Ejemplo n.º 34
0
        public HttpResponseMessage PutLogoutUser(string sessionKey)
        {
            try
            {
                var context = new MoviesContext();
                using (context)
                {
                    var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                    if (user == null)
                    {
                        throw new ArgumentException("Invalid user authentication.");
                    }

                    user.SessionKey = null;
                    context.SaveChanges();

                    var response = this.Request.CreateResponse(HttpStatusCode.OK);
                    return response;
                }
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
                return response;
            }
        }
Ejemplo n.º 35
0
        public HttpResponseMessage PostRegisterUser(UserModel model)
        {
            try
            {
                var dbContext = new MoviesContext();
                using (dbContext)
                {
                    this.ValidateUsername(model.Username);
                    this.ValidateFirstname(model.FirstName);
                    this.ValidateLastname(model.LastName);

                    var user = dbContext.Users.FirstOrDefault(u => u.Username.ToLower() == model.Username.ToLower());

                    if (user != null)
                    {
                        throw new InvalidOperationException("Users exists");
                    }

                    user = new User()
                    {
                        Username = model.Username,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        AuthCode = model.AuthCode,
                        IsAdmin = false
                    };

                    dbContext.Users.Add(user);
                    dbContext.SaveChanges();

                    user.SessionKey = this.GenerateSessionKey(user.Id);
                    dbContext.SaveChanges();

                    var loggedModel = new LoggedUserModel()
                    {
                        Username = model.Username,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        IsAdmin = false,
                        SessionKey = user.SessionKey
                    };

                    var response = this.Request.CreateResponse(HttpStatusCode.Created,
                                              loggedModel);
                    return response;
                }
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest,
                                             ex.Message);
                return response;
            }
        }
Ejemplo n.º 36
0
        public HttpResponseMessage MarkWatched(string sessionKey, int movieId)
        {
            try
            {
                var context = new MoviesContext();
                var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new ArgumentException("Invalid authentication!");
                }

                var movie = context.Movies.FirstOrDefault(m => m.Id == movieId);
                if(movie==null)
                {
                    throw new ArgumentException("Movie not found!");
                }

                var watched = context.Watches.FirstOrDefault(w => w.Movie.Id == movieId && w.User.Id == user.Id);
                if(watched!=null)
                {
                    throw new Exception("You have already added this movie to watched!");
                }

                movie.WhachedBy.Add(new Watches()
                                        {
                                            Movie = movie,
                                            User = user
                                        });
                context.SaveChanges();

                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                return response;
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest,
                                             ex.Message);
                return response;
            }
        }
Ejemplo n.º 37
0
        public HttpResponseMessage AddMovie(string sessionKey, AddMovieModel movie)
        {
            try
            {
                var context = new MoviesContext();
                var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                if (user == null || user.IsAdmin==false)
                {
                    throw new ArgumentException("You don't have permissions to add movies!");
                }

                var newMovie = new Movie()
                                   {
                                       Title = movie.Title,
                                       Description = movie.Description,
                                       CoverUrl = movie.CoverUrl
                                   };

                if (movie.Categories==null || movie.Categories.Count()==0)
                {
                    throw  new ArgumentException("Movie must have categories!");
                }

                foreach (var category in movie.Categories)
                {
                    var cat = context.Categories.FirstOrDefault(c => c.Name == category.Name);
                    if(cat==null)
                    {
                        context.Categories.Add(new Category()
                                                   {
                                                       Name = category.Name
                                                   });
                        context.SaveChanges();
                        cat = context.Categories.FirstOrDefault(c => c.Name == category.Name);
                    }
                    newMovie.Categories.Add(cat);
                }
                context.Movies.Add(newMovie);
                context.SaveChanges();

                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                return response;
            }
            catch (Exception ex)
            {
                var response = this.Request.CreateResponse(HttpStatusCode.BadRequest,
                                             ex.Message);
                return response;
            }
        }