Beispiel #1
0
 public Pokemon(PokemonDto pokemonDto)
 {
     Name        = pokemonDto.Name;
     Description = pokemonDto
                   .TextEntries?
                   .FirstOrDefault(t => t.Language.Name == _language)?.Text ?? string.Empty;
 }
        public IActionResult Update([FromBody] PokemonDto pokemon)
        {
            string token  = Request.Headers["Authorization"];
            var    idUser = _authRepository.GetUserIdFromToken(token);

            return(ExecFunc(() => _pokemonApplication.Update(pokemon, idUser)));
        }
        public async Task <IActionResult> Create(PokemonDto model)
        {
            var det = new Pokemon();

            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Foto != null)
                {
                    string folderPath = Path.Combine(HostingEnvironment.WebRootPath, "img");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Foto.FileName;
                    string filePath = Path.Combine(folderPath, uniqueFileName);

                    if (filePath != null)
                    {
                        model.Foto.CopyTo(new FileStream(filePath, mode: FileMode.Create));
                    }
                }
                Pokemon detalle = new Pokemon {
                    NombrePokemon = model.NombrePokemon,
                    TipoPokemon   = model.TipoPokemon,
                    Foto          = uniqueFileName,
                    Ataque        = model.Ataque,
                    RegionPokemon = model.RegionPokemon
                };
                _context.Add(detalle);
                await _context.SaveChangesAsync();

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

            return(View(model));
        }
 public static Pokemons ToModel(this PokemonDto pokemonDto)
 {
     return(new Pokemons()
     {
         Id = pokemonDto.Id,
         Id_Pokemon_Species = pokemonDto.PokemonSpecies.Id,
         Id_User = pokemonDto.User?.Id,
         Id_Nature = pokemonDto.Nature.Id,
         Id_Move_1 = pokemonDto.Move1?.Id,
         Id_Move_2 = pokemonDto.Move2?.Id,
         Id_Move_3 = pokemonDto.Move3?.Id,
         Id_Move_4 = pokemonDto.Move4?.Id,
         Nickname = pokemonDto.Nickname,
         Level = pokemonDto.Level,
         Hp = pokemonDto.Hp,
         Attack = pokemonDto.Attack,
         Defense = pokemonDto.Defense,
         Sp_Attack = pokemonDto.SpAttack,
         Sp_Defense = pokemonDto.SpDefense,
         Speed = pokemonDto.Speed,
         Iv_Hp = pokemonDto.IvHp,
         Iv_Attack = pokemonDto.IvAttack,
         Iv_Defense = pokemonDto.IvDefense,
         Iv_Sp_Attack = pokemonDto.IvSpAttack,
         Iv_Sp_Defense = pokemonDto.IvSpDefense,
         Iv_Speed = pokemonDto.IvSpeed,
         Ev_Hp = pokemonDto.EvHp,
         Ev_Attack = pokemonDto.EvAttack,
         Ev_Defense = pokemonDto.EvDefense,
         Ev_Sp_Attack = pokemonDto.EvSpAttack,
         Ev_Sp_Defense = pokemonDto.EvSpDefense,
         Ev_Speed = pokemonDto.EvSpeed
     });
 }
        public bool Save(PokemonDto pokemonDto)
        {
            pokemonDto.Validate();
            var pokemonModel = pokemonDto.ToModel();

            _pokemonRepository.Save(pokemonModel);
            return(true);
        }
Beispiel #6
0
 private PokemonDto TranslateText(PokemonDto pokemonDto)
 {
     pokemonDto.Description =
         pokemonDto.Habitat.ToLowerInvariant() == "cave" || pokemonDto.IsLegendary
         ? _textTranslator.TranslateText(pokemonDto.Description, TranslationKind.Yoda).Result
         : _textTranslator.TranslateText(pokemonDto.Description, TranslationKind.Shakespeare).Result;
     return(pokemonDto);
 }
 public bool Update(PokemonDto pokemon, int idUserLogged)
 {
     if (pokemon.User == null || pokemon.User.Id != idUserLogged)
     {
         throw new DomainException("This pokemon belongs to someone else!");
     }
     _pokemonRepository.Update(pokemon.ToModel());
     return(true);
 }
        public void returns_correct_name_and_empty_description_when_entries_provided_in_dto()
        {
            var dto = new PokemonDto
            {
                Name = _knownName
            };

            var pokemon = new Pokemon(dto);

            Assert.AreEqual(_knownName, pokemon.Name);
            Assert.AreEqual(string.Empty, pokemon.Description);
        }
Beispiel #9
0
        public static string ToStatsCaption(this PokemonDto pokemonDto)
        {
            var sb = new StringBuilder();

            sb.AppendLine($"HP 💗 {pokemonDto.Stats.Health}");
            sb.AppendLine($"Attack 💥 {pokemonDto.Stats.Attack}");
            sb.AppendLine($"Defense 🛡 {pokemonDto.Stats.Defense}");
            sb.AppendLine($"Special Attack 🌟 {pokemonDto.Stats.SpecialAttack}");
            sb.AppendLine($"Special Defense 🔰 {pokemonDto.Stats.SpecialDefense}");
            sb.AppendLine($"Speed 👟 {pokemonDto.Stats.Speed}");

            return(sb.ToString());
        }
Beispiel #10
0
 public static InlineQueryResultPhoto ToInlineQueryResultPhoto(this PokemonDto pokemonDto)
 {
     return(new InlineQueryResultPhoto(
                $"pokemon:{pokemonDto.Name.ToLower()}",
                pokemonDto.Image,
                pokemonDto.Sprite ?? pokemonDto.Image)
     {
         Caption = pokemonDto.Description,
         Title = pokemonDto.Name,
         Description = pokemonDto.Description,
         ReplyMarkup = pokemonDto.ToDescriptionKeyboard()
     });
 }
Beispiel #11
0
        public async Task <ActionResult <PokemonDto> > Get([FromRoute] string name)
        {
            Pokemon pokemon = await _pokemonService.GetPokemon(name);

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

            PokemonDto pokemonDto = _pokemonMapper.Map(pokemon);

            return(Ok(pokemonDto));
        }
 public IActionResult Create([FromBody] PokemonDto pokemon)
 {
     return(ExecFunc(() => {
         string token = Request.Headers["Authorization"];
         if (token == null)
         {
             return _pokemonApplication.SaveInCache(pokemon);
         }
         pokemon.User = new User()
         {
             Id = _authRepository.GetUserIdFromToken(token)
         };
         return _pokemonApplication.Save(pokemon);
     }));
 }
        public bool SaveInCache(PokemonDto pokemon)
        {
            AjustMovesNames(pokemon);
            List <PokemonDto> listPokemonDto;

            _cacheDomain.Cache.TryGetValue("Pokemons", out listPokemonDto);
            if (listPokemonDto == null)
            {
                listPokemonDto = new List <PokemonDto>();
            }
            pokemon.Id = listPokemonDto.Count + 1;
            listPokemonDto.Add(pokemon);
            _cacheDomain.Set("Pokemons", listPokemonDto);
            return(true);
        }
Beispiel #14
0
        public async Task <Result <Pokemon> > GetPokemon(string name)
        {
            var response = await _httpClient.GetAsync(_pokemonPath + name);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                PokemonDto pokemonDto = JsonConvert.DeserializeObject <PokemonDto>(result);
                return(new Pokemon(pokemonDto));
            }

            _logger.LogWarning("The pokemon named '{name}' could not be retrieved; reason: {reason}", name, response.ReasonPhrase);
            return(new ErrorResultContent(response.StatusCode, response.ReasonPhrase));
        }
        public void returns_correct_name_and_empty_description_when_language_not_provided_in_dto()
        {
            var dto = new PokemonDto
            {
                Name        = _knownName,
                TextEntries = new List <TextEntryDto> {
                    _foreignLanguageEntry
                }
            };

            var pokemon = new Pokemon(dto);

            Assert.AreEqual(_knownName, pokemon.Name);
            Assert.AreEqual(string.Empty, pokemon.Description);
        }
Beispiel #16
0
 public static IPokemon ToDomainObject(this PokemonDto dto)
 {
     return(new Models.Pokemon
     {
         ID = dto.ID,
         Name = dto.Name,
         HPCurrent = dto.HPCurrent,
         HPMax = dto.HPMax,
         Level = dto.Level,
         Stats = dto.Stats.ToDomainObject(),
         Attacks = dto.Attacks.Select(x => x.ToDomainObject()).ToList(),
         Condition = (Condition)dto.Condition,
         PrimaryTypeID = dto.PrimaryTypeID,
         SecondaryTypeID = dto.SecondaryTypeID
     });
 }
Beispiel #17
0
        public async Task GetSpecies()
        {
            string name    = "foo pokemon";
            string species = "foo species";
            var    pokemon = new PokemonDto(name, species);

            var client = new Mock <IPokemonClient>();

            client.Setup(x => x.GetPokemonAsync(name)).ReturnsAsync(pokemon);

            var service = new PokemonService(client.Object);

            string result = await service.PokemonSpeciesAsync(name);

            Assert.AreEqual(species, result);
        }
Beispiel #18
0
        public Task <PokemonDto> GetPokemonAsync(string name)
        {
            var pokemonDto = new PokemonDto
            {
                FlavorTextEntries = new List <FlavorTextDto>()
                {
                    new FlavorTextDto
                    {
                        Language = new LanguageDto {
                            Name = "en"
                        },
                        Text = "By so delight of showing neither believe he present.Deal sigh up in shew away when.Pursuit express no or prepare replied.Wholly formed old latter future but way she."
                    }
                }
            };

            return(Task.Run(() => pokemonDto));
        }
Beispiel #19
0
        public GenericApiResponse <PokemonDto> GetPokemon(string name)
        {
            var pokemon    = _pokemonRepository.GetByName(name);
            var pokemonDto = new PokemonDto();

            _mapper.Map(pokemon, pokemonDto);
            var genericApiResponse = new GenericApiResponse <PokemonDto> {
                Data = pokemonDto
            };

            if (pokemon != null)
            {
                return(genericApiResponse);
            }

            genericApiResponse.Success      = false;
            genericApiResponse.ErrorMessage = ApiErrors.NotFound.GetDescription();
            throw new ApiException(ApiErrors.NotFound);
        }
 private void AjustMovesNames(PokemonDto pokemonDto)
 {
     if (pokemonDto.Move1 != null)
     {
         pokemonDto.Move1.Name = pokemonDto.Move1.Name.Split('-')[0];
     }
     if (pokemonDto.Move2 != null)
     {
         pokemonDto.Move2.Name = pokemonDto.Move2?.Name.Split('-')[0];
     }
     if (pokemonDto.Move3 != null)
     {
         pokemonDto.Move3.Name = pokemonDto.Move3?.Name.Split('-')[0];
     }
     if (pokemonDto.Move4 != null)
     {
         pokemonDto.Move4.Name = pokemonDto.Move4?.Name.Split('-')[0];
     }
 }
        public void returns_correct_name_and_description_when_provided_in_dto()
        {
            var dto = new PokemonDto
            {
                Name        = _knownName,
                TextEntries = new List <TextEntryDto> {
                    _foreignLanguageEntry,
                    new TextEntryDto {
                        Language = new LanguageDto {
                            Name = "en"
                        }, Text = _knownDescription
                    }
                }
            };

            var pokemon = new Pokemon(dto);

            Assert.AreEqual(_knownName, pokemon.Name);
            Assert.AreEqual(_knownDescription, pokemon.Description);
        }
Beispiel #22
0
 public IActionResult CreatePokemon([FromBody] PokemonDto pokemon)
 {
     try
     {
         _services.InsertPokemon(_mapper.Map <Pokemon>(pokemon));
         return(Created("", pokemon));
     }
     catch (BadRequestException ex)
     {
         return(BadRequest(ex.Message));
     }
     catch (AlreadyExistException ex)
     {
         return(BadRequest(ex.Message));
     }
     catch (BusinessException ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
Beispiel #23
0
        public async Task Get_ServiceAndMapperReturnNonNull_ReturnsMappedDto()
        {
            Pokemon    pokemon    = GetNewPokemon();
            PokemonDto pokemonDto = new PokemonDto()
            {
                Name        = "name",
                Description = "description",
                Habitat     = "habitat",
                IsLegendary = true
            };

            _mockPokemonService.Setup(ps => ps.GetPokemon(It.IsAny <string>())).ReturnsAsync(pokemon);
            _mockPokemonMapper.Setup(pm => pm.Map(pokemon)).Returns(pokemonDto);

            var getResult = await _controller.Get("name");

            var okObjectResult = (OkObjectResult)getResult.Result;

            Assert.AreEqual(pokemonDto, okObjectResult.Value);
        }
Beispiel #24
0
 public IActionResult EditPokemon([FromBody] PokemonDto pokemon, string name)
 {
     try
     {
         _services.EditPokemon(_mapper.Map <Pokemon>(pokemon), name);
         return(Ok(pokemon));
     }
     catch (BadRequestException ex)
     {
         return(BadRequest(ex.Message));
     }
     catch (NotFoundException ex)
     {
         return(NotFound(ex.Message));
     }
     catch (BusinessException ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
Beispiel #25
0
        public static InlineKeyboardMarkup ToStatsKeyboard(this PokemonDto pokemonDto)
        {
            var pokemonBeforeCallback = new Dictionary <string, string>
            {
                { "action", "pokemon_previous" },
                { "requested_pokemon", pokemonDto.Before.Item1.ToString() }
            };

            var pokemonNextCallback = new Dictionary <string, string>
            {
                { "action", "pokemon_next" },
                { "requested_pokemon", pokemonDto.Next.Item1.ToString() }
            };

            var pokemonDescriptionCallback = new Dictionary <string, string>
            {
                { "action", "pokemon_description" },
                { "requested_pokemon", pokemonDto.Id.ToString() }
            };

            var pokemonNext = pokemonDto.Next.Item2;

            if (pokemonNext.Length > 8)
            {
                pokemonNext = $"{new string(pokemonDto.Next.Item2.Take(5).ToArray())}...";
            }

            return(new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithCallbackData($"Show description", JsonConvert.SerializeObject(pokemonDescriptionCallback))
                },
                new[]
                {
                    InlineKeyboardButton.WithCallbackData($"⬅ {pokemonDto.Before.Item2}", JsonConvert.SerializeObject(pokemonBeforeCallback)),
                    InlineKeyboardButton.WithCallbackData($"{pokemonDto.Name}", "no_callback"),
                    InlineKeyboardButton.WithCallbackData($"{pokemonNext} âž¡", JsonConvert.SerializeObject(pokemonNextCallback))
                }
            }));
        }
Beispiel #26
0
        public static IPokemonService GetMocked200PokemonService()
        {
            var pokemonDto = new PokemonDto
            {
                FlavorTextEntries = new List <FlavorTextDto>()
                {
                    new FlavorTextDto
                    {
                        Language = new LanguageDto {
                            Name = "en"
                        },
                        Text = "By so delight of showing neither believe he present.Deal sigh up in shew away when.Pursuit express no or prepare replied.Wholly formed old latter future but way she."
                    }
                }
            };
            var httpClient = new HttpClient(new GenericServiceReturn200ResponseHandler <PokemonDto>(pokemonDto))
            {
                BaseAddress = new System.Uri("http://dummy.com/")
            };
            var logger = Mock.Of <ILogger <PokemonService> >();

            return(new PokemonService(httpClient, logger));
        }
Beispiel #27
0
        public async Task <PokemonDto> GetPokemonAsync(string name)
        {
            var pokemonWrapper = new PokemonDto();

            var request = new HttpRequestMessage(HttpMethod.Get, $"pokemon-species/{name}/");

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
            {
                if (response.IsSuccessStatusCode)
                {
                    pokemonWrapper = await response.Content.ReadAsAsync <PokemonDto>();
                }
                else
                {
                    _logger.LogWarning($"Pokeapi returns not successful status code: {response.StatusCode}");
                    throw new ApiCallFailedException(response.StatusCode);
                }
            }

            return(pokemonWrapper);
        }
Beispiel #28
0
        private PokemonDto DeserializeContent(string content)
        {
            var data = (JObject)JsonConvert.DeserializeObject(content);

            JArray flavorTextEntriesArray = JArray.Parse(data["flavor_text_entries"].ToString());
            var    flavorTextEntries      = new List <FlavorText>();

            try {
                flavorTextEntries = flavorTextEntriesArray.Select(f => new FlavorText {
                    Flavor_Text = f["flavor_text"].ToString(),
                    Language    = new Language {
                        Name = f["language"]["name"].ToString()
                    }
                }).ToList();
            } catch {
                WriteLine("Desciption not found");
            }

            var pokemonDescription = String.Empty;

            if (flavorTextEntries.Any())
            {
                var enFlavorTextEntries = flavorTextEntries.Where(f => f.Language.Name == "en").FirstOrDefault();
                pokemonDescription = enFlavorTextEntries != null ? enFlavorTextEntries.Flavor_Text : String.Empty;
            }

            JToken nameJToken, isLegendaryJToken;
            var    pokemonDto = new PokemonDto()
            {
                Name        = data.TryGetValue("name", out nameJToken) ? (string)nameJToken : string.Empty,
                IsLegendary = data.TryGetValue("is_legendary", out isLegendaryJToken) ? (bool)isLegendaryJToken : false,
                Habitat     = data.SelectToken("habitat.name") != null ? data["habitat"]["name"].ToString() : string.Empty,
                Description = RemoveTextFormating(pokemonDescription)
            };

            return(pokemonDto);
        }
Beispiel #29
0
        public static PokemonDto toDto(this Pokemon entity)
        {
            var dto = new PokemonDto
            {
                PokemonID      = entity.PokemonID,
                PokemonName    = entity.PokemonName,
                PokemonSpecies = new SpeciesDto
                {
                    SpeciesID   = entity.Species.SpeciesID,
                    SpeciesName = entity.Species.SpeciesName,
                    Description = entity.Species.SpeciesDescription,
                    PrimaryType = new TypeDto
                    {
                        TypeName = entity.Species.PrimaryType.TypeName
                    },
                    SecondaryType = entity.Species.SecondaryType != null ? new TypeDto
                    {
                        TypeName = entity.Species.SecondaryType.TypeName
                    } : null
                }
            };

            return(dto);
        }
        public async Task <IActionResult> Post([FromBody] PokemonDto value)
        {
            await _pokemonService.CreatePokemon(value);

            return(Created("", value));
        }