示例#1
0
        public void Do_not_call_add_on_runtime_nor_disk_cache_when_adding_an_object_with_an_empty_key()
        {
            //Arrange

            //Act
            cache.Add(string.Empty, fooResponse);

            //Assert
            runtimeCacheMock.Verify(m => m.Add(It.IsAny <string>(), It.IsAny <Foo>()), Times.Never);
            runtimeCacheMock.Verify(m => m.Add(It.IsAny <string>(), It.IsAny <Foo>()), Times.Never);
        }
示例#2
0
        public static List <RedisEntityInfo> GetMappingProperties(this System.Type type)
        {
            var key  = $"Caching.{type.FullName}";
            var list = CacheService.Get <List <RedisEntityInfo> >(key);

            if (list != null)
            {
                return(list);
            }
            list = new List <RedisEntityInfo>();
            foreach (var propertyInfo in type.GetProperties())
            {
                //if (propertyInfo.PropertyType.Name != "Nullable`1") continue;

                var attr = propertyInfo.GetCustomAttribute <RedisKeyAttribute>();
                if (attr == null)
                {
                    continue;
                }

                var temp = new RedisEntityInfo
                {
                    PropertyInfo = propertyInfo,
                    PropertyName = propertyInfo.Name,
                    GetMethod    = propertyInfo.CreateGetter(),
                    PrimaryKey   = attr.PrimaryKey,
                    PrefixName   = attr.PrefixName
                };
                list.Add(temp);
            }
            CacheService.Add(key, list);
            return(list);
        }
示例#3
0
        public async Task <T?> GetPage <T>(uint id) where T : BasePage
        {
            if (_cacheService.HasPage(id))
            {
                return(_cacheService.Get <T>(id));
            }

            var response = await _diskService.GetBuffer(new ReadRequest(id));

            var page = BasePage.Create <T>(response.BufferSegment);

            if (page != null)
            {
                _cacheService.Add(page);
                return(page);
            }

            return(null);
        }
示例#4
0
        public void Add_AddObjectsOfDifferentTypesToTheCache_AddMethodIsCalled()
        {
            string keyOfString   = "String key";
            string valueOfString = "Some value";

            string keyOfInt   = "Int key";
            int    valueOfInt = 100;

            var expirationTime = new TimeSpan(0, 0, 30);

            var cacheService = new CacheService(_cacheMock.Object);

            cacheService.Add(keyOfString, valueOfString, expirationTime);
            cacheService.Add(keyOfInt, valueOfInt, expirationTime);

            _cacheMock.Verify(cache =>
                              cache.Add(It.Is <string>(s => s == keyOfString), It.Is <string>(o => o == valueOfString), expirationTime));
            _cacheMock.Verify(cache =>
                              cache.Add(It.Is <string>(s => s == keyOfInt), It.Is <int>(o => o == valueOfInt), expirationTime));
        }
 public ActionResult Post([FromBody] JObject data)
 {
     try
     {
         Cache.Add((String)data["id"], (string)data["value"]);
         return(Ok("Success"));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
示例#6
0
        public void Add_KeyAlreadyExists_ThrownInvalidOperationException()
        {
            string   repeatedKey    = "Key is repeated";
            string   value          = "Some value";
            TimeSpan expirationTime = new TimeSpan(1000);

            _cacheMock.Setup(cache => cache.Get(repeatedKey))
            .Returns(new CacheItem("cacheItem", DateTime.UtcNow + new TimeSpan(0, 0, 10)));

            CacheService cacheService = new CacheService(_cacheMock.Object);

            Assert.Throws <InvalidOperationException>(() => cacheService.Add(repeatedKey, value, expirationTime));
        }
示例#7
0
        public void Add_KeyValueAndExpirationTimeAreValid_AddMethodCalled()
        {
            string key            = "Some key";
            string value          = "Some value";
            var    expirationTime = new TimeSpan(0, 0, 30);

            var cacheService = new CacheService(_cacheMock.Object);

            cacheService.Add(key, value, expirationTime);

            _cacheMock.Verify(cache =>
                              cache.Add(It.Is <string>(s => s == key), It.Is <string>(o => o == value), expirationTime));
        }
示例#8
0
        protected override async Task OnInitializedAsync()
        {
            Data = CacheService.Get <AboutData>("AboutData");
            if (Data == null)
            {
                Data = await ViewDataService.GetAboutViewModel().ConfigureAwait(false);

                CacheService.Add("AboutData", Data, Data.MaxAge);
            }

            AboutData        = Data.PageData;
            InterestingLinks = Data.InterestingLinks;
            DotNetLinks      = Data.DotNetLinks;
        }
示例#9
0
        public void TestGetOrCreate()
        {
            CacheService cacheService = new CacheService();

            try
            {
                var person = cacheService.GetOrCreate("int", () =>
                {
                    return(new Person()
                    {
                        Name = "wangrui"
                    });
                });
                cacheService.Add("add", person, TimeSpan.Zero, TimeSpan.FromDays(1));
                cacheService.Add("add2", person, TimeSpan.FromDays(1), TimeSpan.MaxValue);
                var a = cacheService.Get("add");
                var b = cacheService.Get("add2");
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#10
0
        protected override async Task OnInitializedAsync()
        {
            Data = CacheService.Get <DocumentListData>("Documents");
            if (Data == null)
            {
                Data = await ViewDataService.GetDocumentsViewModel().ConfigureAwait(false);

                CacheService.Add("Documents", Data, Data.MaxAge);
            }

            Documents        = Data.Documents;
            InterestingLinks = Data.InterestingLinks;
            DotNetLinks      = Data.DotNetLinks;
        }
示例#11
0
        protected override async Task OnInitializedAsync()
        {
            Data = CacheService.Get <IndexData>("IndexData");
            if (Data == null)
            {
                Data = await ViewDataService.GetIndexViewModel().ConfigureAwait(false);

                CacheService.Add("IndexData", Data, Data.MaxAge);
                LoadingMessage = "Loading";
            }

            HeroData   = Data.PageData;
            SkillsData = Data.SkillsData;
            MainTitle  = "Richard Hernandez";
        }
示例#12
0
        public void TestReadWriteNoMapCache()
        {
            var logger = LogManager.GetCurrentClassLogger();
            var cache  = new CacheService(logger, "TEST_CACHE", false);
            var key    = "THE_KEY";
            var value  = "THE_VALUE";

            cache.Add(key, value);

            // key should be present
            Assert.IsTrue(cache.ContainsKey(key));

            // should be able to get the value
            Assert.AreEqual(value, cache.GetValue(key));
        }
        static void Main(string[] args)
        {
            while (true)
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                var user = new User();
                for (int i = 0; i < 100000; i++)
                {
                    var type = user.GetType();
                    //foreach (var propertyInfo in type.GetProperties())
                    //{

                    //    propertyInfo.SetValue(user, Convert.ChangeType("123", propertyInfo.PropertyType));
                    //    propertyInfo.GetValue(user);
                    //}

                    var pros = CacheService.Get <List <PropertyEntity> >(type.FullName);
                    if (pros == null)
                    {
                        pros = new List <PropertyEntity>();
                        foreach (var propertyInfo in type.GetProperties())
                        {
                            pros.Add(new PropertyEntity
                            {
                                PropertyInfo = propertyInfo,
                                HasAttr      = propertyInfo.IsDefined(typeof(MyAttr)),
                                PropertyType = propertyInfo.PropertyType,
                                SetMethod    = propertyInfo.CreateSetter(),
                                GetMethod    = propertyInfo.CreateGetter()
                            });
                        }
                        CacheService.Add(type.FullName, pros);
                    }

                    foreach (var pro in pros)
                    {
                        pro.Set(user, "123");
                        pro.Get(user);
                        //pro.PropertyInfo.SetValue(user, Convert.ChangeType("123", pro.PropertyType));
                        //pro.PropertyInfo.GetValue(user);
                    }
                }
                watch.Stop();
                Console.WriteLine(watch.Elapsed.TotalMilliseconds);
                Console.ReadKey();
            }
        }
        public virtual async Task <TModel> GetOneAsync(Guid id)
        {
            var cacheKey = BuildCacheKey(nameof(GetOneAsync), id);

            var result = CacheService.Get <TModel>(cacheKey);

            if (result != null)
            {
                return(result);
            }

            result = await GetCollection().Find(x => x.Id == id).FirstOrDefaultAsync();

            CacheService.Add(cacheKey, result);
            return(result);
        }
示例#15
0
        public void Add_KeyIsTheSameAsTheKeyOfTheExpiredObject_ChangeValueCalled()
        {
            string key            = "Some key";
            string value          = "Some value";
            var    expirationTime = new TimeSpan(0, 0, 10);

            _cacheMock.Setup(cache => cache.Get(key))
            .Returns(new CacheItem(value, DateTime.UtcNow + new TimeSpan(0, 0, 1)));

            CacheService cacheService = new CacheService(_cacheMock.Object);

            Thread.Sleep(2000);

            cacheService.Add(key, value, expirationTime);
            _cacheMock.Verify(cache => cache.ChangeValue(It.Is <string>(s => s == key), It.Is <string>(s => s == value), It.IsAny <TimeSpan>()));
        }
示例#16
0
        public static UserEntity Get(int id)
        {
            string     key    = CNC.ACCOUNT_ENTITY_ID + id;
            UserEntity entity = CacheService.Get(key) as UserEntity;

            if (entity == null)
            {
                entity = UserData.Get(id);
                if (entity != null)
                {
                    CacheService.Add(key, entity);
                }
            }

            return(entity);
        }
示例#17
0
        protected override async Task OnInitializedAsync()
        {
            Sent = false;
            var Data = CacheService.Get <AboutData>("AboutData");

            if (Data == null)
            {
                Data = await ViewDataService.GetAboutViewModel().ConfigureAwait(false);

                CacheService.Add("AboutData", Data, Data.MaxAge);
            }

            InterestingLinks = Data.InterestingLinks;
            DotNetLinks      = Data.DotNetLinks;
            StatusMessage    = Data.ContactStatus;
            ButtonIsDisabled = Data.ContactStatus != null;
        }
        public virtual async Task <TModel> SaveAsync(TModel item)
        {
            if (item.Id != Guid.Empty)
            {
                item.UpdatedDate = DateTime.UtcNow;
            }

            if (HasValidUser())
            {
                item.OwnerUserId = CurrentContext.CurrentUserId;
            }

            var errors = await ValidateObject(item);

            if (errors.Any())
            {
                throw new ValidationException("A validation error has occured saving item of type '" + item.GetType(),
                                              errors);
            }

            if (item.Id == Guid.Empty)
            {
                item.Id = Guid.NewGuid();
                await GetCollection().InsertOneAsync(item);
            }
            else
            {
                var filter = Builders <TModel> .Filter.Eq("_id", item.Id);
                await GetCollection().ReplaceOneAsync(filter, item, new UpdateOptions {
                    IsUpsert = true
                });
            }

            Logger.LogInformation("Entity Saved to {CollectionName}: \'{Id}\' - {@item}",
                                  CollectionName,
                                  item.Id, item);

            //make sure we update the cache...
            var cacheKey = BuildCacheKey(nameof(GetOneAsync), item.Id);

            CacheService.Add(cacheKey, item);

            return(item);
        }
示例#19
0
        private QuerySource GetResult(QueryTerm queryTerm)
        {
            const int PageSize = 15;
            var       model    = new QuerySource();
            var       query    = new List <LinkItem>();
            int       totalHits;
            Dictionary <string, string> cacheDic = CreateSearchDic("ResultList", queryTerm);
            Dictionary <string, string> countDic = CreateSearchDic("ResultCount", queryTerm);

            if (string.IsNullOrWhiteSpace(queryTerm.Dq))
            {
                if (string.IsNullOrWhiteSpace(queryTerm.Query) &&
                    CacheService.Exists(cacheDic) &&
                    CacheService.Exists(countDic))
                {
                    query     = CacheService.Get <List <LinkItem> >(cacheDic);
                    totalHits = CacheService.GetInt32Value(countDic);
                }
                else
                {
                    var searchFilter = GetSearchFilter(queryTerm.Query, queryTerm.Order, queryTerm.Descending, queryTerm.Page, PageSize);
                    query = OutDoorLuceneService.Search(queryTerm, searchFilter, out totalHits);
                    //query = OutDoorLuceneService.Search(out totalHits);

                    if (string.IsNullOrWhiteSpace(queryTerm.Query))
                    {
                        CacheService.Add <List <LinkItem> >(query, cacheDic, 10);
                        CacheService.AddInt32Value(totalHits, countDic, 10);
                    }
                }
            }
            else
            {
                var searchFilter = GetSearchFilter(queryTerm.Query, queryTerm.Order, queryTerm.Descending, queryTerm.Page, PageSize);
                query = OutDoorLuceneService.Search(queryTerm, searchFilter, out totalHits);
            }
            model.Items       = query;
            model.TotalCount  = totalHits;
            model.CurrentPage = queryTerm.Page;
            model.PageSize    = PageSize;
            model.Querywords  = string.IsNullOrEmpty(queryTerm.Query) ? "" : queryTerm.Query;
            return(model);
        }
示例#20
0
        public void TestPersistCache()
        {
            var logger = LogManager.GetCurrentClassLogger();
            var cache  = new CacheService(logger, "TEST_CACHE", true);
            var key    = "THE_KEY";
            var value  = "THE_VALUE";

            cache.Add(key, value);

            cache.WriteCacheEntries();

            // load the cache again...should read it from the file
            cache = new CacheService(logger, "TEST_CACHE", true);
            Assert.AreEqual(value, cache.GetValue(key));

            // delete the cache file
            cache.DeleteCacheFile();

            //load it again and ensure it is empty
            cache = new CacheService(logger, "TEST_CACHE", true);
            Assert.IsFalse(cache.ContainsKey(key));
        }
        public virtual async Task <List <TModel> > GetAllAsync(bool onlyActive = true)
        {
            var cacheKey = BuildCacheKey(nameof(GetAllAsync), onlyActive);

            var results = CacheService.Get <List <TModel> >(cacheKey);

            if (results != null)
            {
                return(results);
            }

            if (onlyActive)
            {
                results = await GetCollection().Find(x => x.IsActive).ToListAsync();
            }
            else
            {
                results = await GetCollection().Find(x => x.IsActive).ToListAsync();
            }

            CacheService.Add(cacheKey, results);
            return(results);
        }
示例#22
0
        public static bool Reserve(string word)
        {
            if (word.Length < 3)
            {
                return(true);
            }
            HashSet <string> h = null;

            if (CacheService.Contains("RESERVE_KEYWORD"))
            {
                h = CacheService.Get(RESERVE_KEYWORD) as HashSet <string>;
            }
            else
            {
                h = KeywordData.GetReserve(); CacheService.Add(RESERVE_KEYWORD, h);
            }

            if (h != null)
            {
                return(h.Contains(word));
            }
            return(false);
        }
示例#23
0
        /// <summary>
        ///  用户登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static bool Login(string name, string pwd)
        {
            UserEntity entity = null;

            pwd = MU.MD5(pwd);
            try
            {
                if (name.Contains("@"))
                {
                    entity = UserData.LoginByEmail(name, pwd);
                }
                else
                {
                    entity = UserData.LoginByName(name, pwd);
                }

                //write cookie
                if (entity != null)
                {
                    CacheService.Add(CNC.ACCOUNT_ENTITY_ID + entity.id, entity);
                    string id = entity.id.ToString(); // id 仅作内部使用,不对外公开
                    QA.SetCookie(FormsAuthentication.FormsCookieName,
                                 FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1, id, DateTime.Now, DateTime.MaxValue, true, id, FormsAuthentication.FormsCookiePath))
                                 , DateTime.MaxValue); //设置永久保留登录信息,之后版本可考虑进行配置

                    QA.SetCookie(SC.CN.A_NAME, HttpUtility.UrlEncode(entity.name), DateTime.MaxValue);
                    string cookie = QA.GetCookie(SC.CN.FROM);

                    //TODO: write log,add to task.
                    Log.Login(entity);
                }
            }
            catch { }

            return(entity != null);
        }
示例#24
0
        private List <LinkGroup> GetSearch(QueryTerm queryTerm)
        {
            List <LinkGroup> result = new List <LinkGroup>();

            Dictionary <string, string> cacheDic = new Dictionary <string, string>();

            cacheDic.Add(CacheService.ServiceName, "ListController");
            cacheDic.Add(CacheService.ServiceMethod, "GetSearch");
            cacheDic.Add("City", queryTerm.City.ToString());
            cacheDic.Add("MediaCode", queryTerm.MediaCode.ToString());
            cacheDic.Add("FormatCode", queryTerm.FormatCode.ToString());
            cacheDic.Add("OwnerCode", queryTerm.OwnerCode.ToString());
            cacheDic.Add("PeriodCode", queryTerm.PeriodCode.ToString());
            if (CacheService.Exists(cacheDic))
            {
                result = CacheService.Get <List <LinkGroup> >(cacheDic);
                return(result);
            }


            #region CityGroup
            if (queryTerm.City != 0)
            {
                var city          = CityCateService.Find(queryTerm.City);
                var prevCityGroup = new List <LinkGroup>();
                GetPrevCityGroup(prevCityGroup, city, queryTerm);
                prevCityGroup.Reverse();
                result.AddRange(prevCityGroup);
                GetNextCityGroup(result, city, queryTerm);
            }
            else
            {
                var city = CityCateService.Find(queryTerm.Province);
                GetNextCityGroup(result, city, queryTerm);
            }
            #endregion

            #region MediaCode
            if (queryTerm.MediaCode != 0)
            {
                var media          = MediaCateService.Find(queryTerm.MediaCode);
                var prevMediaGroup = new List <LinkGroup>();
                GetPrevMediaGroup(prevMediaGroup, media, queryTerm);
                prevMediaGroup.Reverse();
                result.AddRange(prevMediaGroup);
                GetNextMediaGroup(result, media, queryTerm, false);
            }
            else
            {
                GetNextMediaGroup(result, null, queryTerm, true);
            }
            #endregion

            #region FormatCode
            LinkGroup formatGroup = new LinkGroup()
            {
                Group = new LinkItem()
                {
                    Name = "媒体形式",
                    Url  = Url.Action("index", new
                    {
                        province   = queryTerm.Province,
                        city       = queryTerm.City,
                        mediacode  = queryTerm.MediaCode,
                        formatcode = 0,
                        ownercode  = queryTerm.OwnerCode,
                        periodcode = queryTerm.PeriodCode,
                        authstatus = queryTerm.AuthStatus,
                        deadline   = queryTerm.DeadLine,
                        price      = queryTerm.Price,
                        order      = queryTerm.Order,
                        descending = queryTerm.Descending,
                        page       = 1
                    })
                }
            };
            formatGroup.Items = FormatCateService.GetALL().Where(x => x.PID.Equals(null)).ToList().Select(x => new LinkItem()
            {
                ID   = x.ID,
                Name = x.CateName,
                Url  = Url.Action("index", new
                {
                    province   = queryTerm.Province,
                    city       = queryTerm.City,
                    mediacode  = queryTerm.MediaCode,
                    formatcode = x.ID,
                    ownercode  = queryTerm.OwnerCode,
                    periodcode = queryTerm.PeriodCode,
                    authstatus = queryTerm.AuthStatus,
                    deadline   = queryTerm.DeadLine,
                    price      = queryTerm.Price,
                    order      = queryTerm.Order,
                    descending = queryTerm.Descending,
                    page       = 1
                }),
                Selected = queryTerm.FormatCode == x.ID
            }).ToList();

            result.Add(formatGroup);

            #endregion

            #region OwnerCode
            //LinkGroup ownerGroup = new LinkGroup()
            //{
            //    Group = new LinkItem()
            //    {
            //        Name = "代理类型",
            //        Url = Url.Action("index", new
            //        {
            //            province = queryTerm.Province,
            //            city = queryTerm.City,
            //            mediacode = queryTerm.MediaCode,
            //            formatcode = queryTerm.FormatCode,
            //            ownercode = 0,
            //            periodcode = queryTerm.PeriodCode,
            //            authstatus = queryTerm.AuthStatus,
            //            deadline = queryTerm.DeadLine,
            //            price = queryTerm.Price,
            //            order = queryTerm.Order,
            //            descending = queryTerm.Descending,
            //            page = 1
            //        })
            //    }
            //};
            //ownerGroup.Items = OwnerCateService.GetALL().Where(x => x.PID.Equals(null)).ToList().Select(x => new LinkItem()
            //{
            //    ID = x.ID,
            //    Name = x.CateName,
            //    Url = Url.Action("index", new
            //    {
            //        province = queryTerm.Province,
            //        city = queryTerm.City,
            //        mediacode = queryTerm.MediaCode,
            //        formatcode = queryTerm.FormatCode,
            //        ownercode = x.ID,
            //        periodcode = queryTerm.PeriodCode,
            //        authstatus = queryTerm.AuthStatus,
            //        deadline = queryTerm.DeadLine,
            //        price = queryTerm.Price,
            //        order = queryTerm.Order,
            //        descending = queryTerm.Descending,
            //        page = 1

            //    }),
            //    Selected = queryTerm.OwnerCode == x.ID

            //}).ToList();

            //result.Add(ownerGroup);

            #endregion

            #region PeriodCode
            //LinkGroup periodGroup = new LinkGroup()
            //{
            //    Group = new LinkItem()
            //    {
            //        Name = "最短投放周期",
            //        Url = Url.Action("index", new
            //        {
            //            province = queryTerm.Province,
            //            city = queryTerm.City,
            //            mediacode = queryTerm.MediaCode,
            //            formatcode = queryTerm.FormatCode,
            //            ownercode = queryTerm.OwnerCode,
            //            authstatus = queryTerm.AuthStatus,
            //            deadline = queryTerm.DeadLine,
            //            price = queryTerm.Price,
            //            order = queryTerm.Order,
            //            descending = queryTerm.Descending,
            //            page = 1
            //        })
            //    }
            //};
            //periodGroup.Items = PeriodCateService.GetALL().Where(x => x.PID.Equals(null)).ToList().Select(x => new LinkItem()
            //{
            //    ID = x.ID,
            //    Name = x.CateName,
            //    Url = Url.Action("index", new
            //    {
            //        province = queryTerm.Province,
            //        city = queryTerm.City,
            //        mediacode = queryTerm.MediaCode,
            //        formatcode = queryTerm.FormatCode,
            //        ownercode = queryTerm.OwnerCode,
            //        periodcode = x.ID,
            //        authstatus = queryTerm.AuthStatus,
            //        deadline = queryTerm.DeadLine,
            //        price = queryTerm.Price,
            //        order = queryTerm.Order,
            //        descending = queryTerm.Descending,
            //        page = 1

            //    }),
            //    Selected = queryTerm.PeriodCode == x.ID

            //}).ToList();

            //result.Add(periodGroup);

            #endregion

            CacheService.Add <List <LinkGroup> >(result, cacheDic, 180);
            return(result);
        }