示例#1
0
        public void TestFetchPageInfo()
        {
            PageInfo p = DataFetcher.FetchPageInfo(testUrl);

            Assert.IsNotNull(p.PageTitle);
            Assert.IsTrue(p.ImageCount > 0);
        }
示例#2
0
        public void TestCheckAbsoluteUriRelative()
        {
            string relativeUri = "/images/relative.gif";
            bool   isAbsolute  = DataFetcher.CheckUrlAbsolute(relativeUri);

            Assert.IsFalse(isAbsolute, "check failed to identify relative uri");
        }
示例#3
0
        public void TestCheckAbsoluteUriAbsolute()
        {
            string absoluteUri = "http://www.google.com.au";
            bool   isAbsolute  = DataFetcher.CheckUrlAbsolute(absoluteUri);

            Assert.IsTrue(isAbsolute, "check failed to identify absolute uri");
        }
示例#4
0
        private void StudyBuddyFindBuddyButton_Click(object sender, EventArgs e)
        {
            availableBuddiesLabel.Visible = true;
            availableBuddiesFlowLayoutPanel.Controls.Clear(); //clearing what was in panel before

            List <User> users         = DataFetcher.GetUsersAsList();
            var         userInterests = DataFetcher.GetUserInterestsAsStringList();


            var subjectID = getId(chooseWhatToLearnComboBox.Text, interests); //^delegate usage

            //get users who have that interest and are up for teaching
            var matchedUsers = from user in users
                               join userInterest in userInterests
                               on user.id equals Convert.ToInt32(userInterest[0])                             // userInterest[0] - userID
                                   where user.upForTeaching == 1
                                   where Convert.ToInt32(userInterest[1]) == subjectID.FirstOrDefault <int>() // userInterest[1] - subjectID
                                   where user.id != CurrentUser.id
                               select user.name;

            Action <IEnumerable <string> > showUsers = delegate(IEnumerable <string> Users) //^anonymous method
            {
                foreach (var user in Users)
                {
                    Label name = new Label();
                    name.AutoSize = true;
                    name.Text     = user;
                    availableBuddiesFlowLayoutPanel.Controls.Add(name);
                }
            };

            showUsers(matchedUsers);
        }
示例#5
0
 public FileWatcher(DataFetcher dataFetcher, string directory, ErrorFetcher errorFetcher, MonitoringSourceControl sourceControl)//FileWatcher Constructor initializing all Delegates
 {
     this.Directory     = directory;
     this.fetcher       = dataFetcher;
     this.errorFetcher  = errorFetcher;
     this.MonitorSCList = sourceControl;
 }
示例#6
0
        private async Task GetPkmnType(IDialogContext context, string PkmnName)
        {
            try
            {
                List <string> Types = new List <string>();
                Pokemon       p     = await DataFetcher.GetNamedApiObject <Pokemon>(PkmnName);

                if (p != null)
                {
                    string Tipos = "";
                    foreach (var tp in p.Types)
                    {
                        Types.Add(tp.Type.Name);
                        Tipos += tp.Type.Name;
                        Tipos += " ";
                    }
                    //string Tipos = "Flying Dragon "; // Para testes no Proxy
                    await context.PostAsync($"Tipo(s) de {PkmnName}: {Tipos.Trim()}");
                }
                context.Wait(MessageReceived);
            }
            catch (Exception e)
            {
                await context.PostAsync($"[GetPkmnType]Ocorreu um erro: {e.Message}");
            }
        }
示例#7
0
        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine(e.Data);
            DataFetcher dataFetcher = new DataFetcher();

            LoLClient lol = new LoLClient();

            if (e.Data.Contains("#01"))
            {
                Send(lol.GetSummonerIdByName(e.Data.Substring(3)));
            }
            else if (e.Data.Contains("#04"))
            {
                // ↓ Tony, add here the method for ChampionStatisticsActivity
                //Send ($"#05{METHOD NAME)");
                string jsonChampStats = dataFetcher.ChampionStatsData(e.Data.Substring(3));
                Console.WriteLine(jsonChampStats);
                Send($"{jsonChampStats}");
            }
            else if (e.Data.Contains("#06"))
            {
                // ↓ Tony, add here the method for MatchHistory
                //Send ($"#07{METHOD NAME)");
                string jsonMatchesHistory = dataFetcher.MatchHistoryData(e.Data.Substring(3));
                Send($"{jsonMatchesHistory}");
            }
        }
示例#8
0
        /// <summary>
        /// 获取查询参数列表
        /// 如果QueryParameters有值,则以其为准,否则,以DataFetcher为准
        /// </summary>
        /// <returns>查询参数列表</returns>
        public IEnumerable <DataParameter> GetParameters()
        {
            List <DataParameter> queryParameters = new List <DataParameter>();

            if (DataFetcher.IsNotNull())
            {
                var parameters = DataFetcher.Value.GetParameters();
                if (parameters.IsNotNullOrEmpty())
                {
                    queryParameters.AddRange(parameters);
                }
            }

            if (QueryParameters.IsNotNullOrEmpty())
            {
                for (int i = 0; i < queryParameters.Count; i++)
                {
                    var foundParam = QueryParameters.Where(p => p.Name == queryParameters[i].Name).FirstOrDefault();
                    if (foundParam != null)
                    {
                        queryParameters[i] = foundParam;
                    }
                }
            }
            return(queryParameters);
        }
示例#9
0
        public void TestRemoveInvalidCharacters()
        {
            string illegalFilename = "asdf?g.gif";
            string newFilename     = DataFetcher.RemoveInvalidFilenameCharacters(illegalFilename);

            Assert.AreEqual("asdfg.gif", newFilename);
        }
示例#10
0
        public IHttpActionResult PostStock(string stockSymbol)
        {
            Stock stock = null;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!db.Stocks.Any(s => s.Symbol == stockSymbol))
            {
                try
                {
                    stock = DataFetcher.GetStockQuote(stockSymbol);
                }
                catch (Exception)
                {
                    return(Content(HttpStatusCode.BadRequest, "Stock symbol not found."));
                }

                db.Stocks.Add(stock);
                db.SaveChanges();
            }
            else
            {
                return(Content(HttpStatusCode.BadRequest, "The stock you are trying to add is already in the list."));
            }

            return(CreatedAtRoute("DefaultApi", new { id = stock.ID }, stock));
        }
        /// <summary>
        /// Defines the actions at the start of the service
        /// </summary>
        /// <param name="args">Start para</param>
        protected override void OnStart(string[] args)
        {
            log.Info($"Starting the {nameof(SolarEdgeService)}");
            DataFetcher DF = DataFetcher.Instance;

            DF.ConnectionTimeoutMs         = SolarEdgeServiceSettings.Default.ConnectionTimeoutMs;
            DF.IPAdress                    = SolarEdgeServiceSettings.Default.IPAdress;
            DF.ModBusPort                  = SolarEdgeServiceSettings.Default.ModBusPort;
            DF.RefreshIntervalMs           = SolarEdgeServiceSettings.Default.RefreshIntervalMs.Limit(1, int.MaxValue);
            DF.ReadInverterData            = SolarEdgeServiceSettings.Default.ReadInverterData;
            DF.ReadMeterData               = SolarEdgeServiceSettings.Default.ReadMeterData;
            DF.MinIntervalBetweenUpdatesMs = SolarEdgeServiceSettings.Default.MinIntervalBetweenUpdatesMs.Limit(1, int.MaxValue);

            DataUpdateModeEnum dataUpdateMode;

            if (Enum.TryParse(SolarEdgeServiceSettings.Default.DataUpdateMode, out dataUpdateMode))
            {
                DF.DataUpdateMode = dataUpdateMode;
            }
            else
            {
                log.Debug($"No valid DataUpdateMode valkue found. Will use {DataUpdateModeEnum.UpdateExistingObjects} as default. Valid values are {DataUpdateModeEnum.UpdateExistingObjects} and {DataUpdateModeEnum.CreateNewObjects}");
                DF.DataUpdateMode = DataUpdateModeEnum.UpdateExistingObjects;
            }


            DF.Start();
            CommunicationManager.Instance.ActivateServices();

            log.Info($"{nameof(SolarEdgeService)} started");
        }
示例#12
0
        /// <summary>
        /// 获取格式表
        /// DataColumns,则以其为准,否则,以DataColumns为准
        /// </summary>
        /// <returns>格式表</returns>
        public IEnumerable <DataField> GetColumns()
        {
            List <DataField> dataColumns = new List <DataField>();;

            if (DataFetcher.IsNotNull())
            {
                var schemaTable = DataFetcher.Value.GetDataSchema();
                var fields      = DataPublic.GetDataFieldsByTable(schemaTable);
                dataColumns.AddRange(fields);
            }

            if (DataColumns.IsNotNullOrEmpty())
            {
                foreach (DataField dataColumn in DataColumns)
                {
                    var foundColumn = dataColumns.Where(p => p.Name == dataColumn.Name).FirstOrDefault();
                    if (foundColumn != null)
                    {
                        dataColumns.Remove(foundColumn);
                    }
                    dataColumns.Add(dataColumn);
                }
            }
            return(dataColumns);
        }
示例#13
0
        private static async void OnSearch(object sender, EventArgs e)
        {
            mainLabel.Text = "Cargando...";
            PokemonSpecies p = await DataFetcher.GetNamedApiObject <PokemonSpecies>(pkmnText.Text.ToLower());

            Pokemon pk = await DataFetcher.GetNamedApiObject <Pokemon>(pkmnText.Text.ToLower());

            if (p == null || pk == null)
            {
                throw new Exception("Eso no es un Pokemon o llegaste al límite de llamadas al API.");
            }
            else
            {
                try
                {
                    pkmnId         = p.ID;
                    mainLabel.Text = "Ingresa el nombre de un Pokémon:";
                    GetMainInfo(pkmnId, p, pk);
                    GetBaseStats(pk);
                }
                catch (Exception ex)
                {
                    throw new Exception("Ajale jaleo!");
                }
            }
        }
示例#14
0
        [HttpGet] // https://localhost:44392/api/pokemon?name=charizard
        public async Task <PokemonModel> GetPokemon([FromQuery] string name)
        {
            var obj = await DataFetcher.GetNamedApiObject <Pokemon>(name.ToLower()); // wrapper can't handle any uppercase letters, wah wah

            // create PokemonModel from PokeApi.Pokemon
            var pokemon = new PokemonModel()
            {
                Id            = obj.ID,
                Name          = obj.Name,
                BackImageUri  = obj.Sprites.BackMale,
                FrontImageUri = obj.Sprites.FrontMale,

                BaseHP         = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("hp")).Select(s => s.BaseValue).FirstOrDefault() * 10,
                ActingHP       = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("hp")).Select(s => s.BaseValue).FirstOrDefault() * 10,
                Attack         = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("attack")).Select(s => s.BaseValue).FirstOrDefault(),
                Defense        = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("defense")).Select(s => s.BaseValue).FirstOrDefault(),
                SpecialAttack  = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("special-attack")).Select(s => s.BaseValue).FirstOrDefault(),
                SpecialDefense = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("special-defense")).Select(s => s.BaseValue).FirstOrDefault(),
                Speed          = obj.Stats.Where(s => s.Stat.Name.ToLower().Equals("speed")).Select(s => s.BaseValue).FirstOrDefault()
            };

            // add list of available moves to pokemon
            obj.Moves.Select(m => m.Move).ToList().ForEach(m =>
            {
                pokemon.Moves.Add(
                    new MoveModel()
                {
                    Name        = m.Name,
                    ResourceUri = m.Url.AbsoluteUri.ToString()
                });
            });

            foreach (var m in pokemon.Moves)
            {
                var info = await GetAdditionInfo(m.ResourceUri);

                if (info != null && info.Count > 0)
                {
                    m.Id     = info.ContainsKey("id") ? int.Parse(info?["id"].ToString()) : 0;
                    m.Damage = info.ContainsKey("power") && info?["power"] != null?int.Parse(info?["power"].ToString()) : 0;

                    m.Category = info.ContainsKey("damage_class") && info?["damage_class"] != null ? ((ExpandoObject)info?["damage_class"]).First().Value.ToString() : string.Empty;
                    m.Type     = info.ContainsKey("type") ? ((ExpandoObject)info?["type"]).First().Value.ToString() : string.Empty;
                }
            }

            pokemon.Moves.RemoveAll(m => m.Damage == 0); // get rid of moves without damage

            // add any types to the pokemon
            obj.Types.ToList().ForEach(t =>
            {
                pokemon.Types.Add(new Shared.Models.PokemonType
                {
                    Name        = t.Type.Name,
                    ResourceUri = t.Type.Url.AbsoluteUri.ToString()
                });
            });

            return(pokemon);
        }
示例#15
0
        static void Main(string[] args)
        {
            IList <UserWithPwdModel> pwd = new DataFetcher <UserWithPwdModel>().List(SqlProvider.CreateTransaction <UserWithPwdModel>());
            string      message          = "";
            UserFetcher userFetcher      = new UserFetcher();
            UserUpdater userUpdater      = new UserUpdater(userFetcher);
            //写入数据对象并提交
            DateTime dt = DateTime.Now;

            for (int i = 0; i < 10000; i++)
            {
                Random    random = new Random(i);
                string    id     = (random.Next(0, 10000)).ToString();
                string    tran   = SqlProvider.CreateTransaction <UserModel>();
                UserModel model  = userFetcher.GetById(tran, id);
                if (model == null)
                {
                    model = new UserModel()
                    {
                        Code = "liwq_" + id, Name = "liweiquan_" + id, Id = id
                    }
                }
                ;
                else
                {
                    model.Code = "llwwwqqq";
                }
                bool result = userUpdater.Save(tran, model, out message);
                SqlProvider.CloseTransaction(tran, result);
                if (result)
                {
                }
                //  Console.WriteLine(i);
                else
                {
                    Console.WriteLine(message);
                }
            }
            Console.WriteLine((DateTime.Now - dt).TotalMilliseconds);
            Console.Write("done");
            Console.Read();
            //在新的事务中,更改数据,将数据合并到持久化对象中,最后保存提交事务

            //tran = SqlProvider.CreateTransaction();
            //UserModel usrCp = new UserModel() { Id = "201201001", Code = "75125", Creator = "Liwq", Flag = 1, Name = "Liweiquande" };
            //IList<UserModel> usrDbs = SqlProvider.GetDbInstance<UserModel>().Select(tran, new List<OrderBy>() { new OrderBy() { Field = "Id" } }, new Limit(), out message, Restrain.Eq("Id", "201201001"));
            //UserModel usrDb = null;
            //if (usrDbs.Count > 0)
            //    usrDb = usrDbs[0];
            //usrDb.Merge(usrCp);
            //SqlProvider.GetDbInstance<UserModel>().Update(usrCp, tran, out message);
            //SqlProvider.CloseTransaction(tran, true);

            //在新事务中查询自定义的模板
            //tran = SqlProvider.CreateTransaction();
            //IList<UserWithPwdModel> models = SqlProvider.GetDbInstance<UserWithPwdModel>().Select(tran, new List<OrderBy>() { new OrderBy() { Field = "Id" } }, new Limit(), out message, Restrain.Lk("ID", "%2%"));
            //SqlProvider.CloseTransaction(tran,true);

            //Console.Read();
        }
示例#16
0
        public async Task <PokemonApi> recuperarPokemonAPI(string nombrePokemon)
        {
            try
            {
                PokemonApi     pokemonApi    = new PokemonApi();
                PokemonSpecies pokemonSpecie = await DataFetcher.GetNamedApiObject <PokemonSpecies>(nombrePokemon.ToLower());

                if (pokemonSpecie != null)
                {
                    pokemonApi.Id     = pokemonSpecie.ID;
                    pokemonApi.Nombre = pokemonSpecie.Name;


                    PokeAPI.Pokemon pokemon = await DataFetcher.GetNamedApiObject <PokeAPI.Pokemon>(pokemonSpecie.ID.ToString());

                    if (pokemon.Types != null)
                    {
                        pokemonApi.Tipo = pokemon.Types[0].Type.Name;
                    }

                    return(pokemonApi);
                }
            }
            catch (Exception error) { }
            return(null);
        }
示例#17
0
        public async Task <PokemonDto?> GetPokemon(int pokeNumber)
        {
            var rawCachedPokemon = await Cache.GetStringAsync(CacheKeys.Pokemon(pokeNumber));

            if (rawCachedPokemon != null)
            {
                Logger.LogTrace("Found pokemon {@PokemonId} in cache.", pokeNumber);

                var cachedPokemon = JsonConvert.DeserializeObject <PokemonDto>(rawCachedPokemon);

                return(cachedPokemon);
            }

            Pokemon        pokemon;
            PokemonSpecies species;

            try
            {
                pokemon = await DataFetcher.GetApiObject <Pokemon>(pokeNumber);

                species = await DataFetcher.GetApiObject <PokemonSpecies>(pokeNumber);
            }
            catch (Exception e)
            {
                if (e.Message == "Response status code does not indicate success: 404 (Not Found).")
                {
                    return(default);
示例#18
0
        /// <summary>
        /// This method uses the text of the activity to decide which type
        /// of card to respond with and reply with that card to the user.
        /// </summary>
        /// <param name="step">A <see cref="WaterfallStepContext"/> provides context for the current waterfall step.</param>
        /// <param name="cancellationToken" >(Optional) A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="DialogTurnResult"/> indicating the turn has ended.</returns>
        /// <remarks>Related types <see cref="Attachment"/> and <see cref="AttachmentLayoutTypes"/>.</remarks>
        private static async Task <DialogTurnResult> ShowCardStepAsync(WaterfallStepContext step, CancellationToken cancellationToken)
        {
            // Get the pokemon name from the activity
            var pokemonName = step.Context.Activity.Text.ToLowerInvariant().Split(' ')[0];

            // Reply to the activity we received with an activity.
            var reply = step.Context.Activity.CreateReply();

            // Cards are sent as Attachments in the Bot Framework.
            // So we need to create a list of attachments on the activity.
            reply.Attachments = new List <Attachment>();

            Pokemon pokemon = await DataFetcher.GetNamedApiObject <Pokemon>(pokemonName);

            PokemonSpecies pokemonSpecies = await DataFetcher.GetNamedApiObject <PokemonSpecies>(pokemonName);

            reply.Attachments.Add(GetThumbnailCard(pokemon, pokemonSpecies).ToAttachment());

            // Send the card(s) to the user as an attachment to the activity
            await step.Context.SendActivityAsync(reply, cancellationToken);

            // Give the user instructions about what to do next
            await step.Context.SendActivityAsync("Type another Pokémon name to see information about it!", cancellationToken : cancellationToken);

            return(await step.EndDialogAsync(cancellationToken : cancellationToken));
        }
示例#19
0
        public async Task Team()
        {
            MySqlConnection conn = DatabaseHelper.GetClosedConnection();

            if (!await conn.IsUserRegistered(Context.User.Id))
            {
                return;
            }

            IUserMessage msg;

            if (Private)
            {
                msg = await(await Context.User.GetOrCreateDMChannelAsync()).SendMessageAsync("Loading Data...");
            }
            else
            {
                msg = await Context.Channel.SendMessageAsync("Loading Data...");
            }

            Models.Team     t    = (await conn.GetXMLFromDatabaseAsync("Team", "Trainers", Context.User.Id)).Deserialize <Models.Team>();
            Models.Pokemon  p    = t.First();
            PokeAPI.Pokemon pApi = await DataFetcher.GetApiObject <PokeAPI.Pokemon>(p.ID);

            EmbedBuilder builder = new EmbedBuilder()
            {
                Title        = $"{(Context.User as IGuildUser).Nickname ?? Context.User.Username}'s {p.Nickname ?? pApi.Name.Capatalize()}",
                Color        = Color.Teal,
                Description  = p.ToString(pApi.Name),
                ThumbnailUrl = $"https://img.pokemondb.net/sprites/black-white/anim/normal/{pApi.Name}.gif"
            };

            await msg.ModifyAsync(x => { x.Content = ""; x.Embed = builder.Build(); });
        }
示例#20
0
            public async Task Purge(int ID)
            {
                IUserMessage msg = await Context.Channel.SendMessageAsync("Fetching Data...");

                try
                {
                    PokeAPI.Pokemon p = await DataFetcher.GetApiObject <PokeAPI.Pokemon>(ID);

                    EmbedBuilder builder = new EmbedBuilder()
                    {
                        Title = "Pokemon Request by ID", Color = Color.DarkGreen, ThumbnailUrl = p.Sprites.FrontMale
                    };

                    builder.Description = $"{FormatHelper.Capatalize(p.Name)} the {FormatHelper.Capatalize((await DataFetcher.GetApiObject<PokemonSpecies>(ID)).Genera[2].Name)}";

                    EmbedFieldBuilder field = new EmbedFieldBuilder()
                    {
                        Name     = "Base Stats",
                        IsInline = true
                    };

                    foreach (PokemonStats stat in p.Stats)
                    {
                        field.Value += $"{FormatHelper.Capatalize(stat.Stat.Name)}: {stat.BaseValue.ToString()}\n";
                    }

                    builder.AddField(field);

                    await msg.ModifyAsync(x => { x.Content = ""; x.Embed = builder.Build(); });
                }
                catch
                {
                    await msg.ModifyAsync(x => x.Content = "Could find pokemon with ID: " + ID);
                }
            }
示例#21
0
        public override async Task <FetchDataFromUrlCommand> HandleAsync(FetchDataFromUrlCommand command, CancellationToken cancellationToken = new CancellationToken())
        {
            var html = await DataFetcher.FetchData(command.Url);

            command.Html = html;
            return(await base.HandleAsync(command, cancellationToken));
        }
示例#22
0
 public HomeController(HttpClient httpClient, IConfiguration cfg,
                       DataFetcher dataFetcher)
 {
     this.httpClient  = httpClient;
     this.cfg         = cfg;
     this.dataFetcher = dataFetcher;
 }
示例#23
0
        public MonsterTypeStaticData(byte id)
        {
            var type = DataFetcher.GetApiObject <PokemonType>(id).Result;

            ID   = id;
            Name = type.Names.Single(MonsterStaticData.GetLocalizedName).Name;

            foreach (var damageRelation in type.DamageRelations.DoubleDamageTo)
            {
                DamageRelations.Attacker.Add(new TypeDamageRelationEffective((byte)damageRelation.ID));
            }
            foreach (var damageRelation in type.DamageRelations.HalfDamageTo)
            {
                DamageRelations.Attacker.Add(new TypeDamageRelationNotEffective((byte)damageRelation.ID));
            }
            foreach (var damageRelation in type.DamageRelations.NoDamageTo)
            {
                DamageRelations.Attacker.Add(new TypeDamageRelationNone((byte)damageRelation.ID));
            }

            foreach (var damageRelation in type.DamageRelations.DoubleDamageFrom)
            {
                DamageRelations.Defender.Add(new TypeDamageRelationEffective((byte)damageRelation.ID));
            }
            foreach (var damageRelation in type.DamageRelations.HalfDamageFrom)
            {
                DamageRelations.Defender.Add(new TypeDamageRelationNotEffective((byte)damageRelation.ID));
            }
            foreach (var damageRelation in type.DamageRelations.NoDamageFrom)
            {
                DamageRelations.Defender.Add(new TypeDamageRelationNone((byte)damageRelation.ID));
            }
        }
        public async Task TestPokemonApi()
        {
            PokemonSpecies p = await DataFetcher.GetNamedApiObject <PokemonSpecies>(pokemonName);

            Assert.IsNotNull(p);
            Assert.AreEqual(p.Name, pokemonName);
        }
示例#25
0
        public async Task <IEnumerable <MonsterResume> > ListAllResumePerRegion(int regionId)
        {
            Pokedex pokedex = null;
            //var

            var    assembly = IntrospectionExtensions.GetTypeInfo(typeof(MonsterRepository)).Assembly;
            Stream stream   = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.pokedex_{regionId}.json");
            string json     = "";

            using (var reader = new System.IO.StreamReader(stream))
            {
                json = await reader.ReadToEndAsync();
            }


            if (!string.IsNullOrEmpty(json))
            {
                pokedex = Newtonsoft.Json.JsonConvert.DeserializeObject <Pokedex>(json);
            }
            else
            {
                pokedex = await DataFetcher.GetApiObject <Pokedex>(regionId);
            }

            return(pokedex.Entries.Select(x => new MonsterResume
            {
                Id = x.EntryNumber,
                Name = x.Species.Name,
                ImagePath = $"{IMAGE_DEFAULT}{x.EntryNumber}{IMAGE_EXTENSION}"
            }));
        }
示例#26
0
        private IReadOnlyList <AttackLearn> GetLearnableAttacks()
        {
            var learnableAttacksList = new List <AttackLearn>();

            foreach (var move in DataFetcher.GetApiObject <Pokemon>(ID).Result.Moves)
            {
                if (move.VersionGroupDetails.Any())
                {
                    var vg = move.VersionGroupDetails.First();
                    switch (vg.LearnMethod.ID)
                    {
                    case 1:
                        learnableAttacksList.Add(new AttackLearn(Cached <AttackStaticData> .Get((short)move.Move.ID), new AttackLearn.ByLevel((byte)vg.LearnedAt)));
                        break;

                    case 2:
                        learnableAttacksList.Add(new AttackLearn(Cached <AttackStaticData> .Get((short)move.Move.ID), new AttackLearn.ByBreeding()));
                        break;

                    case 3:
                        learnableAttacksList.Add(new AttackLearn(Cached <AttackStaticData> .Get((short)move.Move.ID), new AttackLearn.ByTutor()));
                        break;

                    case 4:
                        learnableAttacksList.Add(new AttackLearn(Cached <AttackStaticData> .Get((short)move.Move.ID), new AttackLearn.ByMachine()));
                        break;
                        // Else is shit
                    }
                }
            }
            return(learnableAttacksList);
        }
示例#27
0
        private static bool SetSession(UserDataFetcher UDF)
        {
            /* Session. unix in file.
             * we will hash it.
             * send it to server.
             * __________________
             * check procedure:
             * if hash matches -> proceed
             * does not match -> invalid session
             */
            if (!InputValidator.ValidateId(UDF.GetId()))
            {
                return(error.SetErrorAndReturnFalse(ErrorCode.USER_NOT_FOUND));
            }
            //-----timestamp
            long unix = DataFetcher.GetServerTimeStamp();

            UserDataPusher.PushSessionFileLoggedIn(unix);
            string hashedUnix = timestampHasher.Hash(unix.ToString(), DataFetcher.GetDeviceIdentifier());

            UserDataPusher.UpdateUserSession(UDF, unix, hashedUnix);
            //System.Windows.Forms.MessageBox.Show($"hashedUnix: {hashedUnix} ({hashedUnix.Length})");

            return(true);

            /*
             * if (UDF.GetCurrentUserTimeStamp().IsTimeStampOlderThan(7 * 24)) //^extension
             *  //user has not been logged in for a whole week
             *  return true;
             * return true;
             */
        }
示例#28
0
        private async void GetCoinsAndCurrencies()
        {
            DataFetcher rdf    = new DataFetcher();
            string      result = await rdf.GetThings();

            MyTextBox.AppendText(result);
        }
示例#29
0
        public void GetAllAccounts()
        {
            // Example to show how to call the GET methods

            int    numberOfAccounts = 0;
            string accts            = DataFetcher.Get_Accounts();

            try
            {
                dynamic json = JsonConvert.DeserializeObject(accts);

                if (json["lastPage"] != null)
                {
                    while (json["lastPage"] == false)
                    {
                        string accounts = DataFetcher.Get_Accounts(json["nextPageKey"].ToString());
                        json              = JsonConvert.DeserializeObject(accounts);
                        numberOfAccounts += json["accounts"].Count;

                        //Code to process the accounts
                    }

                    Console.WriteLine("The number of accounts for the user " + m_sdk.UserName + " are : " + numberOfAccounts);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error parsing the json" + ex.Message.ToString());
            }
        }
示例#30
0
        public async Task GetEggGroupInstanceByIdDeserializeAllProperties()
        {
            DataFetcher.SetHttpClient(FakeHttpClientAdapter.Singleton);

            var eggGroup = await EggGroup.GetInstanceAsync(1);

            eggGroup.AssertResourceWellConfigured();
        }
示例#31
0
 void Start()
 {
     enabeld=false;
     //if (cam == null)
         cam = Camera.main;
     //if(player==null)
         player=GameObject.Find("Player").GetComponent<Player>();
     dataFetcher=GetComponent<DataFetcher>();
     //cam = Camera.main;
     debug=GameObject.Find("debug").GetComponent<Text>();
     //debug.text = Screen.dpi + " res " + Screen.width+" " + Screen.height;
     GameObject clone= Instantiate (lineRenderer, transform.position, transform.rotation) as GameObject;
     linerenderer=clone.GetComponent<LineRenderer>();
     spriteRn= Instantiate (touchPointer, transform.position, transform.rotation) as GameObject;
     spriteR=spriteRn.GetComponent<SpriteRenderer>();
     spriteR.enabled = false;
     linerenderer.enabled=false;
      screenSize = Mathf.Sqrt (Screen.width * Screen.width + Screen.height * Screen.height) / Screen.dpi;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Do przekazania z drzewa - co jest rozwinięte (strategia, cel czy dzialanie) i id tego czegos rozwiniętego
        // jezeli bedzie kilka galezi rozwiniętch jednoczesnie? (? lista parametrow? po przecinku ?)
        int strategyNr = 3, targetNr = 16, subtargetNr = 27, dzialNr = 6;// do testow

        DataFetcher dataFetcher = new DataFetcher();
        String query;

        //Wszystkie strategie
        query = "SELECT id, id_parent, lp, nazwa_strategii AS tresc, nazwa_jednostki, widocznosc FROM strategia";
        SqlDataAdapter strategies = dataFetcher.getSelectResultsAsSQLDataAdapter(query);

        //wszystkie cele
        query = "SELECT id, lp, id_strategii, id_parent, tresc, widocznosc FROM cel WHERE id_parent is null";
        SqlDataAdapter targets = dataFetcher.getSelectResultsAsSQLDataAdapter(query);

        //podcele do konkretnego celu
        query = "SELECT id, lp, id_strategii, id_parent, tresc, widocznosc FROM cel "
            + "WHERE id_parent = " + targetNr + ";";
        SqlDataAdapter subTargets = dataFetcher.getSelectResultsAsSQLDataAdapter(query);

        //dzialania do konkretnego celu/podcelu
        query = "SELECT * FROM dzialanie_cel INNER JOIN dzialanie " +
            "ON dzialanie_cel.id_celu = " + targetNr +";";
        SqlDataAdapter operations = dataFetcher.getSelectResultsAsSQLDataAdapter(query);

        DataTable dt = dataFetcher.getSelectResultsAsDataTable("SELECT id, lp, tresc from cel where id_strategii = " + strategyNr + ";");

        int no = dt.Rows.Count;

        for (int i=0; i<no; i++) // dla wszytskich wyciagnietych wierszy
        {
            TableRow row = new TableRow();

            String id = dt.Rows[0]["id"].ToString();

            //liczba porządkowa
            TableCell lpCell = new TableCell();
            lpCell.CssClass = "lpCells";
            lpCell.Controls.Add(new LiteralControl(strategyNr + "." + dt.Rows[i]["lp"].ToString()));
            row.Cells.Add(lpCell);

            //tresc
            TableCell contentCell = new TableCell();
            contentCell.CssClass = "contentCells";
            contentCell.Controls.Add(new LiteralControl(dt.Rows[i]["tresc"].ToString()));
            row.Cells.Add(contentCell);

            // wszystkie guziki
            TableCell buttonCell = new TableCell();
            buttonCell.CssClass = "buttonCells";
            buttonCell.Width = 66;

            //dodaj
            ImageButton addButton = new ImageButton();
           // addButton.ID = "addButton_" + id;
            addButton.ImageUrl = "add.png";
            addButton.Enabled = true;
            addButton.Visible = true;
            addButton.Height = 22;
            addButton.Width = 22;
            addButton.OnClientClick = "javascript:Popup(" + id + "," + strategyNr + "," + 0 + ");";
            buttonCell.Controls.Add(addButton);

            //edytuj
            ImageButton editButton = new ImageButton();
           // editButton.ID = "editButton_" + id;
            editButton.ImageUrl = "edit.png";
            editButton.Enabled = true;
            editButton.Visible = true;
            editButton.Height = 22;
            editButton.Width = 22;
            editButton.OnClientClick = "javascript:Popup(" + id + "," + strategyNr + "," + 1 + ");";
            buttonCell.Controls.Add(editButton);

            //usun
            //niebezpiczne usuwanie
            ImageButton deleteButton = new ImageButton();
          //  deleteButton.ID = "deleteButton_" + id;
            deleteButton.ImageUrl = "delete.png";
            deleteButton.Enabled = true;
            deleteButton.Visible = true;
            deleteButton.Height = 22;
            deleteButton.Width = 22;
            deleteButton.OnClientClick = "javascript:Popup(" + id + "," + strategyNr + "," + 1 + ");";
            buttonCell.Controls.Add(deleteButton);
            row.Cells.Add(buttonCell);
            TargetTable.Rows.Add(row);
        }
    }
示例#33
0
    void Awake()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy (gameObject);

            cam = Camera.main;
            player=GameObject.Find("Player").GetComponent<Player>();
            scorePanel=GameObject.Find("Panel_Score").GetComponent<RectTransform>();

        boardScript=GetComponent<BoardManager>();
        inputHandler=GetComponent<InputHandler>();
        dataFetcher=GetComponent<DataFetcher>();

        scoreSlider = scorePanel.Find("Slider_Score").GetComponent<Slider>();
        livesSlider = scorePanel.Find("Slider_lives").GetComponent<Slider>();
        levelText=GameObject.Find("level").GetComponent<Text>();
        levelDesc=GameObject.Find("level_desc").GetComponent<Text>();

        scoreText = scorePanel.Find("Text_Score").GetComponent<Text>();
        sceneEnd = GameObject.Find ("scene_end").GetComponent<Image>();
        bRestart= GameObject.FindWithTag ("Respawn").GetComponent<Button>();
        bRestart.gameObject.SetActive (false);
        bResume= GameObject.FindWithTag ("Resume").GetComponent<Button>();
        bResume.gameObject.SetActive (false);
        bPause= GameObject.FindWithTag ("Pause").GetComponent<Button>();
        //bPause.gameObject.SetActive (false);
        bExit= GameObject.FindWithTag ("Finish").GetComponent<Button>();
        bExit.gameObject.SetActive (false);
        bSoundOn= GameObject.Find ("sound_on").GetComponent<Button>();
        bSoundOn.gameObject.SetActive (false);
        bSoundOff= GameObject.Find ("sound_off").GetComponent<Button>();
        bSoundOff.gameObject.SetActive (false);
        debug=GameObject.Find("debug").GetComponent<Text>();
        sound= GetComponent<AudioSource>();

        initGame ();
        if (Screen.width > Screen.height)
            camerazoom = 8;
        StartCoroutine("cameraZoomIn");
        highS = PlayerPrefs.GetInt ("high_score");
    }