public async Task ClearCacheWipesAllCachedData()
        {
            // assemble
            PokeApiClient sut   = CreateSut();
            Berry         berry = new Berry {
                Name = "test", Id = 1
            };

            mockHttp.Expect($"*berry/{berry.Id}*")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeNamedResourceList <Berry>()));
            mockHttp.Expect("*berry")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeNamedResourceList <Berry>()));
            mockHttp.Expect($"*berry/{berry.Id}*")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeNamedResourceList <Berry>()));
            mockHttp.Expect("*berry")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeNamedResourceList <Berry>()));

            // act
            await sut.GetResourceAsync <Berry>(berry.Id);

            await sut.GetNamedResourcePageAsync <Berry>();

            sut.ClearCache();
            await sut.GetResourceAsync <Berry>(berry.Id);

            await sut.GetNamedResourcePageAsync <Berry>();

            // assert
            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task UrlNavigationResolveAsyncSingle()
        {
            // assemble
            Pokemon responsePikachu = new Pokemon
            {
                Name    = "pikachu",
                Id      = 25,
                Species = new NamedApiResource <PokemonSpecies>
                {
                    Name = "pikachu",
                    Url  = "https://pokeapi.co/api/v2/pokemon-species/25/"
                }
            };
            PokemonSpecies responseSpecies = new PokemonSpecies {
                Name = "pikachu"
            };

            MockHttpMessageHandler mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect("*pokemon/pikachu/").Respond("application/json", JsonConvert.SerializeObject(responsePikachu));
            mockHttp.Expect("*pokemon-species/25/").Respond("application/json", JsonConvert.SerializeObject(responseSpecies));
            PokeApiClient client = new PokeApiClient(mockHttp);

            Pokemon pikachu = await client.GetResourceAsync <Pokemon>("pikachu");

            // act
            PokemonSpecies species = await client.GetResourceAsync(pikachu.Species);

            // assert
            mockHttp.VerifyNoOutstandingExpectation();
        }
示例#3
0
        static async Task Main()
        {
            PokeApiClient client = new PokeApiClient();

            try
            {
                // Pokemon result = await client.GetPokemonByName("BULBASAUR");
                Pokemon result = await client.GetPokemonById(1);

                Console.WriteLine($"Pokemon Id: {result.Id}" +
                                  $"\nName: {result.Name}" +
                                  $"\nWeight (in hectograms): {result.Weight}" +
                                  $"\nHeight (in inches): {result.Height}");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("I'm sorry, that Pokemon does not exist");
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Please try again later.");
            }


            Console.ReadKey();
        }
示例#4
0
        public async Task PokeDex([Remainder] string name)
        {
            PokeApiClient pokeClient = new PokeApiClient();
            Pokemon       poke       = await pokeClient.GetResourceAsync <Pokemon>(name);


            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle($"Data On {name}");
            if (poke.Types.Count == 2)
            {
                embed.WithDescription($"Type: {poke.Types[0].Type.Name} | {poke.Types[1].Type.Name}\n" +
                                      $"**HP:** {poke.Stats[0].BaseStat}\n" +
                                      $"**Attack:** {poke.Stats[1].BaseStat}\n" +
                                      $"**Defense:** {poke.Stats[2].BaseStat}\n" +
                                      $"**Sp.Atk:** {poke.Stats[3].BaseStat}\n" +
                                      $"**Sp.Def:** {poke.Stats[4].BaseStat}\n" +
                                      $"**Speed:** {poke.Stats[5].BaseStat}\n");
            }
            else
            {
                embed.WithDescription($"Type: {poke.Types[0].Type.Name}\n" +
                                      $"**HP:** {poke.Stats[0].BaseStat}\n" +
                                      $"**Attack:** {poke.Stats[1].BaseStat}\n" +
                                      $"**Defense:** {poke.Stats[2].BaseStat}\n" +
                                      $"**Sp.Atk:** {poke.Stats[3].BaseStat}\n" +
                                      $"**Sp.Def:** {poke.Stats[4].BaseStat}\n" +
                                      $"**Speed:** {poke.Stats[5].BaseStat}\n");
            }
            embed.WithImageUrl(poke.Sprites.FrontDefault);
            await Context.Channel.SendMessageAsync("", embed : embed.Build());
        }
        /// <summary>
        /// Retrieves a Pokedex entry for the specified Pokemon, which contains the pokemon's name,
        /// the blurb associated with their pokedex entry, and what game that blurb came from
        /// </summary>
        /// <param name="pokemonName">The name of the pokemon, which should be formatted as lowercase</param>
        /// <returns></returns>
        public async Task <PokedexEntry> GetPokedexEntryAsyncFor(string pokemonName)
        {
            // Clean any extra space from around the name and make sure it's in lower-case
            // or else the API throws a fit in the form of a 404 Not Found
            var formattedPokemonName = pokemonName.Trim().ToLower();

            using (PokeApiClient pkmnClient = new PokeApiClient())
            {
                var pokemonSprite = await GetFrontDefaultPokemonSpriteImageUrlAsync(pkmnClient, formattedPokemonName);

                var allFlavorTextEnglish = await GetAllEnglishPokedexEntriesAsync(pkmnClient, formattedPokemonName);

                // Select a random flavor text entry to be used
                var flavorTextDataObject = allFlavorTextEnglish[rnd.Next(allFlavorTextEnglish.Count)];

                var englishFormattedGameVersion = await GetFormattedGameVersionNameInEnglishAsync(pkmnClient, flavorTextDataObject);

                var englishFormattedPokemonName = await GetFormattedEnglishPokemonNameAsync(pkmnClient, formattedPokemonName);

                return(new PokedexEntry
                {
                    SpriteUrl = pokemonSprite,
                    PokemonName = englishFormattedPokemonName,
                    FlavorText = RemoveNewLinesFromFlavorText(flavorTextDataObject.FlavorText),
                    CameFrom = englishFormattedGameVersion
                });
            }
        }
        /// <summary>
        /// Fetches the formatted name of the version from which the pokedex entry game
        /// to display to the user, i.e., instead of "alpha-sapphire", returns "Alpha Sapphire"
        /// </summary>
        /// <param name="client">The PokeAPI client currently in use</param>
        /// <param name="flavorText">The pokedex entry selected in the body of <see cref="GetPokedexEntryAsyncFor(string)"/></param>
        /// <returns></returns>
        private async Task <string> GetFormattedGameVersionNameInEnglishAsync(PokeApiClient client, PokemonSpeciesFlavorTexts flavorText)
        {
            // In order to get the properly formatted name from the API, we need to get the Version object from the resource
            var flavorTextVersion = await client.GetResourceAsync(flavorText.Version);

            return(flavorTextVersion.Names.Where(x => x.Language.Name == "en").SingleOrDefault().Name);
        }
示例#7
0
        static async Task Main(string[] args)
        {
            PokeApiClient client = new PokeApiClient();

            try
            {
                //Pokemon result = await client.GetPokemonByName("Bulbasaur");
                Pokemon result = await client.GetPokemonById(1);

                Console.WriteLine($"Pokemon ID: {result.Id} " +
                                  $"\n  Name: {result.Name} " +
                                  $"\n  Weight: {result.Weight}lbs" +
                                  $"\n  Height: {result.Height}in");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("That Pokemon does not exist");
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Please try again later.");
            }


            Console.ReadKey();
        }
示例#8
0
        /// <summary>
        ///Given a Pokemon name,returns the description
        /// </summary>
        /// <param name="pokemonName"></param>
        /// <returns>
        /// Returns the description of the Pokemon if exists;<br/>
        /// Empty string if the pokemon does not exist;<br/>
        /// Null if something goes wrong;
        /// </returns>
        public async Task <string> FindDescriptionByNameAsync(string pokemonName)
        {
            PokeApiClient pokeClient   = new PokeApiClient();
            var           descriprtion = string.Empty;

            try
            {
                /*to avoid error 404 Pokemon not found ,i have preloaded all the pokemon'names
                 * and i chek in my HashSet before.
                 */
                if (_pokemonIndex.Contains(pokemonName))

                {
                    Pokemon pokemon = await pokeClient.GetResourceAsync <Pokemon>(pokemonName);

                    Ability ability = await pokeClient.GetResourceAsync <Ability>(pokemon.Abilities[0].Ability.Name);

                    descriprtion = ability.EffectEntries.FirstOrDefault(e => e.Language.Name == "en").Effect;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);

                return(null);
            }



            return(descriprtion);
        }
        public async Task UrlNavigationCancellationAsyncSingle()
        {
            // assemble
            Pokemon responsePikachu = new Pokemon
            {
                Name    = "pikachu",
                Id      = 25,
                Species = new NamedApiResource <PokemonSpecies>
                {
                    Name = "pikachu",
                    Url  = "https://pokeapi.co/api/v2/pokemon-species/25/"
                }
            };
            PokemonSpecies responseSpecies = new PokemonSpecies {
                Name = "pikachu"
            };

            MockHttpMessageHandler mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect("*pokemon/pikachu/").Respond("application/json", JsonConvert.SerializeObject(responsePikachu));
            mockHttp.Expect("*pokemon-species/25/").Respond("application/json", JsonConvert.SerializeObject(responseSpecies));
            PokeApiClient client = new PokeApiClient(mockHttp);

            Pokemon pikachu = await client.GetResourceAsync <Pokemon>("pikachu");

            CancellationToken cancellationToken = new CancellationToken(true);

            // act / assemble
            await Assert.ThrowsAsync <OperationCanceledException>(async() => { await client.GetResourceAsync(pikachu.Species, cancellationToken); });
        }
示例#10
0
        // GET: UserDraftPicks/Details/5
        public async Task <ActionResult> Details(int?draftId, string userId)
        {
            if (draftId == null || userId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var userDraftPicks = db.UserDraftPicks.Where(dp => dp.DraftId == draftId && dp.UserId == userId).Select(dp => dp.PokemonLocalId).ToList();
            var tieredPokemon  = db.vw_PokemonTiered.Where(p => userDraftPicks.Any(dp => dp == p.PokemonLocalId)).ToList();

            // *** ***

            PokeApiClient pokeClient = new PokeApiClient();
            var           pokemon    = new List <Pokemon>();

            foreach (var item in tieredPokemon)
            {
                Pokemon poke = await pokeClient.GetResourceAsync <Pokemon>(item.PokemonName);

                pokemon.Add(poke);
            }

            var currentPlayer = db.AspNetUsers.Find(userId);

            var viewModel = new UserDraftPickDetailsViewModel()
            {
                PokemonTiered = tieredPokemon,
                Pokemons      = pokemon,
                BattleTag     = currentPlayer.BattleTag,
            };

            return(View(viewModel));
        }
        public async Task ClearResourceListCacheOfSpecificType()
        {
            // assemble
            PokeApiClient sut = CreateSut();

            mockHttp.Expect("*machine")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeApiResourceList <Machine>()));
            mockHttp.Expect("*berry")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeNamedResourceList <Berry>()));
            mockHttp.Expect("*machine")
            .Respond("application/json", JsonConvert.SerializeObject(CreateFakeApiResourceList <Machine>()));

            // act
            await sut.GetApiResourcePageAsync <Machine>();

            await sut.GetNamedResourcePageAsync <Berry>();

            sut.ClearResourceListCache <Machine>();
            await sut.GetApiResourcePageAsync <Machine>();

            await sut.GetNamedResourcePageAsync <Berry>();

            // assert
            mockHttp.VerifyNoOutstandingExpectation();
        }
示例#12
0
        public async void setup(string pokeName)
        {
            if (pokeName != "")
            {
                //RootObject pokemon = await PokeApi.getDadosPokemon(formPoke.url);
                PokeApiClient pokeClient = new PokeApiClient();
                Pokemon       pokemon    = await pokeClient.GetResourceAsync <Pokemon>(pokeName);

                this.idPoke        = pokemon.Id;
                poke_imagem.Source = pokemon.Sprites.FrontDefault; //ImageSource.FromUri(new Uri(pokemon.sprites.front_default));
                poke_name.Text     = pokemon.Name.ToUpper();
                poke_weight.Text   = pokemon.Weight.ToString();
                poke_height.Text   = pokemon.Height.ToString();

                StringBuilder types = new StringBuilder();
                if (pokemon.Types != null)
                {
                    foreach (var item in pokemon.Types)
                    {
                        types.Append(item.Type.Name).Append(" - ");
                    }
                    types.Remove(types.Length - 3, 3);
                }
                else
                {
                    types.Append("-");
                }

                poke_types.Text = types.ToString().ToUpper();
            }
        }
        public async Task ClearResourceCacheOfAllTypes()
        {
            // assemble
            Berry berry = new Berry {
                Name = "test", Id = 1
            };
            Machine machine = new Machine {
                Id = 1
            };
            PokeApiClient sut = CreateSut();

            mockHttp.Expect("*machine*")
            .Respond("application/json", JsonConvert.SerializeObject(machine));
            mockHttp.Expect("*berry*")
            .Respond("application/json", JsonConvert.SerializeObject(berry));
            mockHttp.Expect("*machine*")
            .Respond("application/json", JsonConvert.SerializeObject(machine));
            mockHttp.Expect("*berry*")
            .Respond("application/json", JsonConvert.SerializeObject(berry));

            // act
            await sut.GetResourceAsync <Machine>(machine.Id);

            await sut.GetResourceAsync <Berry>(berry.Id);

            sut.ClearResourceCache();
            await sut.GetResourceAsync <Machine>(machine.Id);

            await sut.GetResourceAsync <Berry>(berry.Id);

            // assert
            mockHttp.VerifyNoOutstandingExpectation();
        }
示例#14
0
        internal static async void ShinySpawnPokemon(SocketGuild guild, SocketTextChannel channel, string PokemonName)
        {
            PokeApiClient pokeClient = new PokeApiClient();
            Pokemon       poke       = await pokeClient.GetResourceAsync <Pokemon>(PokemonName);

            Spawned spawn = new Spawned()
            {
                channel = channel.Id,
                name    = poke.Name,
                shiny   = true
            };
            string result = JsonConvert.SerializeObject(spawn);

            Console.WriteLine(result);
            File.WriteAllText(@"Resources/Spawned.json", result);
            Console.WriteLine("Stored!");

            result = String.Empty;
            result = File.ReadAllText(@"Resources/Spawned.json");
            Spawned resultSpawn = JsonConvert.DeserializeObject <Spawned>(result);

            Console.WriteLine(resultSpawn.ToString());

            Console.WriteLine($"{poke.Name}");
            var embed = new EmbedBuilder();

            embed.WithTitle("A wild pokemon has appeared!");
            embed.WithDescription("Guess the pokemon and type p.catch <pokemon> to catch it");
            embed.WithImageUrl($"https://play.pokemonshowdown.com/sprites/xyani-shiny/" + spawn.name + ".gif");


            await channel.SendMessageAsync("", embed : embed.Build());
        }
示例#15
0
 public async Task Handle(Message message, ITelegramBotClient botClient, PokeApiClient pokeApiClient)
 {
     await botClient.SendTextMessageAsync(
         chatId : message.Chat,
         text : $"Hello, {message.From.FirstName}\\! I'm the Pokédex Bot\\. You can ask me about Pokémon names and I'll show you their Pokédex information\\. To get this information please enter /battle followed by the name or ID of the Pokémon, e\\.g\\. `/battle Charizard`\\.",
         parseMode : ParseMode.MarkdownV2
         );
 }
        // GET: Pokemons
        public async Task <ActionResult> Details(string name)
        {
            PokeApiClient pokeClient = new PokeApiClient();

            Pokemon hoOh = await pokeClient.GetResourceAsync <Pokemon>(name);

            return(View(hoOh));
        }
示例#17
0
 public async Task Handle(Message message, ITelegramBotClient botClient, PokeApiClient pokeApiClient)
 {
     await botClient.SendTextMessageAsync(
         chatId : message.Chat,
         text : $"Hello, {message.From.FirstName}! I'm the Pokédex Bot. Supported commands are /start, /help, and /battle <name or ID>.",
         parseMode : ParseMode.Default
         );
 }
        /// <summary>
        /// Get pokemon by id
        /// Moves will be sorted in alphabetical order
        /// </summary>
        /// <param name="desiredId"></param>
        /// <returns></returns>
        public static async Task <Pokemon> GetById(int desiredId)
        {
            PokeApiClient myClient = new PokeApiClient();
            Pokemon       result   = await myClient.GetPokemonById(desiredId);

            result.moves.OrderBy(m => m.move.name);

            return(result);
        }
        public void Setup()
        {
            this.pokeApiClient      = new PokeApiClient();
            this.pokemonService     = new PokemonService(this.pokeApiClient);
            this.shakespeareService = new ShakespeareService();
            this.cacheService       = new CacheService();

            this.translationService = new TranslationService(pokemonService, shakespeareService, cacheService);
        }
示例#20
0
        /// <summary>
        /// Get Pokemon by ID,
        /// moves will be sorted alphabetically.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task <Pokemon> GetByID(int id)
        {
            PokeApiClient myClient = new PokeApiClient();
            Pokemon       result   = await myClient.GetPokemonById(id);

            // sorts moves by name, alphabetically
            result.moves.OrderBy(m => m.move.name);

            return(result);
        }
示例#21
0
        /// <summary>
        /// Fetch the formatted name of the pokemon being queried
        /// </summary>
        /// <param name="client">The PokeAPI client currently in use</param>
        /// <param name="pokemonName">The name of the pokemon as a search term submitted by the end user</param>
        /// <returns></returns>
        private async Task <string> GetFormattedEnglishPokemonNameAsync(PokeApiClient client, string pokemonName)
        {
            var pokemonApiObject = await client.GetResourceAsync <Pokemon>(pokemonName);

            var pokemonSpeciesObject = await client.GetResourceAsync(pokemonApiObject.Species);

            var englishName = pokemonSpeciesObject.Names.Where(x => x.Language.Name == "en").Select(y => y.Name).Single();

            return(englishName);
        }
示例#22
0
        public void GivenJson_WhenParsePokemonsPage_ThenReturnsExpected(string file, int expectedCount, string expectedNextPage)
        {
            var json = File.ReadAllText(file);

            var actual = PokeApiClient.ParsePokemonsPage(json);

            Assert.IsNotNull(actual);
            Assert.AreEqual(expectedCount, actual.Names.Length);
            Assert.AreEqual(expectedNextPage, actual.NextPage?.ToString());
        }
示例#23
0
        public async Task GetLocationPagedResourceIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            NamedApiResourceList <Location> page = await client.GetNamedResourcePageAsync <Location>();

            // assert
            Assert.True(page.Results.Any());
        }
示例#24
0
        public async Task GetSuperContestEffectResourceAsyncIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            SuperContestEffect superContestEffect = await client.GetResourceAsync <SuperContestEffect>(1);

            // assert
            Assert.True(superContestEffect.Id != default(int));
        }
示例#25
0
        public async Task GetEvolutionChainPagedResourceIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            ApiResourceList <EvolutionChain> page = await client.GetApiResourcePageAsync <EvolutionChain>();

            // assert
            Assert.True(page.Results.Any());
        }
示例#26
0
        public async Task GetEncounterConditionValuePagedResourceIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            NamedApiResourceList <EncounterConditionValue> page = await client.GetNamedResourcePageAsync <EncounterConditionValue>();

            // assert
            Assert.True(page.Results.Any());
        }
示例#27
0
        public async Task GetSuperContestEffectPagedResourceIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            ApiResourceList <SuperContestEffect> page = await client.GetApiResourcePageAsync <SuperContestEffect>();

            // assert
            Assert.True(page.Results.Any());
        }
示例#28
0
        public async Task GetContestTypeResourceAsyncIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            ContestType contestType = await client.GetResourceAsync <ContestType>(1);

            // assert
            Assert.True(contestType.Id != default(int));
        }
示例#29
0
        public async Task GetTypeResourceAsyncIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            PokeApiNet.Models.Type type = await client.GetResourceAsync <PokeApiNet.Models.Type>(1);

            // assert
            Assert.True(type.Id != default(int));
        }
示例#30
0
        public async Task GetStatResourceAsyncIntegrationTest()
        {
            // assemble
            PokeApiClient client = new PokeApiClient();

            // act
            Stat stat = await client.GetResourceAsync <Stat>(1);

            // assert
            Assert.True(stat.Id != default(int));
        }