Esempio n. 1
0
        private GameEntity InitGame(Game game)
        {
            var gameEntity = _mapper.Map <Game, GameEntity>(game);

            if (game.Genres != null)
            {
                IEnumerable <GenreEntity> sqlGenres    = _genreRepository.GetGenres(game.Genres);
                IEnumerable <Genre>       notSqlGenres = game.Genres.Except(_mapper.Map <IEnumerable <GenreEntity>, IEnumerable <Genre> >(sqlGenres), new IdDomainComparer <Genre>());
                foreach (var genre in notSqlGenres)
                {
                    _genreRepository.Add(genre);
                }

                _context.SaveChanges();

                gameEntity.Genres = _genreRepository.GetGenres(game.Genres).ToList();
            }
            if (game.PlatformTypes != null)
            {
                gameEntity.PlatformTypes = _platformRepository.GetPlatformTypes(game.PlatformTypes).ToList();
            }
            if (game.Publisher != null)
            {
                gameEntity.Publisher = _context.Publishers.FirstOrDefault(x => x.CompanyName == game.Publisher.CompanyName);

                if (gameEntity.Publisher == null)
                {
                    _publisherRepository.Add(game.Publisher);
                    _context.SaveChanges();
                    gameEntity.Publisher = _context.Publishers.FirstOrDefault(x => x.CompanyName == game.Publisher.CompanyName);
                }
            }

            return(gameEntity);
        }
Esempio n. 2
0
        private async Task <ICollection <MovieGenre> > AddGenres(Movie movie)
        {
            var genreIdList = movie.Genres.Select(genre => genre.GenreId).ToList();
            var genres      = new List <Genre>();

            foreach (var genreId in genreIdList)
            {
                var genre = await _genreRepository.Find(x => x.Name == genreId);

                if (genre == null)
                {
                    genre = new Genre()
                    {
                        Name = genreId,
                    };
                    await _genreRepository.Add(genre);
                }

                genres.Add(genre);
            }

            var movieGenres = new List <MovieGenre>();

            foreach (var genre in genres)
            {
                movieGenres.Add(new MovieGenre()
                {
                    Movie = movie,
                    Genre = genre
                });
            }

            return(movieGenres);
        }
        public async Task <ActionResult <GenreModel> > Post(GenreModel model)
        {
            try
            {
                var existing = _repository.CheckForExistingGenreName(model.Name);

                if (existing)
                {
                    return(BadRequest($"The genre, {model.Name}, already exists in database."));
                }

                var genre = _mapper.Map <Genre>(model);

                var genreId = _repository.GenerateGenreId();

                var location = _linkGenerator.GetPathByAction("Get", "Genres", new { genreId = genreId.Id });

                _repository.Add(genre);

                if (await _repository.SaveChangesAsync())
                {
                    return(Created(location, _mapper.Map <GenreModel>(genre)));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }

            return(BadRequest());
        }
Esempio n. 4
0
        public void AddGenre(GenreDto dto)
        {
            Genre entity = new Genre();

            entity.Name = dto.Name;
            _genreRepository.Add(entity);
            _genreRepository.Save();
        }
Esempio n. 5
0
 public void CreateGenre(GenreDTO genreDTO)
 {
     using (var transaction = GenreRepository.UnitOfWork.BeginTransaction(2))
     {
         GenreRepository.Add(GenreFactory.CreateGenre(genreDTO.Type));
         transaction.Commit();
     }
 }
Esempio n. 6
0
        protected override async Task Handle(CreateGenreCommand request, CancellationToken cancellationToken)
        {
            var genre = new Core.Models.Genre
            {
                Name = request.Name,
            };

            await _genreRepository.Add(genre, cancellationToken);
        }
Esempio n. 7
0
        public Genre Update(Genre genre)
        {
            IGenreRepository genreRepository = _repositoryFactory.GetDataRepository <IGenreRepository>();

            Genre updatedGenre = null;

            updatedGenre = genre.Id == 0 ? genreRepository.Add(genre) : genreRepository.Update(genre);

            return(updatedGenre);
        }
Esempio n. 8
0
        public async Task <GenreResponse> AddGenreAsync(AddGenreRequest request)
        {
            Genre genre = await _mapper.From(request).AdaptToTypeAsync <Genre>();

            Genre result = _genreRepository.Add(genre);

            int affected = await _genreRepository.UnitOfWork.SaveChangesAsync();

            return(_mapper.Map <GenreResponse>(result));
        }
Esempio n. 9
0
        public Task <int> Add(Genre entity)
        {
            /* Por enquanto não estamos fazendo nada além de retornar o id do genêro inserido no repositório.
             * Mas esse serviço é responsável por mapear a entidade se ela não estiver no formato esperado pelo repositório,
             * se vier no formato do CQRS por exemplo.
             * Aqui também é o local responsável por chamar outros repositórios caso seja necessário.
             */

            return(genreRepository.Add(entity));
        }
Esempio n. 10
0
        public async Task <GenreResponse> AddGenreAsync(AddGenreRequest request)
        {
            var item = new Genre {
                GenreDescription = request.GenreDescription
            };

            var result = _genreRepository.Add(item);
            await _genreRepository.UnitOfWork.SaveChangesAsync();

            return(_genreMapper.Map(result));
        }
Esempio n. 11
0
        public async Task <IActionResult> CreateGenre([FromBody] GenreResource resource)
        {
            var genre = _mapper.Map <GenreResource, Genre>(resource);

            _repository.Add(genre);
            await _unitOfWork.CompleteAsync();

            var result = _mapper.Map <Genre, GenreResource>(genre);

            return(Ok(result));
        }
Esempio n. 12
0
 public void Add(Genre genre)
 {
     try
     {
         _genreRepository.Add(genre);
         _logger.LogInformation(LoggerMessageDisplay.GenreCreated);
     }
     catch (Exception ex)
     {
         _logger.LogInformation(LoggerMessageDisplay.GenreCreatedNotFound, ex);
     }
 }
        public async Task <ServiceResult> Add(GenreModel model)
        {
            var serviceResult = new ServiceResult();
            var result        = await _genreRepository.Add(model);

            serviceResult.Success = result.Success;
            if (!result.Success)
            {
                serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                serviceResult.Error.Description = result.Message;
            }
            return(serviceResult);
        }
Esempio n. 14
0
        public async Task <GenreResponse> Handle(AddGenreCommand command, CancellationToken cancellationToken)
        {
            var item = new Entities.Genre {
                GenreDescription = command.GenreDescription
            };

            var result = _genreRepository.Add(item);
            await _genreRepository.UnitOfWork.SaveChangesAsync(cancellationToken);

            return(new GenreResponse {
                GenreId = result.GenreId, GenreDescription = result.GenreDescription
            });
        }
Esempio n. 15
0
        public ActionResult Create([FromForm] Genre genre)
        {
            try
            {
                _repository.Add(genre);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(new BadRequestResult());
            }
        }
Esempio n. 16
0
 public IActionResult Create(Genre genre)
 {
     if (ModelState.IsValid)
     {
         _genreRepository.Add(genre);
         _logger.LogInformation(LoggerMessageDisplay.GenreCreated);
         return(RedirectToAction(nameof(Index)));
     }
     else
     {
         _logger.LogWarning(LoggerMessageDisplay.GenreNotCreatedModelStateInvalid);
     }
     return(View());
 }
 public ActionResult <Genre> PostGenre(GenreDTO genreDTO)
 {
     try {
         Genre genreToCreate = new Genre()
         {
             Name = genreDTO.Name
         };
         _genreRepository.Add(genreToCreate);
         _genreRepository.SaveChanges();
         return(CreatedAtAction(nameof(GetGenre), new { id = genreToCreate.GenreId }, genreToCreate));
     }
     catch (Exception ex) {
         return(BadRequest(ex.Message));
     }
 }
Esempio n. 18
0
        public object Add(Genre genre)
        {
            try {
                genre.CreationDate = DateTime.Now;

                _repo.Add(genre);

                var controllerAction = new ControllerActionDescriptor();

                string actionName = controllerAction.ActionName;

                return(CreatedAtAction(actionName, genre));
            } catch (Exception error) {
                throw error;
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Handling save request and response
        /// </summary>
        /// <param name="request">Messaging.Genres.SaveGenreRequest</param>
        /// <returns>Messaging.Genres.SaveGenreResponse</returns>
        SaveGenreResponse IGenreService.SaveGenre(SaveGenreRequest request)
        {
            var response = new SaveGenreResponse()
            {
                Request       = request,
                ResponseToken = Guid.NewGuid()
            };

            try
            {
                if (request.Genre?.Id == 0)
                {
                    if (ServerValidation(request)) //server-side validation
                    {
                        response.Genre    = request.Genre;
                        response.Genre.Id = _repository.Add(request.Genre.MapToModel());
                        response.Success  = true;
                    }
                    else
                    {
                        response.Success = false;
                    }
                }
                else if (request.Genre?.Id > 0)
                {
                    if (ServerValidation(request)) //server-side validation
                    {
                        response.Genre   = _repository.Save(request.Genre.MapToModel()).MapToView();
                        response.Success = true;
                    }
                    else
                    {
                        response.Success = false;
                    }
                }
                else
                {
                    response.Success = false;
                }
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.Success = false;
            }
            return(response);
        }
Esempio n. 20
0
        public async Task <IActionResult> CreateGenre([FromBody] GenreResource genreResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var genre = mapper.Map <GenreResource, Genre>(genreResource);

            repository.Add(genre);
            await unitOfWork.CompleteAsync();

            genre = await repository.GetGenre(genre.Id);

            var result = mapper.Map <Genre, GenreResource>(genre);

            return(Ok(result));
        }
        public async Task <ActionResult <GenreDTO> > PostGenre(GenreDTO genreDTO)
        {
            try
            {
                var mappedEntity = _mapper.Map <Genre>(genreDTO);
                _genreRepository.Add(mappedEntity);

                if (await _genreRepository.Save())
                {
                    return(Created($"/api/v1.0/genres/{mappedEntity.GenreID}", _mapper.Map <GenreDTO>(mappedEntity)));
                }
            }
            catch (Exception e)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Database failure, cannot create item. {e.Message}"));
            }
            return(BadRequest());
        }
        public async Task <ActionResult> CreateGenre([FromBody] GenreDTO genreDTO)
        {
            try
            {
                var genre         = _mapper.Map <Genre>(genreDTO);
                var genreFromRepo = await _repository.Add(genre);

                if (genreFromRepo != null)
                {
                    return(CreatedAtAction(nameof(GetGenreById), new { id = genre.Id }, genre));
                }
                return(BadRequest("Failed to create genre."));
            }
            catch (Exception e)
            {
                var result = new { Status = StatusCodes.Status500InternalServerError, Data = $"Failed to create the genre. Exception thrown when attempting to add data to the database: {e.Message}" };
                return(this.StatusCode(StatusCodes.Status500InternalServerError, result));
            }
        }
        public ActionResult Add(GenreModel genre)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View("AddGenre", genre));
                }
                var model = new Genre();
                model.Genre_Id   = genre.Genre_Id;
                model.Name_Genre = genre.Name_Genre;
                genreRepository.Add(model);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 24
0
        public CreateGenreResponse CreateGenre(CreateGenreRequest request)
        {
            var response = new CreateGenreResponse();

            var genre = new Genre {
                Name = request.Name, Description = request.Description
            };

            ThrowExceptionIfGenreIsInvalid(genre);

            _genreRepository.Add(genre);

            _uow.Commit();

            MvcSiteMapProvider.SiteMaps.ReleaseSiteMap();

            response.Genre = genre.ConvertToGenreView();

            return(response);
        }
Esempio n. 25
0
        public IActionResult Save(EditorViewModel editorViewModel)
        {
            if (!ModelState.IsValid)
            {
                return View("editor", editorViewModel);
            }

            var genre = _mappingEngine.Map<Genre>(editorViewModel);

            if (string.IsNullOrWhiteSpace(genre.Id))
            {
                try
                {
                    var newId = _genreRepository.Add(genre);
                    return RedirectToAction("Detail", new { id = newId });
                }
                catch (Exception ex)
                {
                    // todo: log ex
                    ModelState.AddModelError("", "Unable to add genre. Please contact your system administrator.");
                    return View("editor", editorViewModel);
                }
            }
            else
            {
                try
                {
                    _genreRepository.Save(genre);
                    return RedirectToAction("Detail", new { id = genre.Id });
                }
                catch (Exception ex)
                {
                    // todo: log ex
                    ModelState.AddModelError("", "Unable to update genre. Please contact your system administrator.");
                    return View("editor", editorViewModel);
                }
            }
        }
Esempio n. 26
0
        public async Task <string> Create(GenreCreateModel genreCreateModel)
        {
            if (genreCreateModel == null || genreCreateModel.Name.IsNullOrEmpty())
            {
                throw new CustomException("Некоректные данные");
            }
            var genres = await _genreRepository.GetAll();

            if (genres == null)
            {
                throw new ServerException("Сервер вернул null");
            }
            if (genres.Any(w => string.Equals(w.Name, genreCreateModel.Name)))
            {
                throw new CustomException("Жанр с таким именем уже существует");
            }
            var result = await _genreRepository.Add(_mapper.Map <Genre>(genreCreateModel));

            if (result == null)
            {
                throw new ServerException("Ошибка сервера при добавлении");
            }
            return(result.Id);
        }
 public void Post([FromBody] Genre value)
 {
     _repository.Add(value);
 }
Esempio n. 28
0
        private void AddGenre(Comic comic, IGenreRepository genreRepository, string genreStr)
        {
            if (string.IsNullOrEmpty(genreStr)) return;

            string[] genres = genreStr.Split(',');

            foreach (string genre in genres)
            {
                string genreTrim = genre.Trim();

                Genre genreDb = genreRepository.Find(g => g.GenreName.Equals(genreTrim)).FirstOrDefault();

                if (genreDb == null)
                {
                    genreDb = new Genre
                    {
                        GenreName = genreTrim,
                        Comics = new List<Comic>()
                    };

                    genreDb.Comics.Add(comic);
                    genreRepository.Add(genreDb);
                }
                else
                {
                    if (genreDb.Comics == null) genreDb.Comics = new List<Comic>();
                    if (genreDb.Comics.Any(c => c.ComicUrl.Equals(comic.ComicUrl))) continue;

                    genreDb.Comics.Add(comic);
                    genreRepository.Edit(genreDb);
                }

                if (comic.Genres == null) comic.Genres = new List<Genre>();
                if (!comic.Genres.Any(g => g.GenreName.Equals(genreTrim)))
                {
                    comic.Genres.Add(genreDb);
                }

                genreRepository.Save();
            }
        }
Esempio n. 29
0
 public void Add(Genre genre)
 {
     _genreRepository.Add(genre);
 }
Esempio n. 30
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start!");

            var genre = new Genre("Dubstep");

            _genreRepository.Add(genre);
            Console.WriteLine("Genre created");

            var country = new Country("Germany");

            _countryRepository.Add(country);
            Console.WriteLine("Country created");

            var userData = new CommonUserData("Egop", "Bird", "Tit", DateTime.Today);

            _commonUserDataRepository.Add(userData);
            Console.WriteLine("CommonUserData created");

            var userLibrary = new UserLibrary(new List <Album>(), new List <Playlist>());

            _userLibraryRepository.Add(userLibrary);
            Console.WriteLine("UserLibrary created");

            var art = new Art("image.jpg");

            _artRepository.Add(art);
            Console.WriteLine("Art created");

            var playlist = new Playlist("test playlist", "test description", art, userLibrary,
                                        new List <TrackToPlaylist>());

            _playlistRepository.Add(playlist);
            Console.WriteLine("Playlist created");

            userLibrary.Playlists.Add(playlist);
            _userLibraryRepository.Update(userLibrary);

            Console.WriteLine("Playlist added to UserLibrary");

            var distributorData = new DistributorData("test distributor", country, new List <Album>(),
                                                      new List <ArtistToDistributor>());

            _distributorDataRepository.Add(distributorData);
            Console.WriteLine("DistributorData created");

            var album = new Album("test album", DateTime.Now, art, genre, distributorData, new List <Track>());

            _albumRepository.Add(album);
            Console.WriteLine("Album created");

            var track = new Track("Terror Drums", "test.mp3", 0, false, album, new List <TrackToPlaylist>());

            track.Playlists.Add(new TrackToPlaylist(track, playlist));
            _trackRepository.Add(track);
            Console.WriteLine("Track created");

            //foreach (var genre in _genreRepository.GetAll())
            //{
            //    Console.WriteLine(genre.Title);
            //}
            Console.ReadKey();
        }
Esempio n. 31
0
 public void AddGenre(Genre genre)
 {
     _genreRepository.Add(genre);
     _unitOfWork.Commit();
 }