public static MovieEntity ToBllEntity(this MovieViewModel model)
        {
            var result = new MovieEntity()
            {
                Id          = model.Id,
                Title       = model.Title,
                Description = model.Description,
                Year        = model.Year,
                Length      = model.Length,
                Mark        = model.Mark,
                Producer    = model.Producer,
                Budget      = model.Budget
            };

            if (model.Picture != null)
            {
                byte[] input = null;
                var    br    = new BinaryReader(model.Picture.InputStream);
                input          = br.ReadBytes((int)model.Picture.ContentLength);
                result.Picture = new byte[input.Length];
                input.CopyTo(result.Picture, 0);
            }
            else
            {
                result.Picture = null;
            }
            return(result);
        }
示例#2
0
        public async Task <IActionResult> Update(int id, [FromBody] MovieEntity movieEntity)
        {
            try
            {
                if (movieEntity == null)
                {
                    return(BadRequest());
                }

                MovieEntity movieEntityToUpdate = await _MoviesRepository.GetSingle(id);

                if (movieEntityToUpdate == null)
                {
                    return(NotFound());
                }

                movieEntityToUpdate.Title    = movieEntity.Title;
                movieEntityToUpdate.Director = movieEntity.Director;

                await _MoviesRepository.Update(movieEntityToUpdate);

                return(Ok(movieEntityToUpdate));
            }
            catch (Exception exception)
            {
                Console.Write(exception.ToString());
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
        public async Task <IActionResult> AddMovie(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "movies")] HttpRequest req,
            ILogger log)
        {
            try
            {
                string apiKey          = req.Headers["x-api-key"];
                string encryptedApiKey = StaticMethods.Hash(apiKey);
                if (encryptedApiKey == await _apiKeyRepository.Get())
                {
                    string      requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                    Movie       movie       = JsonConvert.DeserializeObject <Movie>(requestBody);
                    MovieEntity movieEntity = new MovieEntity(movie);
                    await _repository.Add(movieEntity);

                    return(new OkObjectResult(movieEntity));
                }
                else
                {
                    var result = new ObjectResult("Api Key Invalid");
                    result.StatusCode = StatusCodes.Status401Unauthorized;
                    return(result);
                }
            }
            catch (Exception exception)
            {
                log.LogError(exception.ToString());
                var result = new ObjectResult(exception.Message);
                result.StatusCode = StatusCodes.Status500InternalServerError;
                return(result);
            }
        }
示例#4
0
        public async Task Delete(int id)
        {
            MovieEntity model = await GetSingle(id);

            _context.Movies.Remove(model);
            await _context.SaveChangesAsync();
        }
示例#5
0
        public async Task <MovieModel> AddMovieAsync(MovieEntity entity)
        {
            this.appDbContext.Movies.Add(entity);
            await this.appDbContext.SaveChangesAsync();

            return(entity.AsModel());
        }
        public void Insert_adds_entity()
        {
            // Arrange
            var builder = new DbContextOptionsBuilder <Database>();

            builder.UseInMemoryDatabase(databaseName: "Insert_adds_entity");

            var context = new Database(builder.Options);

            InitDbContext(context);

            var repo   = new MovieRepository(context);
            var entity = new MovieEntity
            {
                Id          = 4,
                Title       = "A View to Kill",
                ReleaseYear = 1979,
                Summary     = "Roger Moore's last movie"
            };

            // Act
            repo.Insert(entity);

            // Assert
            Assert.Equal(expected: 4, actual: context.Movies.Count());
        }
示例#7
0
        public MovieEntity GetMovieEntity()
        {
            // TODO: Add error/edge-case handling as appropriate
            MovieEntity movie = new MovieEntity();

            movie.MovieId    = this.MovieId;
            movie.Name       = this.Name;
            movie.AltNames   = this.AltNames;
            movie.Posters    = this.Posters;
            movie.Rating     = this.Ratings;
            movie.Synopsis   = this.Synopsis;
            movie.Cast       = this.Casts ?? string.Empty;
            movie.Stats      = this.Stats ?? string.Empty;
            movie.Songs      = this.Songs;
            movie.Trailers   = this.Trailers;
            movie.Pictures   = this.Pictures;
            movie.Genre      = this.Genre;
            movie.Month      = this.Month;
            movie.Year       = this.Year;
            movie.UniqueName = this.UniqueName;
            movie.State      = this.State;
            movie.MyScore    = this.MyScore;
            movie.JsonString = this.JsonString;
            movie.Popularity = this.Popularity;
            return(movie);
        }
示例#8
0
        public ActionResult AddMovie(MoviePostData data)
        {
            if (data == null || string.IsNullOrEmpty(data.Name) || string.IsNullOrEmpty(data.UniqueName))
            {
                return(null);
            }

            try
            {
                var         tableMgr = new TableManager();
                MovieEntity movie    = data.GetMovieEntity();
                movie.RowKey = movie.MovieId;
                tableMgr.UpdateMovieById(movie);

                UpdateCache(movie);

                UpdateLuceneIndex(movie);
            }
            catch (Exception)
            {
                return(null);
            }

            return(null);
        }
示例#9
0
        public void Edit(MovieEntity movieEntity) //filmleri düzenleyen metot
        {
            var entity = _movieContext.Movies.FirstOrDefault(x => x.Id == movieEntity.Id);

            _movieContext.Movies.Remove(entity);
            _movieContext.Movies.Add(movieEntity);
        }
示例#10
0
        public override void Init()
        {
            base.Init();

            string key = string.Format(Constant.MovieDetailApi, this._id);

            this.Entity = this.ServiceManager.Cache.GetOrAdd(key, () =>
            {
                string error;
                Stream response = Utils.ExecuteWebRequest(key, 4, out error);

                if (string.IsNullOrEmpty(error))
                {
                    var result = JObject.Load(new JsonTextReader(new StreamReader(response, Encoding.UTF8)));
                    return(MovieEntity.Parse(result));
                }
                else
                {
                    throw new DoubanApiException(error);
                }
            }, TimeSpan.FromMinutes(30));

            this.Comments =
                this.ServiceManager.MovieCommentService.GetAll()
                .Where(item => item.MovieId.Equals(this._id, StringComparison.OrdinalIgnoreCase))
                .ToList();

            this.Comments.Sort((left, right) =>
            {
                return(left.CreatedTime.CompareTo(right.CreatedTime));
            });
        }
示例#11
0
        // Parent Node/Body
        public MovieEntity GetMovieDetails(HtmlNode body)
        {
            MovieEntity movie = new MovieEntity();

            movie.RowKey     = movie.MovieId = Guid.NewGuid().ToString();
            movie.Name       = GetMovieName(body);
            movie.AltNames   = GetMovieByAltName(body);
            movie.UniqueName = GetMovieUniqueName(movie.Name);
            movie.Rating     = GetMovieRating(body);
            movie.Synopsis   = GetMovieStory(body);
            movie.Genre      = GetMovieGenre(body);
            movie.Month      = GetMovieMonth(body);
            movie.Year       = GetMovieYear(body);
            movie.Stats      = GetMovieStats(body);

            movie.TwitterHandle = string.Empty;
            movie.Trailers      = string.Empty;
            movie.Pictures      = string.Empty;
            movie.State         = string.Empty;
            movie.MyScore       = Util.DEFAULT_SCORE;
            movie.JsonString    = "[]";

            movie.Name       = movie.Name.Replace(":", string.Empty);
            movie.AltNames   = movie.AltNames.Replace(":", string.Empty);
            movie.UniqueName = movie.UniqueName.Replace(":", string.Empty);

            return(movie);
        }
示例#12
0
        internal static string SetReviewAndUpdateMovieRating(string movieId, string reviewId, int rating, string bag)
        {
            var         tableMgr = new TableManager();
            MovieEntity movie    = tableMgr.GetMovieById(movieId);

            if (movie != null)
            {
                ReviewEntity review = tableMgr.GetReviewById(reviewId);

                if (review != null)
                {
                    // -1 => Negative
                    //  0 => No rating
                    // +1 => Positive
                    rating = (rating < 0) ? -1 : 1;

                    review.SystemRating = rating;
                    tableMgr.UpdateReviewById(review);

                    string myscore = movie.MyScore;
                    if (string.IsNullOrEmpty(myscore) || myscore == "0")
                    {
                        myscore = "{\"teekharating\":\"0\",\"feekharating\":\"0\",\"criticrating\":\"\"}";
                    }

                    RatingConvertion newRating = new RatingConvertion();
                    RatingConvertion oldRating;
                    try
                    {
                        oldRating = jsonSerializer.Value.Deserialize(myscore, typeof(RatingConvertion)) as RatingConvertion;
                    }
                    catch
                    {
                        myscore   = "{\"teekharating\":\"0\",\"feekharating\":\"0\",\"criticrating\":\"\"}";
                        oldRating = jsonSerializer.Value.Deserialize(myscore, typeof(RatingConvertion)) as RatingConvertion;
                    }

                    var teekha = oldRating.teekharating + (rating > 0 ? 1 : 0);
                    var feekha = oldRating.feekharating + (rating < 0 ? 1 : 0);
                    newRating.teekharating = teekha;
                    newRating.feekharating = feekha;
                    newRating.criticrating = ((int)(teekha / (double)(teekha + feekha) * 100)).ToString();

                    string strNewRating = jsonSerializer.Value.Serialize(newRating);
                    movie.Rating  = newRating.criticrating;
                    movie.MyScore = strNewRating;
                    tableMgr.UpdateMovieById(movie);

                    return(jsonSerializer.Value.Serialize(new { Status = "Ok", UserMessage = "Successfully update movie rating" }));
                }
                else
                {
                    return(jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Unable to find review with passed review id. Please check review id." }));
                }
            }
            else
            {
                return(jsonSerializer.Value.Serialize(new { Status = "Error", UserMessage = "Unable to find movie with passed movie id. Please check movie id." }));
            }
        }
        /// <inheritdoc />
        private protected override CommandResult Execute(AddOrUpdateMovieCommandModel model)
        {
            if (Movie == null)
            {
                Movie = new MovieEntity();
            }

            Movie.Title = model.Title;
            Movie.Type  = model.Type;
            Movie.Year  = model.Year;

            Context.SaveChanges();

            var removedFiles = Context.MovieFileEntities.Where(mf => mf.MovieId == Movie.Id && !model.FileIds.Contains(mf.Id));

            foreach (var removedFile in removedFiles)
            {
                removedFile.MovieId = null;
            }

            var newFiles = Context.MovieFileEntities.Where(mf => mf.MovieId != Movie.Id && model.FileIds.Contains(mf.Id));

            foreach (var newFile in newFiles)
            {
                newFile.MovieId = Movie.Id;
            }

            Context.SaveChanges();

            return(new CommandResult());
        }
示例#14
0
 // Movie 实体
 private movie MovieMapperInitializer(MovieEntity movieEntity)
 {
     Mapper.Initialize(x => x.CreateMap <MovieEntity, movie>()
                       .ForMember(dest => dest.movieDirectors, opt => opt.Ignore())
                       .ForMember(dest => dest.movieGenres, opt => opt.Ignore()));
     return(Mapper.Map <MovieEntity, movie>(movieEntity));
 }
示例#15
0
        public async Task <MovieEntity> Add(MovieEntity newMovie)
        {
            _context.Movies.Add(newMovie);
            await _context.SaveChangesAsync();

            return(newMovie);
        }
示例#16
0
        public IActionResult Edit(MovieViewModel model)
        {
            var movieEntity = new MovieEntity
            {
                Id          = model.Id,
                Name        = model.Name,
                Director    = model.Director,
                Cast        = model.Cast,
                ReleaseYear = model.ReleaseYear,
                Writer      = model.Writer,
                Category    = model.Category,
                ImdbUrl     = model.ImdbUrl,
                Score       = model.Score,
                Review      = model.Review
            };

            _movieService.Edit(movieEntity);
            var updatedEntity = _movieService.Get(model.Id);

            return(View(new MovieViewModel
            {
                Id = updatedEntity.Id,
                Name = updatedEntity.Name,
                Director = updatedEntity.Director,
                Cast = updatedEntity.Cast,
                ReleaseYear = updatedEntity.ReleaseYear,
                Writer = updatedEntity.Writer,
                Category = updatedEntity.Category,
                ImdbUrl = updatedEntity.ImdbUrl,
                Score = updatedEntity.Score,
                Review = updatedEntity.Review
            }));
        }
示例#17
0
        public async Task UpsertRatingAsync(Guid userId, Guid movieId, decimal rating, CancellationToken cancellationToken = default)
        {
            using (MoviesDbContext context = _dbContextFactory())
            {
                UserEntity user = context.Users.SingleOrDefault(a => a.Id == userId);

                if (user == null)
                {
                    throw new UserNotFoundException($"User with ID {userId} not found");
                }

                MovieEntity movie = context.Movies.SingleOrDefault(a => a.Id == movieId);

                if (movie == null)
                {
                    throw new MovieNotFoundException($"Movie with ID {movieId} not found");
                }

                RatingEntity entity =
                    context.Ratings.SingleOrDefault(a => a.UserId == userId && a.MovieId == movieId) ??
                    new RatingEntity
                {
                    User  = user,
                    Movie = movie,
                };

                entity.Rating  = rating;
                entity.DateSet = DateTimeOffset.UtcNow;

                await context.SaveChangesAsync(cancellationToken);
            }
        }
        public void Update(MovieEntity movie)
        {
            var m = GetById(movie.Id);

            if (m != null)
                m.Likes = movie.Likes; //Only updates likes for the moment
        }
示例#19
0
 /// <summary>
 /// 通过 Infalte 数据获取 SVGA 的 MovieEntity.
 /// </summary>
 /// <param name="inflatedBytes"></param>
 private void GetMovieEntity()
 {
     if (this.InflatedBytes != null)
     {
         this.MovieEntity = MovieEntity.Parser.ParseFrom(this.InflatedBytes);
     }
 }
        public async Task Run([QueueTrigger("movies", Connection = "AzureWebJobsStorage")] string myQueueItem, ILogger log)
        {
            try
            {
                Movie movie = JsonConvert.DeserializeObject <Movie>(myQueueItem);

                MovieEntity movieEntity = new MovieEntity(movie);

                if (movieEntity.Title != "")
                {
                    //Download the image from the Url
                    var imageBytes = StaticMethods.GetImageFromUrl(movieEntity.ImageUrl);

                    //Add or update entity to the storage table movies
                    await _movieEntityCrudRepository.AddOrUpdate(movieEntity);

                    //Add image to the storage blob imagemovies
                    await _movieImageCrudRepository.Add(imageBytes, movieEntity.Id + "/" + DateTime.UtcNow.Ticks.ToString());
                }
                else
                {
                    //Delete the entity from the storage table movies
                    await _movieEntityCrudRepository.Delete(movieEntity.Id);

                    //Delete the image from the storage blob movieimages
                    await _movieImageCrudRepository.DeleteFolder(movieEntity.Id);
                }
            }
            catch (Exception exception)
            {
                log.LogError(exception.Message);
            }
        }
        public void AddNew_Movie_Persistent()
        {
            //Arrange
            var movie = new MovieEntity()
            {
                Id              = new Guid("82a58772-dd6a-4a66-b7cc-08e316232663"),
                OriginalTitle   = "Star Wars: Episode III - Revenge of the Sith",
                CzechTitle      = "Star Wars: Epizoda III - Pomsta Sithù",
                Genre           = GenreType.ScienceFiction,
                PosterImageUrl  = "https://img.csfd.cz/files/images/film/posters/000/005/5671_445cb1.jpg?h180",
                CountryOfOrigin = "USA",
                Length          = TimeSpan.FromMinutes(140),
                Description     = "V tøetí epizodì ságy Star Wars zuøí Klonové války, které prohloubily rozpory mezi kancléøem Palpatinem a Radou Jediù. Mladý rytíø Jedi Anakin Skywalker se musí rozhodnout, na èí stranì bude stát. Podlehne slibùm moci a pokušení Temné strany, vstoupí do služeb zlého Darth Sidiouse a stane se z nìj Darth Vader. Sithští lordové se chtìjí spoleènì pomstít a prvním krokem jejich plánu je likvidace Jediù. Pouze Yoda a Obi-Wan pøežijí a musejí se Sithùm postavit, což vede k dramatickému souboji svìtelnými meèi mezi Anakinem a Obi-Wanem, který rozhodne o osudu galaxie.",
            };

            //Act
            _testContext.MoviesDbContextSUT.Movies.Add(movie);
            _testContext.MoviesDbContextSUT.SaveChanges();

            //Assert
            using var dbx = _testContext.DbContextFactory.CreateDbContext();
            var movieFromDb = dbx.Movies.First(m => m.Id == movie.Id);

            Assert.Equal(movie, movieFromDb, MovieEntity.MovieComparer);
        }
示例#22
0
        public void Put(MovieEntity entity)
        {
            var realm = Realm.GetInstance();

            realm.Write(() => {
                realm.Add(entity);
            });
        }
示例#23
0
 public static MovieListModel MapMovieEntityToListModel(MovieEntity entity)
 {
     return(new MovieListModel
     {
         Id = entity.Id,
         Name = entity.OriginalTitle
     });
 }
示例#24
0
 public bool Put(string movie_name, [FromBody] MovieEntity movieEntity)
 {
     if (movie_name != null)
     {
         return(_movieServices.UpdateMovie(movie_name, movieEntity));
     }
     return(false);
 }
        public ActionResult DeleteConfirmed(Guid id)
        {
            MovieEntity movieEntity = db.Movies.Find(id);

            db.Movies.Remove(movieEntity);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 /*
  * public MovieEntity CreateMovie(MovieEntity movie)
  * {
  *  int newId;
  *  var lastMovie = movies.OrderByDescending(s => s.Id).FirstOrDefault();
  *  {
  *      newId = lastMovie.Id + 1;
  *  }
  *  movie.Id = newId;
  *  movies.Add(movie);
  *  return movie;
  * }*/
 public void CreateMovie(MovieEntity movie)
 {
     //_dbContext.Entry(movie.Production).State = EntityState.Unchanged;
     if (movie.Production != null)
     {
         _dbContext.Entry(movie.Production).State = EntityState.Unchanged;
     }
     _dbContext.Movies.Add(movie);
 }
示例#27
0
 public MovieDto MapToDto(MovieEntity MovieEntity)
 {
     return(new MovieDto()
     {
         Id = MovieEntity.Id,
         Title = MovieEntity.Title,
         Director = MovieEntity.Director
     });
 }
        /*
         * public bool DeleteMovie(int movieId)
         * {
         *  var movieToDelete = movies.FirstOrDefault(c => c.Id == movieId);
         *  movies.Remove(movieToDelete);
         *  return true;
         * }*/
        public bool DeleteMovie(int movieId)
        {
            var movieToDelete = new MovieEntity()
            {
                Id = movieId
            };

            _dbContext.Entry(movieToDelete).State = EntityState.Deleted;
            return(true);
        }
示例#29
0
        public async Task IfTheMovieToUpdate_DoesntExist_ReturnNull()
        {
            var movie = new MovieEntity {
                Id = 3, Name = "Jumanji"
            };

            var result = await _movieRepository.Update(movie);

            Assert.Null(result);
        }
示例#30
0
        public async Task <GetMovieResponseModel> GetMovieByIdAsync(Guid movieId, CancellationToken token)
        {
            Contract.Requires <Exception>(movieId != Guid.Empty, nameof(movieId));

            MovieEntity movieEntity = await _movieRepository.GetMovieByIdAsync(movieId, token);

            GetMovieResponseModel responseModel = await movieEntity.BuildAdapter().AdaptToTypeAsync <GetMovieResponseModel>();

            return(responseModel);
        }