Пример #1
0
        public ActionResult AddReview(MovieModel moviemodel)
        {
            var model = new ReviewModel();
            model.MovieId = moviemodel.MovieId;
            model.ReviewId = Guid.NewGuid().ToString();

            return View("AddReview", model);
        }
Пример #2
0
 public ActionResult AddMovie(MovieModel model)
 {
     if (string.IsNullOrEmpty(model.MovieId))
     {
         model.MovieId = Guid.NewGuid().ToString();
     }
     return AddReview(model);
 }
Пример #3
0
        public ActionResult Submit_MovieInput(MovieModel model)
        {
            if (!model.Validate())
            {
                @ViewBag.ValidationError = "Check details and submit again";
                return View(model);
            }

            return AddMovie(model);
        }
        public async Task <ActionResult <MovieModel> > GetMovieAsync(long id)
        {
            var mov = await _db.Movies.Include(x => x.SubCategory).FirstOrDefaultAsync(x => x.Id == id);

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

            var actors = await _db.MovieActors.Include(x => x.Actor).Where(x => x.MovieId == mov.Id).ToListAsync();

            var links = await _db.MovieLinks.Where(x => x.MovieId == mov.Id).ToListAsync();

            var model = new MovieModel
            {
                Movie  = mov,
                Actors = actors,
                Links  = links
            };

            return(model);
        }
        public async void Get_ActionExecutes_ReturnsRequestedProduct()
        {
            //-- Arrange
            _mockMovieRepo.Setup(repo => repo.GetMovieAsync(10))
            .Returns(Task.FromResult(
                         new Movie {
                Id = 10, Title = "Movie 1"
            }));

            var expected = new MovieModel {
                Id = 10, Title = "Movie 1"
            };

            //-- Act
            var result = await _controller.Get(10);

            //-- Assert
            var okResult = Assert.IsType <OkObjectResult>(result.Result);
            var actual   = Assert.IsType <MovieModel>(okResult.Value);

            Assert.Equal(expected.Id, actual.Id);
        }
        /// <summary>
        /// Search in TheMovieDb WebService for movies
        /// </summary>
        /// <param name="keyword">Movie name</param>
        /// <returns>List of movies matched search criteria</returns>
        public List <MovieModel> Search(string keyword)
        {
            try
            {
                var request = new RestRequest("search/movie", Method.GET);
                request.AddParameter("api_key", _configurationFactory.ApiKey);
                request.AddParameter("query", keyword);
                request.AddParameter("page", "1");

                var response = _client.Execute <TheMoviesDbSearchResultsModel>(request);
                var results  = response.Data.results;
                var movies   = new List <MovieModel>();
                foreach (var movie in results)
                {
                    var newmovie = new MovieModel
                    {
                        Id          = movie.id.ToString(),
                        Description = movie.overview,
                        Title       = movie.title,
                        PosterUrl   = "https://image.tmdb.org/t/p/w300/" + movie.poster_path,
                        Vote        = movie.vote_average,
                        ReleaseDate = movie.release_date
                    };
                    DateTime date;
                    var      valid = DateTime.TryParse(movie.release_date, out date);
                    newmovie.ReleaseYear = valid ? date.Year : 0;

                    movies.Add(newmovie);
                }

                return(movies);
            }
            catch (Exception)
            {
                // Should Log Here Using Elmah or anyservice and save log in DB
                // For Testing will return Empty list
                return(new List <MovieModel>());
            }
        }
Пример #7
0
    public static IList<MovieModel> GetMoviesByRottenTomatoAudienceRating(int count = 10, int skip = 0)
    {
        try
            {
                MoviesDBDataContext db = new MoviesDBDataContext();
                var movies = (from m in db.RtMovies
                              select m).OrderByDescending(m => m.AudienceScore).Skip(skip).Take(count).ToList();

                List<MovieModel> results = new List<MovieModel>();
                foreach (var m in movies)
                {
                    MovieModel t = new MovieModel(m.NetflixMovy, m);
                    results.Add(t);
                }

                return results;
            }
            catch
            {
                return null;
            }
    }
Пример #8
0
        // GET: Movie
        public ActionResult AddMovie()
        {
            IMDB_Context context    = new IMDB_Context();
            var          actorslist = context.Actors.Select(x => new SelectListItem
            {
                Value = x.ActorId.ToString(),
                Text  = x.Name
            }).ToList();
            var producerlist = context.Producers.Select(x => new SelectListItem
            {
                Value = x.ProducerId.ToString(),
                Text  = x.Name
            }).ToList();

            MovieModel model = new MovieModel()
            {
                Actors    = actorslist,
                Producers = producerlist
            };

            return(View("AddMovie", model));
        }
Пример #9
0
        public void PartialUpdateMovie_Returns_NoContentResult()
        {
            // Arrange
            var movieRepositoryMock = new Mock <IMovieRepository>();
            var subGenreIMapperMock = new MapperConfiguration(config =>
            {
                config.AddProfile(new MovieMapper());
            });
            var movieMapper = subGenreIMapperMock.CreateMapper();
            MoviesController movieApiController = new MoviesController(movieRepositoryMock.Object, mapper: movieMapper);
            var patchDoc   = new JsonPatchDocument <MoviesUpdateDTO>();
            var movieModel = new MovieModel()
            {
                Name        = "Adult Content",
                DateCreated = DateTime.Parse("15 May 2015"),
                Id          = Guid.NewGuid(),
                GenreId     = Guid.NewGuid(),
                Genres      = new GenreModel(),
            };
            var movieDto = new MoviesUpdateDTO()
            {
                Id          = movieModel.Id,
                Name        = movieModel.Name,
                DateCreated = movieModel.DateCreated,
                GenreId     = movieModel.GenreId,
                SubGenreId  = Guid.NewGuid()
            };

            movieRepositoryMock.Setup(repo => repo.GetMovie(It.IsAny <Guid>())).Returns(movieModel);
            patchDoc.ApplyTo(movieDto, movieApiController.ModelState);
            movieRepositoryMock.Setup(repo => repo.UpdateMovie(It.IsAny <MovieModel>())).Returns(true);
            // Act
            var subGenreResult  = movieApiController.PartialUpdateMovie(movieModel.Id, patchDoc);
            var noContentResult = subGenreResult as NoContentResult;

            // Assert
            Assert.True(noContentResult.StatusCode is StatusCodes.Status204NoContent);
        }
Пример #10
0
        public static void SaveList(bool showMessage, Button saveButton, Sections section, ListView listView)
        {
            StreamWriter saveFile = new StreamWriter(savePath);

            foreach (ListViewItem item in listView.Items)
            {
                if (section == Sections.Movie)
                {
                    MovieModel movieData     = new MovieModel(item.Text, item.SubItems[1].Text);
                    string     formattedData = DataFormatController.NewMovieDataFormatter(movieData);
                    saveFile.WriteLine(formattedData);
                }

                if (section == Sections.Serie)
                {
                    SerieModel serieData     = new SerieModel(item.Text, item.SubItems[1].Text);
                    string     formattedData = DataFormatController.NewSerieDataFormatter(serieData);
                    saveFile.WriteLine(formattedData);
                }

                if (section == Sections.Book)
                {
                    BookModel bookData      = new BookModel(item.Text, item.SubItems[1].Text, item.SubItems[2].Text);
                    string    formattedData = DataFormatController.NewBookDataFormatter(bookData);
                    saveFile.WriteLine(formattedData);
                }
            }

            saveFile.Close();

            if (showMessage)
            {
                MessageBox.Show(section + "list saved!");
                showMessage          = false;
                saveButton.Enabled   = false;
                saveButton.BackColor = Colors.OptionButtonsDeactiveColor;
            }
        }
Пример #11
0
        public async Task <IActionResult> Edit(MovieModel model, IFormFile file)
        {
            if (ModelState.IsValid)
            {
                var entity = _movieService.GetById(model.MovieId);
                if (entity == null)
                {
                    return(NotFound());
                }
                entity.Name     = model.Name;
                entity.Category = model.Category;
                entity.Director = model.Director;
                entity.Stars    = model.Stars;
                entity.Year     = model.Year;
                entity.Review   = model.Review;

                if (file != null)
                {
                    entity.ImageUrl = file.FileName;
                    var path  = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", file.FileName);
                    var path2 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", "1-" + file.FileName);
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    using (var stream = new FileStream(path2, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }

                _movieService.Update(entity);

                TempData["message"] = $"{entity.Name} başarıyla güncellendi.";
                return(RedirectToAction("MovieList"));
            }
            return(View(model));
        }
Пример #12
0
        public async Task EditAsync(MovieModel model)
        {
            if (await _context.Movies.AnyAsync(x => x.Name.Trim().ToLower() == model.Name.Trim().ToLower() && x.Id != model.Id))
            {
                throw new DuplicatedExcpection("Filme já cadastrado");
            }

            var category = await _context.MovieCategories.FirstOrDefaultAsync(x => x.Id == model.CategoryId);

            if (category == null)
            {
                throw new NotFoundException("Categoria não encontrada");
            }

            var movie = await _context.Movies
                        .Include(x => x.Category)
                        .FirstOrDefaultAsync(x => x.Id == model.Id);

            if (movie == null)
            {
                throw new NotFoundException("Filme não Encontrado");
            }
            movie.Name           = model.Name.Trim();
            movie.Duration       = model.Duration.Value;
            movie.Classification = model.Classification.Value;
            movie.Category       = category;
            movie.Synopsis       = model.Synopsis;

            try
            {
                _context.Movies.Update(movie);
                await _context.SaveChangesAsync();
            }
            catch
            {
                throw new Exception("Não foi possível cadastrar esse filme");
            }
        }
Пример #13
0
        /// <summary>
        /// The generate picture gallery.
        /// </summary>
        private static void GeneratePictureGallery()
        {
            bool changed = false;

            for (int index = 0; index < MovieDatabase.Count; index++)
            {
                MovieModel movie = MovieDatabase[index];
                if (!inGallery.Contains(movie.MovieUniqueId))
                {
                    if (movie.SmallPoster != null)
                    {
                        var superTip = new SuperToolTip {
                            AllowHtmlText = DefaultBoolean.True
                        };

                        superTip.Items.AddTitle(string.Format("{0} ({1})", movie.Title, movie.Year));

                        var galleryItem = new GalleryItem(movie.SmallPoster, movie.Title, string.Empty)
                        {
                            Tag = movie.MovieUniqueId, SuperTip = superTip
                        };

                        if (!galleryGroup.Items.Contains(galleryItem))
                        {
                            galleryGroup.Items.Add(galleryItem);
                            inGallery.Add(movie.MovieUniqueId);

                            changed = true;
                        }
                    }
                }
            }

            if (changed)
            {
                GalleryChanged(null, null);
            }
        }
Пример #14
0
        // Returns scraped movie data
        public async Task <IEnumerable <MovieModel> > GetMovies()
        {
            string url  = "https://www.imdb.com/chart/top?ref_=nb_mv_3_chttp";
            string html = await SpiderModel.HttpGet(url);

            if (html != null)
            {
                HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);
                var Images = htmlDoc.DocumentNode.SelectNodes("//td[@class='posterColumn']//img");
                var Titles = htmlDoc.DocumentNode.SelectNodes("//td[@class='titleColumn']//a");
                var Years  = htmlDoc.DocumentNode.SelectNodes("//span[@class='secondaryInfo']");
                if (Years != null)
                {
                    List <MovieModel> movieList = new List <MovieModel>();
                    for (int z = 0; z < Years.Count; z++)
                    {
                        MovieModel    movie = new MovieModel();
                        HtmlAttribute src   = Images[z].Attributes[@"src"];
                        string[]      split = src.Value.Split('@');
                        movie.Image = split.Length == 3 ? (split[0] + "@@._V1_UY368_CR3,0,240,360_AL_.jpg") : (split[0] + "@._V1_UY368_CR3,0,240,360_AL_.jpg");
                        movie.Title = Titles[z].InnerText;
                        movie.Year  = Years[z].InnerText.Substring(1, 4);
                        movieList.Add(movie);
                    }
                    MoviesListModel.SetMoviesData(movieList);
                    return(MoviesListModel.GetMoviesData());
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Пример #15
0
        public ActionResult MovieList(string sortingOrder, string sortingDir, string searchText, string filterValue, int?pageNo)
        {
            MovieModel model = new MovieModel();

            try
            {
                ViewBag.CurrentSortOrder = sortingOrder;

                if (string.IsNullOrEmpty(sortingDir))
                {
                    sortingDir = "ASC";
                }
                if (pageNo == null)
                {
                    pageNo = 1;
                }

                ViewBag.sortingDir = sortingDir;
                if (searchText != null)
                {
                    pageNo = 1;
                }
                else
                {
                    searchText = filterValue;
                }
                ViewBag.FilterValue = searchText;
                model.GetAllMovies(model, sortingOrder, sortingDir, searchText);

                int pageSize   = 5;
                int pageNumber = (pageNo ?? 1);

                return(View(model.MovieWithProducer.ToPagedList(pageNumber, pageSize)));
            }
            catch (Exception ex) { }

            return(View(model.MovieWithProducer.ToPagedList(1, 3)));
        }
Пример #16
0
        public async Task <IActionResult> AddMovie(string name, string description, [FromForm] ImageModel imageModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var movieModel = new MovieModel()
            {
                Name        = name,
                Description = description,
                Logo        = imageModel.Image
            };

            var result = await _movieService.AddMovie(movieModel);

            if (result.Error != null)
            {
                return(BadRequest(result));
            }

            return(Ok(result));
        }
Пример #17
0
        public ActionResult Create(MovieModel model)
        {
            try
            {
                //Validate
                if (ModelState.IsValid)
                {
                    //Save if valid
                    var movie = model.ToDomain();
                    _database.Add(movie);

                    // PostRedirectGet
                    return(RedirectToAction("Index"));
                }
                ;
            } catch (Exception e)
            {
                // Don't use Exception overload - doesn't work
                ModelState.AddModelError("", e.Message);
            };

            return(View(model));
        }
Пример #18
0
        public IActionResult Add(MovieModel movie)
        {
            /*if(movie == null)
             * {
             * return View("Add");
             * }
             *
             * if (string.IsNullOrWhiteSpace(movie.Genre) ||
             *  string.IsNullOrWhiteSpace(movie.Title))
             * {
             * return View("Add");
             * }
             */

            if (ModelState.IsValid)
            {
                movies.Add(movie);

                return(RedirectToAction("Get"));
            }

            return(View("Add", movie));
        }
Пример #19
0
        /// <summary>
        /// Load movie data by imdb id
        /// </summary>
        /// <param name="imdbId"></param>
        /// <returns></returns>
        public static MovieModel LoadMovieByImdbId(string imdbId)
        {
            if (string.IsNullOrWhiteSpace(imdbId))
            {
                throw new ArgumentNullException(nameof(imdbId));
            }

            string     imdb       = imdbId.StartsWith("tt") ? imdbId : string.Concat("tt", imdbId);
            MovieModel movieModel = new MovieModel();

            using (HttpClient cl = new HttpClient())
            {
                string url = string.Format(MOVIE_URL, imdb, API_KEY_V3);

                string movieJson = cl.GetStringAsync(url).Result;
                movieModel.InfoData = JsonConvert.DeserializeObject <Model.Movie.MovieInfoModel>(movieJson);

                movieModel.PosterData = LoadImagesById(cl, imdb);
                movieModel.VideoData  = LoadVideosById(cl, imdb);

                return(movieModel);
            }
        }
Пример #20
0
        // GET: /movies/random
        public IActionResult Random()
        {
            var movie = new MovieModel {
                Name = "The Blind side.."
            };
            var customers = new List <CustomerModel>
            {
                new CustomerModel {
                    Name = "Ashok", Id = 1
                },
                new CustomerModel {
                    Name = "Sudhakar", Id = 2
                }
            };

            var model = new RandomMovieViewModel
            {
                Movie     = movie,
                Customers = customers
            };

            return(View(model));
        }
Пример #21
0
        public ActionResult Edit(MovieModel model)
        {
            try
            {
                //Validate
                if (ModelState.IsValid)
                {
                    //Save if valid
                    var movie = model.ToDomain();
                    _database.Update(movie.Id, movie);

                    //PRG
                    return(RedirectToAction("Edit", new { id = movie.Id }));
                }
                ;
            } catch (Exception e)
            {
                //Don't use Exception overload - doesn't work
                ModelState.AddModelError("", e.Message);
            };

            return(View(model));
        }
Пример #22
0
        public ActionResult Edit(MovieModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Id == 0)
                {
                    MovieManager.Create(model.ToData());
                }

                else
                {
                    MovieManager.Update(model.ToData());
                }


                // sūtam atpakaļ uz kino rediģēšanas formu
                return(RedirectToAction("Edit", "Cinema", new { id = model.CinemaId }));
            }



            return(View(model));
        }
Пример #23
0
        // Update movie data
        public void UpdateMovieInTable(MovieModel movie)
        {
            string updateString = "update dbo.Movies set " +
                                  "Rating = @rating, Title = @title, Year = @year, Rental_Cost = @price, Copies = @copies, Plot = @plot, Genre = @genre " +
                                  "where MovieID = @id";

            SqlCommand updateCommand = new SqlCommand(updateString, _connection);

            updateCommand.Parameters.AddWithValue("@id", movie.MovieId);
            updateCommand.Parameters.AddWithValue("@rating", movie.Rating);
            updateCommand.Parameters.AddWithValue("@title", movie.Title);
            updateCommand.Parameters.AddWithValue("@year", movie.Year);
            updateCommand.Parameters.AddWithValue("@price", movie.RentalPrice);
            updateCommand.Parameters.AddWithValue("@copies", movie.Copies);
            updateCommand.Parameters.AddWithValue("@plot", movie.Plot);
            updateCommand.Parameters.AddWithValue("@genre", movie.Genre);

            _connection.Open();
            updateCommand.ExecuteNonQuery();
            _connection.Close();

            DataUpdateEventAndSignature(nameof(UpdateMovieInTable));
        }
Пример #24
0
        // Add new movie to database
        public void AddMovieToTable(MovieModel movie)
        {
            string insertString = "insert into dbo.Movies " +
                                  "(Rating, Title, Year, Rental_Cost, Copies, Plot, Genre)" +
                                  "values " +
                                  "(@rating, @title, @year, @price, @copies, @plot, @genre)";

            SqlCommand insertCommand = new SqlCommand(insertString, _connection);

            insertCommand.Parameters.AddWithValue("@rating", movie.Rating);
            insertCommand.Parameters.AddWithValue("@title", movie.Title);
            insertCommand.Parameters.AddWithValue("@year", movie.Year);
            insertCommand.Parameters.AddWithValue("@price", movie.RentalPrice);
            insertCommand.Parameters.AddWithValue("@copies", movie.Copies);
            insertCommand.Parameters.AddWithValue("@plot", movie.Plot);
            insertCommand.Parameters.AddWithValue("@genre", movie.Genre);

            _connection.Open();
            insertCommand.ExecuteNonQuery();
            _connection.Close();

            DataUpdateEventAndSignature(nameof(AddMovieToTable));
        }
Пример #25
0
        public ActionResult Edit(MovieModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var item = model.ToDomain();

                    var existing = _database.GetAll()
                                   .FirstOrDefault(i => i.Id == model.Id);
                    _database.Edit(existing.Name, item);

                    return(RedirectToAction("Index"));
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                };
            }
            ;

            return(View(model));
        }
Пример #26
0
        public ActionResult Delete ( MovieModel model )
        {
            //Exception handling

            // Always do PRG for modifications
            //   Post, Redirect, Get

            //Check for model validity
            try
            {
                _database.Delete(model.Id);

                //Redirect to list
                return RedirectToAction(nameof(Index));
            } catch (Exception e)
            {
                //NEVER USE THIS - IT DOESN'T WORK
                //ModelState.AddModelError("", e);
                ModelState.AddModelError("", e.Message);
            };

            return View(model);
        }
Пример #27
0
        public ActionResult Delete(MovieModel model)
        {
            // Always do PRG for modifications
            //   Post, Redirect, Get

            //Check for model validity

            try
            {
                _database.Delete(model.Id);

                //Redirect to list
                return(RedirectToAction(nameof(Index)));
            } catch (Exception e)
            {
                //Never use this - it doesn't work
                //ModelState.AddModelError("", e);
                ModelState.AddModelError("", e.Message);
            };


            return(View(model));
        }
Пример #28
0
        void SyncToMain(MovieModel results)
        {
            this.InvokeOnMainThread(delegate
            {
                if (results != null)
                {
                    // first clear the data
                    // searchResults.Clear();

                    searchResults.Add(results);
                    TableView.ReloadData();
                }
                else
                {
                    // first clear the data
                    searchResults.Clear();
                    TableView.ReloadData();
                    new UIAlertView("", "Could not retrieve movies ! Try again", null, "OK").Show();
                }

                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            });
        }
Пример #29
0
        public void ShouldSaveMovie()
        {
            var movieData = new MovieModel()
            {
                Title       = "Resident Evil",
                Status      = "Disponível",
                Year        = 2002,
                ReleaseDate = "01/05/2002",
                Cast        = { "Milla Jovovich", "Ali Larter", "Ian Glen", "Shawn Roberts" },
                Plot        = "A missão do esquadrão e da Alice é desligar a Rainha Vermelha e coletar dados sobre o incidente.",
                Cover       = CoverPath() + "resident-evil-2002.jpg"
            };

            Database.RemoveByTitle(movieData.Title);

            _movie.Add();
            _movie.Save(movieData);

            Assert.That(
                _movie.HasMovie(movieData.Title),
                $"Erro ao verificar se o filme {movieData.Title} foi cadastrado."
                );
        }
Пример #30
0
        /// <summary>
        /// Edits the movie.
        /// </summary>
        /// <param name="model">The movie model.</param>
        /// <returns>boolean true and false</returns>
        /// <exception cref="System.Exception">system exception</exception>
        public bool EditMovie(MovieModel model)
        {
            ////try is initilized to execute ignore the error and continue normal flow of the execution
            try
            {
                ////connection is established between databse and application
                using (var connection = new SqlConnection("Data Source=.;Initial Catalog=Bollywood;Integrated Security=True"))
                {
                    int rowsAffected = connection.Execute("Edit", new { model.Id, model.MovieName, model.Actor, model.Director, model.Producer, model.DateOfRelease }, commandType: CommandType.StoredProcedure);
                    connection.Close();
                    if (rowsAffected > 0)
                    {
                        return(true);
                    }

                    return(false);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Пример #31
0
        public IEnumerable <MovieModel> GetAll()
        {
            var movies = new List <MovieModel>();

            foreach (var movie in _context.Movies.OrderBy(a => a.Id))
            {
                var mov = new MovieModel
                {
                    _id             = movie.Id,
                    title           = movie.Title,
                    numberInStock   = movie.NumberInStock,
                    dailyRentalRate = movie.DailyRentalRate,
                    genre           = new MovieGenreModel
                    {
                        _id  = movie.MovieGenreId,
                        name = _context.MovieGenres.FirstOrDefault(b => b.Id == movie.MovieGenreId).Name,
                    }
                };

                movies.Add(mov);
            }
            return(movies);
        }
Пример #32
0
        public void ShouldSaveMovie()
        {
            var movieData = new MovieModel()
            {
                Title       = "Resident Evil",
                Status      = "Disponível",
                Year        = 2002,
                ReleaseDate = "01/05/2002",
                Cast        = { "Milla Jovovich", "Ali Larter", "Ian Glen", "Shawn Roberts" },
                Plot        = "Este é o resumo do filme",
                Cover       = CoverPath() + "Foto_Raphael_Mantilha_Shop_DPedro.jpg"
            };

            Database.RemoveByTitle(movieData.Title);

            _moviePage.Add();
            _moviePage.Save(movieData);

            Assert.That(
                _moviePage.HasMovie(movieData.Title),
                $"Erro ao verificar se o filme {movieData.Title} foi cadastrado."
                );
        }
Пример #33
0
        private Movies ConvertMovieModelToMovies(MovieModel objMovie)
        {
            Movies movie = null;

            using (IMDB_Context context = new IMDB_Context())
            {
                Producers     objProducer = context.Producers.Where(x => x.ProducerId == objMovie.ProducerId).SingleOrDefault <Producers>();
                List <Actors> _ActorsList = new List <Actors>();
                foreach (var item in objMovie.ActorsId)
                {
                    _ActorsList.Add(context.Actors.Where(x => x.ActorId == item).SingleOrDefault());
                }
                movie = new Movies()
                {
                    Name          = objMovie.Name,
                    Plot          = objMovie.Plot,
                    Yearofrelease = Convert.ToDateTime(objMovie.Yearofrelease),
                    Producer      = objProducer,
                    Actors        = _ActorsList
                };
            }
            return(movie);
        }
Пример #34
0
 public void AddToWishList(MovieModel movie, int userId)
 {
     try
     {
         using (SqlConnection conn = new SqlConnection(_builder.ConnectionString))
         {
             using (SqlCommand cmd = new SqlCommand("dbo.AddToWishlist", conn))
             {
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.AddWithValue("@pUserId", userId);
                 cmd.Parameters.AddWithValue("@pMovieId", movie.MovieId.ToString());
                 conn.Open();
                 cmd.ExecuteNonQuery();
                 conn.Close();
             }
         }
     }
     catch (SqlException e)
     {
         Console.WriteLine(e);
     }
     //return response; // might change to return something?
 }
Пример #35
0
    private List<MovieModel> SaveMoviesToDB(IList<dynamic> movies)
    {
        List<MovieModel> netflixMovies = new List<MovieModel>();
        if (movies != null)
        {

            MoviesDBDataContext db = new MoviesDBDataContext();
            foreach (var movie in movies)
            {
                string id = movie.Id;
                NetflixMovy movieFromDb = (from m in db.NetflixMovies
                                           where m.NetflixID == id
                                           select m).FirstOrDefault();
                if (movieFromDb == null)//If not already in db add it
                {
                    MovieModel nm = new MovieModel(movie);

                    db.NetflixMovies.InsertOnSubmit(nm.Netflix);
                    movieFromDb = nm.Netflix;
                }
                MovieModel mm = new MovieModel(movieFromDb, null);
                netflixMovies.Add(mm);
            }
            db.SubmitChanges();
        }
        return netflixMovies;
    }