예제 #1
0
        public async Task <string[]> GetSeriesTags(int seriesId)
        {
            if (SeriesTagsCache.TryGetValue(seriesId, out var v))
            {
                return(v);
            }
            var request  = new HttpRequestMessage(HttpMethod.Get, apiUrl + $"/series/{seriesId}");
            var response = await HTTP.SendAsync(request);

            var content = await response.Content.ReadAsStringAsync();

            Program.LogMsg($"{seriesId} :: {response.StatusCode}", LogSeverity.Info, "GetSeriesTags");
            var jobj   = JObject.Parse(content);
            var array  = jobj["tags"].ToObject <string[]>();
            var parsed = new List <string>();

            foreach (var tag in array)
            {
                if (!int.TryParse(tag, out var tagId))
                {
                    parsed.Add(tag);
                    continue;
                }
                var label = await GetTagLabel(tagId);

                parsed.Add(label);
            }
            SeriesTagsCache.Add(seriesId, parsed.ToArray());
            Program.LogMsg($"For {seriesId}: [{string.Join(", ", parsed)}]", LogSeverity.Info, "GetSeriesTags");
            return(parsed.ToArray());
        }
예제 #2
0
        CacheDictionary <string, int> getMockCacheDict(out DateTime now)
        {
            var      nw    = now = _getNowRoundedUp();
            DateTime nowP2 = now.AddMinutes(2);

            var cd = new CacheDictionary <string, int>(TimeSpan.FromMinutes(1))
            {
                // IMPORTANT NOTE:
                // for mocking, we MUST set this value to greater than highest
                // mock time we want to test ({ "Pineapples", 5 }), otherwise
                // purges will be firing when we don't want them to which will
                // fail the test state / make testing impossible
                RunPurgeTS = TimeSpan.FromMinutes(6)
            };

            foreach (var kv in MockVals1)
            {
                string ky  = kv.Key;
                int    val = kv.Value;

                DateTime fakeAddedTimeAfterNow = now.AddMinutes(val);
                cd.GetDateTimeNow = () => fakeAddedTimeAfterNow;
                cd.Add(ky, val);
            }

            cd.GetDateTimeNow = () => nw;

            return(cd);
        }
예제 #3
0
        public void ParseRow(string[] rowData)
        {
            int index = 0;

            index++;
            Id                  = int.Parse(rowData[index++]);
            index              += 3;
            QuestType           = int.Parse(rowData[index++]);
            TargetProgressCount = int.Parse(rowData[index++]);
            Params              = new CacheList <int>();
            for (int i = 0; i < 5; i++)
            {
                Params.Add(int.Parse(rowData[index++]));
            }
            PrePlayerLevel  = int.Parse(rowData[index++]);
            RewardPlayerExp = int.Parse(rowData[index++]);
            RewardItems     = new CacheDictionary <int, int>();
            for (int i = 0; i < 5; i++)
            {
                int key   = int.Parse(rowData[index++]);
                int value = int.Parse(rowData[index++]);
                if (key != 0)
                {
                    RewardItems.Add(key, value);
                }
            }

            DTDailyQuestCache.TryAdd(Id.ToString(), this);
        }
예제 #4
0
        public virtual bool EnterScene(Creature creature, Vector3 pos)
        {
            if (creature == null || pos == null)
            {
                return(false);
            }

            Grid grid = Grid9Manager.GetGrid(pos);

            if (grid == null)
            {
                Console.WriteLine("Creature:{0} EnterScene failed", creature.Cid);
                return(false);
            }

            grid.AddCid(creature.Cid);

            if (creature.CreatureType != CreatureTypeEnum.CREATURE_PLAYER)
            {
                MapSceneOtherCreature.Add(creature.Cid, creature);
            }
            else
            {
                Player player = (Player)creature;
                m_MapScenePlayer.Add(player.Cid, player);
            }

            return(true);
        }
예제 #5
0
        public virtual bool AddCacheLookup(NodeNetworkSceneTemplate pNodeTemplate)
        {
            if (pNodeTemplate == null)
            {
                return(false);
            }

            return(_scenesCached.Add(pNodeTemplate.SceneName, pNodeTemplate));
        }
예제 #6
0
 public void Add_CacheCapacityReached_MRUKVPRemovedAndNewKVPAdded()
 {
     _cache = new CacheDictionary<int, int>(5,CachePurgeStatergy.MRU);
     FillCache();
     _cache.Add(5, 5);
     Assert.IsFalse(_cache.ContainsKey(4));
     Assert.IsTrue(_cache.ContainsKey(5));
     Assert.AreEqual(_cache.CacheCapacity, _cache.Count);
 }
예제 #7
0
        public virtual void AddPendingServiceCallback(ServiceCallback pCallback)
        {
            if (pCallback == null)
            {
                return;
            }

            pCallback.CallbackId = _usedServiceCallbackIds.GetNext();
            _pendingServiceCallbacks.Add(pCallback.CallbackId, pCallback);
        }
예제 #8
0
        public void Add <T>(T entity) where T : class, IReportingEntity
        {
            lock (lockr)
            {
                var type = typeof(T);
                var data = new CacheData(entity);

                if (_cache.ContainsKey(type))
                {
                    var newId = _cache[type].Max(x => x.Key) + 1;
                    _cache[type].Add(newId, data);
                }
                else
                {
                    _cache.Add(type, new Dictionary <int, CacheData>()
                    {
                        { 1, data }
                    });
                }
            }
        }
예제 #9
0
        void ResolveHost(DnsQuestion question)
        {
            IPAddress address;

            if (IPAddress.TryParse(question.QueryName, out address))
            {
                Console.WriteLine("Ignored question for IP {0}.", address);
                Cache.Add(question, new DnsCacheEntry {
                    Data       = address.GetAddressBytes(),
                    TimeToLive = TimeSpan.FromMinutes(1)
                });
            }
            else
            {
                byte[] addr = HostsFile[question.QueryName];
                if (addr == null)
                {
                    byte[] pkt = new DnsPacket {
                        RecursionDesired = true,
                        Questions        = new [] {
                            question
                        }
                    }.ToByteArray();
                    Console.WriteLine("Question for {0}", question.QueryName);
                    foreach (UdpClient upstream in Upstreams)
                    {
                        upstream.Send(pkt, pkt.Length);
                    }
                }
                else
                {
                    Console.WriteLine("Found {0} in hosts file.", question.QueryName);
                    Cache.Add(question, new DnsCacheEntry {
                        Data       = addr,
                        TimeToLive = HostsFile.TimeToLive
                    });
                }
            }
        }
예제 #10
0
        public static GameContext GetInstance(int actionId, int userId, int timeOut = TimeOut)
        {
            string key = string.Format("{0}_{1}", actionId, userId);

            if (!_contextSet.ContainsKey(key))
            {
                _contextSet.Add(key, new GameContext(actionId, userId, timeOut));
            }
            var context = _contextSet[key];

            if (context != null)
            {
                context.ExpireDate = MathUtils.Now;
            }
            return(context);
        }
예제 #11
0
        public ProxyHandler(ConfigFile cfg)
        {
            MainCache = new CacheDictionary <string, ProxySettings>();
            string   proxyProgram = cfg["Proxy"]["program"].Value;
            TimeSpan defaultTTL   = TimeSpan.FromSeconds(cfg["Proxy"]["defaultTTL"].ToDouble(300));
            TimeSpan timeout      = TimeSpan.FromSeconds(cfg["Proxy"]["programTimeout"].ToDouble(15));

            MainCache.CacheMiss       += host => new ProxyProgram(proxyProgram, host, defaultTTL, timeout).Finished += settings => MainCache.Add(host, settings);
            ConnectionCache            = new CacheDictionary <ushort, ProxyEntry>();
            ConnectionCache.CacheMiss += nonce => {
                Console.Error.WriteLine("Connection has expired.");
                ConnectionCache.Add(nonce, new ProxyEntry(nonce)
                {
                    Settings   = DefaultSettings,
                    TimeToLive = TimeSpan.Zero
                });
            };
            ConnectionTimeout = TimeSpan.FromSeconds(cfg["Proxy"]["connectionTimeout"].ToDouble(60));
        }
예제 #12
0
 public Task <Tuple <byte[], uint> > GetFirstConfigurationPacket(string host)
 {
     return(MainCache[host].ContinueWith(t => {
         ProxyEntry entry = new ProxyEntry {
             Settings = t.Result,
             ConfigurationTriesSent = 1,
             TimeToLive = ConnectionTimeout
         };
         ConnectionCache.Add(entry.Nonce, entry);
         byte[] buffer = new byte[4];
         BitConverter.GetBytes(entry.Nonce).CopyTo(buffer, 0);
         if (BitConverter.IsLittleEndian)
         {
             Array.Reverse(buffer, 0, 2);
         }
         SerializeTry(t.Result, 0, buffer, 2);
         return new Tuple <byte[], uint>(buffer, (uint)t.Result.TimeToLive.TotalSeconds);
     }));
 }
예제 #13
0
        public void ParseRow(string[] rowData)
        {
            int index = 0;

            index++;
            Id = int.Parse(rowData[index++]);
            index++;
            TitleName      = rowData[index++];
            TitleTextureId = int.Parse(rowData[index++]);
            TitleMinScore  = int.Parse(rowData[index++]);
            TitleMaxScore  = int.Parse(rowData[index++]);
            Reward         = new CacheDictionary <int, int>();
            for (int i = 0; i < 5; i++)
            {
                int key   = int.Parse(rowData[index++]);
                int value = int.Parse(rowData[index++]);
                Reward.Add(key, value);
            }
            DTPvpTitleCache.TryAdd(Id.ToString(), this);
        }
예제 #14
0
        /// <summary>
        /// 获得当前请求上下文
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="actionId"></param>
        /// <param name="userId"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static GameContext GetInstance(string sessionId, int actionId, int userId, int timeOut = TimeOut)
        {
            if (string.IsNullOrEmpty(sessionId))
            {
                sessionId = Guid.NewGuid().ToString("N");
            }
            string key = CreateContextKey(sessionId, actionId);

            if (!_contextSet.ContainsKey(key))
            {
                _contextSet.Add(key, new GameContext(sessionId, actionId, userId, timeOut));
            }
            var context = _contextSet[key];

            if (context != null)
            {
                context.UserId     = userId;
                context.ExpireDate = MathUtils.Now;
            }
            return(context);
        }
예제 #15
0
        public void TryGetValue_MRUDicAndKeyPresent_KeyMarkedLastForPurge()
        {
            _cache = new CacheDictionary<int, int>(5, CachePurgeStatergy.MRU);
            FillCache();
            int value;
            Assert.IsTrue(_cache.TryGetValue(0, out value));    //0 moved to top of MRU list
            Assert.AreEqual(0, value);

            _cache.Add(5, 5);
            Assert.IsTrue(_cache.ContainsKey(5));   //newly added key 5 is present
            Assert.IsFalse(_cache.ContainsKey(0));   //0 is not present
        }
예제 #16
0
        public void IndexerSet_MRUDicAndKeyPresent_ValueUpdatedAndMarkedForPurge()
        {
            _cache = new CacheDictionary<int, int>(5, CachePurgeStatergy.MRU);
            FillCache();
            _cache[0] = 100;
            Assert.AreEqual(100, _cache[0]);

            _cache.Add(5, 5);
            Assert.IsTrue(_cache.ContainsKey(5));   //newly added key 5 is present
            Assert.IsFalse(_cache.ContainsKey(0));   //0 is not present
        }
예제 #17
0
        public void IndexerSet_MRUDicAndKeyNotPresent_KVPAddedAndMarkedForPurge()
        {
            _cache = new CacheDictionary<int, int>(5,CachePurgeStatergy.MRU);
            FillCache();
            _cache[5] = 5;
            Assert.AreEqual(5, _cache[5]);

            Assert.IsTrue(_cache.ContainsKey(5));   //newly added key 5 is present
            Assert.IsFalse(_cache.ContainsKey(4));   //0 is not present
            _cache.Add(6,6);
            Assert.IsFalse(_cache.ContainsKey(5));   //key 5 is not present
        }
예제 #18
0
        private ICache <TK, TV> BuildMockForCache <TK, TV>(string cacheName)
        {
            lock (CacheDictionary)
            {
                if (CacheDictionary.TryGetValue(cacheName, out var cache))
                {
                    return((ICache <TK, TV>)cache);
                }
            }

            var mockCache           = new Mock <ICache <TK, TV> >(MockBehavior.Strict);
            var mockCacheDictionary = new Dictionary <TK, TV>();

            mockCache.Setup(x => x.Get(It.IsAny <TK>())).Returns((TK key) =>
            {
                lock (mockCacheDictionary)
                {
                    if (mockCacheDictionary.TryGetValue(key, out var value))
                    {
                        return(value);
                    }
                }

                throw new KeyNotFoundException($"Key {key} not found in mock cache");
            });

            mockCache.Setup(x => x.GetAsync(It.IsAny <TK>())).Returns((TK key) =>
            {
                var task = new Task <TV>(() =>
                {
                    lock (mockCacheDictionary)
                    {
                        if (mockCacheDictionary.TryGetValue(key, out var value))
                        {
                            return(value);
                        }
                    }

                    throw new KeyNotFoundException($"Key {key} not found in mock cache");
                });
                task.Start();

                return(task);
            });

            mockCache.Setup(x => x.Put(It.IsAny <TK>(), It.IsAny <TV>())).Callback((TK key, TV value) =>
            {
                lock (mockCacheDictionary)
                {
                    // Ignite behaviour is writing an existing key updates the value with no error
                    if (mockCacheDictionary.ContainsKey(key))
                    {
                        mockCacheDictionary[key] = value;
                    }
                    else
                    {
                        mockCacheDictionary.Add(key, value);
                    }
                }
            });

            mockCache.Setup(x => x.PutAsync(It.IsAny <TK>(), It.IsAny <TV>())).Returns((TK key, TV value) =>
            {
                var task = new Task(() =>
                {
                    lock (mockCacheDictionary)
                    {
                        // Ignite behaviour is writing an existing key updates the value with no error
                        if (mockCacheDictionary.ContainsKey(key))
                        {
                            mockCacheDictionary[key] = value;
                        }
                        else
                        {
                            mockCacheDictionary.Add(key, value);
                        }
                    }
                });
                task.Start();

                return(task);
            });

            mockCache.Setup(x => x.PutIfAbsent(It.IsAny <TK>(), It.IsAny <TV>())).Returns((TK key, TV value) =>
            {
                lock (mockCacheDictionary)
                {
                    if (!mockCacheDictionary.ContainsKey(key))
                    {
                        mockCacheDictionary.Add(key, value);
                        return(true);
                    }
                }

                return(false);
            });

            mockCache.Setup(x => x.Name).Returns(cacheName);

            mockCache.Setup(x => x.RemoveAll(It.IsAny <IEnumerable <TK> >())).Callback((IEnumerable <TK> keys) =>
            {
                lock (mockCacheDictionary)
                {
                    keys.ForEach(key => mockCacheDictionary.Remove(key));
                }
            });

            mockCache.Setup(x => x.Remove(It.IsAny <TK>())).Returns((TK key) =>
            {
                lock (mockCacheDictionary)
                {
                    if (mockCacheDictionary.ContainsKey(key))
                    {
                        mockCacheDictionary.Remove(key);

                        return(true);
                    }
                }

                return(false);
            });

            mockCache.Setup(x => x.RemoveAsync(It.IsAny <TK>())).Returns((TK key) =>
            {
                var task = new Task <bool>(() =>
                {
                    lock (mockCacheDictionary)
                    {
                        if (mockCacheDictionary.ContainsKey(key))
                        {
                            mockCacheDictionary.Remove(key);

                            return(true);
                        }
                    }

                    return(false);
                });
                task.Start();

                return(task);
            });

            mockCache.Setup(x => x.PutAll(It.IsAny <IEnumerable <KeyValuePair <TK, TV> > >())).Callback((IEnumerable <KeyValuePair <TK, TV> > values) =>
            {
                values.ForEach(value =>
                {
                    lock (mockCacheDictionary)
                    {
                        // Ignite behaviour is writing an existing key updates the value with no error
                        if (mockCacheDictionary.ContainsKey(value.Key))
                        {
                            mockCacheDictionary[value.Key] = value.Value;
                        }
                        else
                        {
                            mockCacheDictionary.Add(value.Key, value.Value);
                        }
                    }
                });
            });

            mockCache
            .Setup(x => x.Query(It.IsAny <ScanQuery <TK, TV> >()))
            .Returns((ScanQuery <TK, TV> query) =>
            {
                // This mock treats the query as an unconstrained query and returns all elements
                if (query == null)
                {
                    return(null);
                }

                lock (mockCacheDictionary)
                {
                    var queryResult = new Mock <IQueryCursor <ICacheEntry <TK, TV> > >();
                    queryResult.Setup(x => x.GetAll()).Returns(() =>
                                                               mockCacheDictionary.Select(x => (ICacheEntry <TK, TV>)(new IgniteMockCacheEntry <TK, TV>(x.Key, x.Value))).ToList());
                    return(queryResult.Object);
                }
            });

            lock (CacheDictionary)
            {
                CacheDictionary.Add(cacheName, mockCache.Object);
            }

            lock (MockedCacheDictionaries)
            {
                MockedCacheDictionaries.Add(cacheName, mockCacheDictionary);
            }

            return(mockCache.Object);
        }
예제 #19
0
        private bool RefreshData(PlayerChessLogic playerChess)
        {
            int         costFieldCount     = 0;
            int         freeFieldCount     = 0;
            int         totalCostFreeCount = 0;
            Transaction t = new Transaction();

            t.DumpEntity(playerChess.MyChess);
            PlayerPackageLogic package = new PlayerPackageLogic();

            package.SetUser(m_UserId);
            foreach (var field in m_RequestPacket.ModifiedChessField)
            {
                var oldField = playerChess.MyChess.ChessBoard[field.Index];
                int oldColor = oldField.Color == ChessFieldColor.Empty || oldField.Color == ChessFieldColor.EmptyGray || oldField.Color == ChessFieldColor.RewardGray ?
                               (int)ChessFieldColor.EmptyGray : (int)oldField.Color;
                if (field.Color != oldColor)
                {
                    t.RollBack();
                    ErrorCode = (int)ErrorType.CannotOpenChance;
                    ErrorInfo = "illegal params";
                    return(false);
                }
                if (field.Color == (int)ChessFieldColor.EmptyGray)
                {
                    RewardChessField oldRewardField = oldField as RewardChessField;
                    if (!oldRewardField.IsOpened && field.IsOpened)
                    {
                        if (!oldRewardField.IsFree)
                        {
                            if (m_RequestPacket.ModifiedChessField.Count == 1)
                            {
                                costFieldCount += 1;
                            }
                            else
                            {
                                freeFieldCount += 1;
                            }
                        }
                        else
                        {
                            freeFieldCount += 1;
                        }
                        m_GotCoin       += oldRewardField.RewardCoin;
                        m_GotMoney      += oldRewardField.RewardMoney;
                        m_GotStarEnergy += oldRewardField.RewardStarEnergy;
                        foreach (var reward in oldRewardField.RewardItems)
                        {
                            if (m_GotItems.ContainsKey(reward.Key))
                            {
                                m_GotItems[reward.Key] += reward.Value;
                            }
                            else
                            {
                                m_GotItems.Add(reward);
                            }
                        }
                        PlayerPackageLogic pp = new PlayerPackageLogic();
                        pp.SetUser(m_UserId);
                        if (!pp.CheckPackageSlot(m_GotItems))
                        {
                            ErrorCode = (int)ErrorType.PackageSlotFull;
                            ErrorInfo = "item count if full";
                            return(false);
                        }
                        playerChess.DeductOpenCount();
                    }
                    oldRewardField.IsFree   = field.IsFree;
                    oldRewardField.IsOpened = field.IsOpened;
                    oldRewardField.ParentId = field.Parent;
                }
                else
                {
                    BattleChessField oldBattleField = oldField as BattleChessField;
                    if (!oldBattleField.IsOpened && field.IsOpened)
                    {
                        m_ResponsePacket.FreeCount = oldBattleField.Count;
                        costFieldCount            += 1;
                        oldBattleField.IsOpened    = field.IsOpened;
                        PlayerDailyQuestLogic.GetInstance(m_UserId).UpdateDailyQuest(DailyQuestType.WinTurnOverChessBattle, 1);
                    }
                    else
                    {
                        if (field.FreeCount < 0 || field.FreeCount > oldBattleField.Count)
                        {
                            ErrorCode = (int)ErrorType.CannotOpenChance;
                            ErrorInfo = "illegal params";
                            return(false);
                        }
                        totalCostFreeCount  += oldBattleField.Count - field.FreeCount;
                        oldBattleField.Count = field.FreeCount;
                    }
                    oldBattleField.ChildrenId.AddRange(field.Children);
                }
            }
            if (freeFieldCount != totalCostFreeCount)
            {
                t.RollBack();
                ErrorCode = (int)ErrorType.CannotOpenChance;
                ErrorInfo = "illegal params";
                return(false);
            }
            if (costFieldCount > 1)
            {
                t.RollBack();
                ErrorCode = (int)ErrorType.CannotOpenChance;
                ErrorInfo = "illegal params";
                return(false);
            }
            playerChess.MyChess.Count -= costFieldCount;
            return(true);
        }