Esempio n. 1
0
        static void Main(string[] args)
        {
            CacheManager <City> citiesCacheManager =
                new CacheManager <City>(new StoreManagerDictinary <long, City>());
            City istanbul = new City()
            {
                Key = 34, Name = "İstanbul"
            };

            City ankara = new City()
            {
                Key = 6, Name = "Ankara"
            };

            citiesCacheManager.Add(istanbul);
            citiesCacheManager.Add(ankara);

            var itemFromCache = citiesCacheManager.Get(34);

            Console.WriteLine(itemFromCache.Name);

            itemFromCache = citiesCacheManager.Get(6);
            Console.WriteLine(itemFromCache.Name);
            Console.Read();
        }
        public void TestAdd()
        {
            CacheManager <string, Tuple <string> > cacheManager = new CacheManager <string, Tuple <string> >();

            string         key1   = "Key 1";
            Tuple <string> value1 = new Tuple <string>("Value 1");

            string         key2   = "Key 2";
            Tuple <string> value2 = new Tuple <string>("Value 2");

            string         key3   = "Key 3";
            Tuple <string> value3 = new Tuple <string>("Value 3");

            string         duplicateKey1   = "Key 1";
            Tuple <string> duplicateValue1 = new Tuple <string>("Value 1");

            cacheManager.Add(key1, value1);
            cacheManager.Add(key2, value2);
            cacheManager.Add(key3, value3);

            cacheManager.Add(duplicateKey1, duplicateValue1);

            Assert.AreEqual(cacheManager.Get(key1), value1);
            Assert.AreEqual(cacheManager.Get(key2), value2);
            Assert.AreEqual(cacheManager.Get(key3), value3);

            Assert.IsNull(cacheManager.Get("Unknown key"));
        }
        /// <summary>
        /// Retrieve an item -in this case, one product, by using an unique object identifier
        /// as key.
        /// </summary>
        /// <param name="anID">Unique identification for an object</param>
        /// <returns>Product object associated to the given ID</returns>
        public Product ReadProductByID(string productID)
        {
            Product product = (Product)cache.GetData(productID);

            // Does our cache already have the requested object?
            if (product == null)
            {
                // Requested object is not cached, so let's retrieve it from
                // data provider and cache it for further requests.
                product = this.dataProvider.GetProductByID(productID);

                if (product != null)
                {
                    cache.Add(productID, product);
                    dataSourceMessage = string.Format(Resources.Culture, Resources.MasterSourceMessage, product.ProductID, product.ProductName, product.ProductPrice) + "\r\n";
                }
                else
                {
                    dataSourceMessage = Resources.ItemNotAvailableMessage + "\r\n";
                }
            }
            else
            {
                dataSourceMessage = string.Format(Resources.Culture, Resources.CacheSourceMessage, product.ProductID, product.ProductName, product.ProductPrice) + "\r\n";
            }
            return(product);
        }
Esempio n. 4
0
 public static void StoreInCache(string key, object data)
 {
     if (null == data)
     {
         manager.Remove(key);
     }
     else
     {
         manager.Add(key, data);
     }
 }
        public IStringLocalizer Create(Type resourceSource)
        {
            CacheItem cacheItem = _cacheManager.Get(_cacheName);

            if (cacheItem == null)
            {
                cacheItem = new CacheItem(_cacheName, new StringLocalizer());
                _cacheManager.Add(_cacheName, cacheItem);
            }

            return((IStringLocalizer)cacheItem.Value);
        }
Esempio n. 6
0
        public void GetBasketThenInsertWithCacheRefresh()
        {
            // Arrange
            const string cacheName = "AccessClient";
            const int    basketId  = 1;
            var          basket    = new ObjectWithAnId {
                Id = basketId
            };
            var checkout = new ObjectWithAnId {
                Id = basketId
            };

            var cacheManager = new CacheManager();
            var cache        = new InMemoryTestCache(cacheName);

            cacheManager.AddCache(cache);

            var cacheKeyBasket   = cacheManager.GetKey("GetBasket", basketId);
            var cacheKeyCheckout = cacheManager.GetKey("GetCheckout", basketId);

            //Act
            if (!cacheManager.HasConfiguration(cacheName))
            {
                Assert.Fail("Should have a cache config file");
            }
            var success = cacheManager.Add(cacheName, cacheKeyBasket, basket);

            Assert.IsTrue(success, "basket should be added.");

            success = cacheManager.Add(cacheName, cacheKeyCheckout, checkout);
            Assert.IsTrue(success, "Checkout should be added.");

            object cached;

            var cacheKeyInsertBasket = cacheManager.GetKey("InsertBasketItem", basket);

            success = cacheManager.TryGet(cacheName, cacheKeyInsertBasket, out cached);
            Assert.IsFalse(success, "Should not be there on that key.");

            var newBasket = new ObjectWithAnId {
                Id = basketId
            };

            success = cacheManager.Add(cacheName, cacheKeyInsertBasket, newBasket);
            Assert.IsTrue(success, "New basket should now be added on original key.");

            cacheManager.TryGet(cacheName, cacheKeyBasket, out cached);
            Assert.AreSame(newBasket, cached, "Now it should be cached.");

            cacheManager.TryGet(cacheName, cacheKeyCheckout, out cached);
            Assert.IsNull(cached, "Checkout should have been flushed");
        }
        public void RemovalOfNonExistingItemDoesNotFireEvents()
        {
            factoryHelper.doExpirations = false;

            using (CacheManager cacheMgr
                       = factoryHelper.BuildCacheManager(instanceName, backingStore, 100, 1, 1, instrumentationProvider))
            {
                cacheMgr.Add(key2, new object(), CacheItemPriority.NotRemovable, new NullCallback(), new NeverExpired());
                cacheMgr.Add(key3, new object(), CacheItemPriority.NotRemovable, new NullCallback(), new NeverExpired());
                instrumentationListener.eventArgs.Clear();

                cacheMgr.Remove(key1);
            }
            Assert.AreEqual(0, instrumentationListener.eventArgs.Count);
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            {
                for (int i = 0; i < 5; i++)
                {
                    List <Program> programs = DBHelper.Query <Program>();
                    if (CacheManager.Contains("DBHelper"))
                    {
                        List <Program> programList = DBHelper.Query <Program>();
                        CacheManager.Add("DBHelper", programList);
                    }
                    List <Program> programResult = CacheManager.GetData <List <Program> >("DBHelper");

                    List <Program> result = CacheManager.Get <List <Program> >("DBHelper",
                                                                               () => DBHelper.Query <Program>(), 30);
                }
                for (int i = 0; i < 5; i++)
                {
                    List <Program> programs = FileHelper.Query <Program>();
                }
                for (int i = 0; i < 5; i++)
                {
                    List <Program> programs = RemoteHelper.Query <Program>();
                }
            }

            Console.ReadKey();
        }
Esempio n. 9
0
        /// <summary>
        /// API用户过期信息缓存
        /// </summary>
        public void SetUserCacheAPI(Sys_User user)
        {
            //生成用户token
            var token = Sys_User.GetKey(user.UserId);

            CacheManager.Add(token, user, 12 * 60);
        }
Esempio n. 10
0
        /// <summary>
        /// Saves the region.
        /// </summary>
        /// <param name="region">The region.</param>
        /// <returns></returns>
        public static int SaveRegion(Region region)
        {
            try
            {
                if (region.IsValid)
                {
                    // Save entity
                    region.Id = DataAccessProvider.Instance().SaveRegion(region);
                    if (region.Id > -1)
                    {
                        CacheManager.Add(region);
                    }
                }
                else
                {
                    // Entity is not valid
                    throw new InValidBusinessObjectException(region);
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }

            // Done
            return(region.Id);
        }
Esempio n. 11
0
        /// <summary>
        /// Gets the regions.
        /// </summary>
        /// <returns></returns>
        public static List <Region> GetRegions()
        {
            List <Region> regions = new List <Region>();

            try
            {
                regions = CBO <Region> .FillCollection(DataAccessProvider.Instance().GetRegions());
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }

            if (regions != null)
            {
                foreach (Region region in regions)
                {
                    CacheManager.Add(region);
                }
            }
            return(regions);
        }
Esempio n. 12
0
        /// <summary>
        /// Gets the region by code.
        /// </summary>
        /// <param name="regionCode">The region code.</param>
        /// <returns></returns>
        public static Region GetRegion(string regionCode)
        {
            Region region = null;

            try
            {
                region = CacheManager.Get <Region>(regionCode);
                if (region == null)
                {
                    region = CBO <Region> .FillObject(DataAccessProvider.Instance().GetRegion(regionCode));

                    if (region != null)
                    {
                        CacheManager.Add(region);
                    }
                }

                return(region);
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }

            return(region);
        }
Esempio n. 13
0
        /// <summary>
        /// Saves the transactionSubType.
        /// </summary>
        /// <param name="transactionSubType">The transactionSubType.</param>
        /// <returns></returns>
        public static int SaveTransactionSubType(TransactionSubType transactionSubType)
        {
            try
            {
                if (transactionSubType.IsValid)
                {
                    // Save entity
                    transactionSubType.Id = DataAccessProvider.Instance().SaveTransactionSubType(transactionSubType);
                    if (transactionSubType.Id != -1)
                    {
                        FrameworkController.GetChecksum(transactionSubType);
                        CacheManager.Add(transactionSubType);
                    }
                }
                else
                {
                    // Entity is not valid
                    throw new InValidBusinessObjectException(transactionSubType);
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }

            // Done
            return(transactionSubType.Id);
        }
Esempio n. 14
0
        /// <summary>
        /// Gets the transactionSubTypes.
        /// </summary>
        /// <returns></returns>
        public static List <TransactionSubType> GetTransactionSubTypes()
        {
            List <TransactionSubType> transactionSubTypes = new List <TransactionSubType>();

            try
            {
                transactionSubTypes =
                    CBO <TransactionSubType> .FillCollection(DataAccessProvider.Instance().GetTransactionSubTypes());

                if (transactionSubTypes != null)
                {
                    foreach (TransactionSubType type in transactionSubTypes)
                    {
                        CacheManager.Add(type);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }
            return(transactionSubTypes);
        }
Esempio n. 15
0
        public void ProvideValidKey_DoesNotAdd(string key)
        {
            var playerMatches = new PlayerMatches();

            CacheManager.Add(playerMatches, key, 1);
            Assert.True(CacheManager.Contains(key));
        }
        public void RefreshQuestions()
        {
            var result    = new List <IQuestion>();
            var jsonFiles = GetJsonFiles();

            var questionNumber = 0;

            foreach (var filePath in jsonFiles)
            {
                var question = Deserialise <Question>(filePath);

                if (question.IsEnabled)
                {
                    if (string.IsNullOrEmpty(question.Description))
                    {
                        question.Description = LoadHtmlFromFile(filePath, question.Id, "Description");
                    }

                    if (string.IsNullOrEmpty(question.MoreInfo))
                    {
                        question.MoreInfo = LoadHtmlFromFile(filePath, question.Id, "MoreInfo");
                    }

                    question.QuestionNumber = ++questionNumber;

                    result.Add(question);
                }
            }

            CacheManager.Add(CacheName, result.Select(q => { q.QuestionCount = result.Count; return(q); }).ToList());
        }
Esempio n. 17
0
        public static IEnumerable <MovieEntity> GetUpcomingMovies(this IStore store)
        {
            IEnumerable <MovieEntity> movies;

            if (!CacheManager.TryGet <IEnumerable <MovieEntity> >(CacheConstants.UpcomingMovieEntities, out movies))
            {
                var retList = store.GetAllMovies();
                movies =
                    retList.Values
                    // Need to update Trailer with new column - State = Released, Upcoming, Production, PreProduction, Script, Planning etc.
                    .Where(movie => movie.State.Trim().ToLower() == "upcoming").OrderBy(m => m.PublishDate);

                CacheManager.Add <IEnumerable <MovieEntity> >(CacheConstants.UpcomingMovieEntities, movies);
            }

            return(movies);

            ////TODO: Clean the comments
            ////List<MovieEntity> upcomingMovies = new List<MovieEntity>();

            ////foreach (var upcomingMovie in retList.Values)
            ////{
            ////    // Need to update Trailer with new column - State = Released, Upcoming, Production, PreProduction, Script, Planning etc.
            ////    if (string.IsNullOrEmpty(upcomingMovie.State) || upcomingMovie.State.ToLower() == "upcoming")
            ////        upcomingMovies.Add(upcomingMovie);
            ////    else
            ////    {
            ////        // Temp = Assuming Month column will be blank for future releases or movies with future release date shall be returned by this block
            ////        // however need to take a call - if we shall rely on date!

            ////    }
            ////}

            ////return upcomingMovies;
        }
Esempio n. 18
0
        public void RemoveTest()
        {
            var cacheManager = new CacheManager();
            var cacheKey     = new CacheKey("AddTest" + DateTime.Now.Ticks);
            var value        = "Test Value " + DateTime.Now;
            var cachePolicy  = new CachePolicy();

            bool result = cacheManager.Add(cacheKey, value, cachePolicy);

            result.Should().BeTrue();

            // look in underlying MemoryCache
            var cachedValue = cacheManager.Get(cacheKey.Key);

            cachedValue.Should().NotBeNull();
            cachedValue.Should().Be(value);

            var removed = cacheManager.Remove(cacheKey);

            removed.Should().NotBeNull();
            removed.Should().Be(value);

            // look in underlying MemoryCache
            var previous = cacheManager.Get(cacheKey.Key);

            previous.Should().BeNull();
        }
Esempio n. 19
0
        private RQItemModel GetModel(RQquery query, bool forEdit)
        {
            RQItemModel rqitemModel = null;

            if (!forEdit && bUseHttpCache)
            {
                rqitemModel = CacheManager.Get <RQItemModel>(query.Id.ToString());
            }
            if (forEdit)
            {
                query.QueryExternal = "";
            }
            if ((rqitemModel == null) || (rqitemModel.IsEditable() != forEdit))
            {
                if (query.QueryBookmarks == false)
                {
                    query.QueryBookmarks = true;
                }
                rqitemModel = new RQItemModel(query, forEdit, this.modelParameters);
                if (!forEdit && bUseHttpCache)
                {
                    CacheManager.Add(query.Id.ToString(), rqitemModel);
                }
            }
            return(rqitemModel);
        }
Esempio n. 20
0
        /// <summary>
        /// Read rules from db
        /// </summary>
        private void GetAuthorizationRules()
        {
            //Read cache to get the rules
            // if cache does not have it, then read from database
            authorizationRules = new Dictionary <string, IAuthorizationRule>();
            string connectionString = authorizationRepositories["default"].Connectionstring;

            // cache the rules
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(
                    "SELECT Name, Expression FROM AuthorizationRule;",
                    connection);
                connection.Open();

                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        authorizationRules.Add(reader.GetString(0), new SqlAuthorizationRule(reader.GetString(0), reader.GetString(1)));
                    }
                }
                reader.Close();
            }

            if (authorizationRules.Count > 0)
            {
                m_CacheManager.Remove(CACHEKEY);
                m_CacheManager.Add(CACHEKEY, authorizationRules);
            }
        }
        public void CacheHitForExpiredItemDoesFireEvents()
        {
            factoryHelper.doExpirations = false;

            using (CacheManager cacheMgr
                       = factoryHelper.BuildCacheManager(instanceName, backingStore, 100, 1, 1, instrumentationProvider))
            {
                cacheMgr.Add(key1, new object(), CacheItemPriority.NotRemovable, new NullCallback(), new AlwaysExpired());
                instrumentationListener.eventArgs.Clear();

                cacheMgr.GetData(key1);
            }

            Assert.AreEqual(3, instrumentationListener.eventArgs.Count);
            IList <CacheAccessedEventArgs> accesses = FilterEventArgs <CacheAccessedEventArgs>(instrumentationListener.eventArgs);
            IList <CacheExpiredEventArgs>  expiries = FilterEventArgs <CacheExpiredEventArgs>(instrumentationListener.eventArgs);
            IList <CacheUpdatedEventArgs>  updates  = FilterEventArgs <CacheUpdatedEventArgs>(instrumentationListener.eventArgs);

            Assert.AreEqual(1, accesses.Count);
            Assert.AreEqual(1, expiries.Count);
            Assert.AreEqual(1, updates.Count);
            Assert.IsFalse(accesses[0].Hit);
            Assert.AreEqual(1L, expiries[0].ItemsExpired);
            Assert.AreEqual(1L, updates[0].UpdatedEntriesCount);
        }
Esempio n. 22
0
 /// <summary>
 /// Adds this route property to the cache.
 /// </summary>
 public void AddToCache()
 {
     if (HasCache)
     {
         CacheManager.Add(this);
     }
 }
Esempio n. 23
0
 private void WorkerMethod()
 {
     int[] keys = GenerateKeyList(700, 1000);
     for (int i = 0; i < 70; i++)
     {
         try
         {
             string randomNumber = keys[i].ToString();
             currentCacheManager.Add(randomNumber, randomNumber);
         }
         catch (SqlException e)
         {
             Console.Write(e);
         }
     }
 }
Esempio n. 24
0
        /// <summary>
        /// Gets the warehouse.
        /// </summary>
        /// <param name="warehouseCode">The warehouse code.</param>
        /// <param name="fullyPopulate">if set to <c>true</c> [fully populate].</param>
        /// <returns></returns>
        public static Warehouse GetWarehouse(string warehouseCode, bool fullyPopulate)
        {
            Warehouse warehouse = null;

            try
            {
                warehouse = CacheManager.Get <Warehouse>(warehouseCode, fullyPopulate);
                if (warehouse == null)
                {
                    warehouse = CBO <Warehouse> .FillObject(
                        DataAccessProvider.Instance().GetWarehouse(warehouseCode),
                        CustomFill,
                        fullyPopulate);

                    if (warehouse != null)
                    {
                        CacheManager.Add(warehouse, fullyPopulate);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }
            return(warehouse);
        }
Esempio n. 25
0
        /// <summary>
        /// Gets the warehouses.
        /// </summary>
        /// <param name="fullyPopualte">if set to <c>true</c> [fully popualte].</param>
        /// <returns></returns>
        public static List <Warehouse> GetWarehouses(bool fullyPopualte)
        {
            List <Warehouse> warehouses = new List <Warehouse>();

            try
            {
                if (fullyPopualte)
                {
                    allRegions = OptrakRegionController.GetRegions();
                }
                warehouses = CBO <Warehouse> .FillCollection(DataAccessProvider.Instance().GetWarehouses(), CustomFill, fullyPopualte);

                allRegions = null;
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }

            if (warehouses != null)
            {
                foreach (Warehouse warehouse in warehouses)
                {
                    CacheManager.Add(warehouse, fullyPopualte);
                }
            }
            return(warehouses);
        }
Esempio n. 26
0
        /// <summary>
        /// Saves the warehouse.
        /// </summary>
        /// <param name="warehouse">The warehouse.</param>
        /// <returns></returns>
        public static int SaveWarehouse(Warehouse warehouse)
        {
            try
            {
                if (warehouse.IsValid)
                {
                    // Save entity
                    warehouse.Id = DataAccessProvider.Instance().SaveWarehouse(warehouse);
                    if (warehouse.Id != -1)
                    {
                        FrameworkController.GetChecksum(warehouse, "Warehouse");
                        CacheManager.Add(warehouse);
                    }
                }
                else
                {
                    // Entity is not valid
                    throw new InValidBusinessObjectException(warehouse);
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "Business Logic"))
                {
                    throw;
                }
            }

            // Done
            return(warehouse.Id);
        }
Esempio n. 27
0
        public void ProvideEmptyKey_DoesNotAdd()
        {
            var playerMatches = new PlayerMatches();

            CacheManager.Add(playerMatches, string.Empty, 1);
            Assert.False(CacheManager.Contains(string.Empty));
        }
Esempio n. 28
0
 /// <summary>
 /// 用户注册验证
 /// </summary>
 public static (bool, int) UserRegisterCheck(ReqUserRegister userRegister)
 {
     try
     {
         var checkEP = userBase.FirstOrDefault(c => c.Phone.Equals(userRegister.Phone));
         if (checkEP != null)
         {
             return(false, 0);
         }
         userRegister.PassWord = userRegister.PassWord.GetMD5FromString();
         userBase.AddEntity(new UserInfo
         {
             UserName   = userRegister.Phone,
             Eamil      = userRegister.Email,
             Password   = userRegister.PassWord,
             Phone      = userRegister.Phone,
             CreateData = DateTime.Now
         });
         var user = userBase.FirstOrDefault(c => c.Phone.Equals(userRegister.Phone) && c.Password.Equals(userRegister.PassWord));
         if (user != null)
         {
             CacheManager.Add(UserInfo.GetKey(user.Id), user);
         }
         return(true, user.Id);
     }
     catch (Exception ex)
     {
         Log.Write(LogLevel.Error, "用户注册出错", ex);
         return(false, 0);
     }
 }
Esempio n. 29
0
        private List <TwitterEntity> GetNowPlayingMovieTweets()
        {
            List <TwitterEntity> twitterList = new List <TwitterEntity>();

            // Find the list of upcoming movies - Get their Twitter Handle
            if (CacheManager.TryGet(CacheConstants.TwitterJson + "NowPlaying", out twitterList))
            {
                return(twitterList);
            }
            else
            {
                if (twitterList == null)
                {
                    twitterList = new List <TwitterEntity>();
                }

                TableManager tbl = new TableManager();
                IEnumerable <MovieEntity> upcomingMovies = tbl.GetCurrentMovies();
                if (upcomingMovies != null)
                {
                    foreach (MovieEntity movie in upcomingMovies)
                    {
                        if (!string.IsNullOrEmpty(movie.TwitterHandle))
                        {
                            // Call GetMovieTweets method
                            List <TwitterEntity> tweets = GetLatestTweets(movie.TwitterHandle);
                            // Add this movie to cache
                            if (tweets != null && tweets.Count > 0)
                            {
                                List <TwitterEntity> movieTweets = new List <TwitterEntity>();
                                if (CacheManager.TryGet(CacheConstants.TwitterJson + movie.UniqueName, out movieTweets))
                                {
                                    CacheManager.Remove(CacheConstants.TwitterJson + movie.UniqueName);
                                }

                                CacheManager.Add(CacheConstants.TwitterJson + movie.UniqueName, tweets);
                            }

                            if (tweets != null && tweets.Count > 5)
                            {
                                // Just keep top 5 tweets
                                tweets.RemoveRange(5, tweets.Count - 5);
                                twitterList.AddRange(tweets);
                            }
                            else if (tweets != null)
                            {
                                twitterList.AddRange(tweets); // Merge the tweet lists into one
                            }
                        }
                    }
                }

                if (twitterList.Count > 0)
                {
                    CacheManager.Add(CacheConstants.TwitterJson + "NowPlaying", twitterList);
                }
            }

            return(twitterList);
        }
Esempio n. 30
0
        public void ExpireGetTest()
        {
            var expiredHandle = new AutoResetEvent(false);
            var cacheManager  = new CacheManager();

            cacheManager.CacheItemExpired += (sender, args) =>
            {
                expiredHandle.Set();
            };

            string key        = "key" + DateTime.Now.Ticks;
            object value      = "value" + DateTime.Now.Ticks;
            var    expiration = TimeSpan.FromMilliseconds(200);

            var cachePolicy = new CachePolicy {
                AbsoluteExpiration = DateTimeOffset.UtcNow.Add(expiration)
            };

            bool isAdded = cacheManager.Add(key, value, cachePolicy);

            isAdded.Should().BeTrue();
            bool contains = cacheManager.Contains(key);

            contains.Should().BeTrue();

            var cachedValue = cacheManager.Get(key);

            cachedValue.Should().NotBeNull();

            expiredHandle.WaitOne(1000);

            cachedValue = cacheManager.Get(key);
            cachedValue.Should().BeNull();
        }
 public void AddKeyNullTest()
 {
   var cacheManager = new CacheManager();
   string key = null;
   object value = "value" + DateTime.Now.Ticks;
   CachePolicy cachePolicy = null;
   bool isAdded = cacheManager.Add(key, value, cachePolicy);
 }
 public void AddTest()
 {
   var cacheManager = new CacheManager(); 
   string key = "key" + DateTime.Now.Ticks;
   object value = "value" + DateTime.Now.Ticks;
   CachePolicy cachePolicy = null; 
   bool isAdded = cacheManager.Add(key, value, cachePolicy);
   Assert.AreEqual(true, isAdded);
   bool doesContain = cacheManager.Contains(key);
   Assert.AreEqual(true, doesContain);
 }
        private void CacheManagerTest(CacheManager mgr)
        {
            string key = "key1";
            string val = "value123";

            Assert.IsNull(mgr.GetData(key));

            mgr.Add(key, val);

            string result = (string)mgr.GetData(key);
            Assert.AreEqual(val, result, "result");
        }
Esempio n. 34
0
 public String GetMyLoveName()
 {
     String myLoveName = String.Empty;
     var cache = new CacheManager();
     myLoveName = cache.Get<String>("MyLoveName");
     if (myLoveName == null)
     {
         //会有多个线程一起等2秒
         Thread.Sleep(2000);
         myLoveName = "谭雄英";
         cache.Add("MyLove", myLoveName);
     }
     return myLoveName;
 }
Esempio n. 35
0
        public void DoReadsWorkCorrectly()
        {
            //            Console.WriteLine("\n\n\n********");
            //            Console.WriteLine("*** DoReadsWorkCorrectly");
            //            Console.WriteLine("********\n\n\n");

            currentCacheManager = CacheFactory.GetCacheManager("InDatabasePerformanceTest");

            for (int i = -100; i < 100; i++)
            {
                currentCacheManager.Add(i.ToString(), i.ToString());
            }

            RunTest(new ThreadStart(ReadRandomWorkerMethod));
        }
        public void CacheManager_TryGet_InCacheReturnTrue_Test()
        {
            //Arrange
            CacheManager cacheManager = new CacheManager();

            CacheKey key = new CacheKey(Guid.NewGuid().ToString());
            CacheItemConfig cacheitem = new CacheItemConfig(key);

            //Act
            object item = new object();
            object expected;
            cacheManager.Add(cacheitem, item);
            bool result = cacheManager.TryGet<object>(cacheitem, out expected);

            //Assert
            Assert.IsTrue(result);
        }
        public void CacheManager_Add_Test()
        {
            //Arrange 
            CacheManager cacheManager = new CacheManager();

            CacheKey key = new CacheKey("fakeKey");
            CacheItemConfig cacheItem = new CacheItemConfig(key);

            //act
            
            cacheManager.Add(cacheItem,new object());

            //assert
            object result;
            Assert.IsTrue(cacheManager.TryGet(cacheItem, out result));
            Assert.IsNotNull(result);

        }
    public void ExpireItemTest()
    {
      var cacheManager = new CacheManager();
      string key = "key" + DateTime.Now.Ticks;
      object value = "value" + DateTime.Now.Ticks;
      TimeSpan expiration = TimeSpan.FromSeconds(2);
      
      var cachePolicy = new CachePolicy { AbsoluteExpiration = DateTimeOffset.Now.Add(expiration) };
      
      bool isAdded = cacheManager.Add(key, value, cachePolicy);
      Assert.AreEqual(true, isAdded);
      bool contains = cacheManager.Contains(key);
      Assert.AreEqual(true, contains);
      
      // waited for exiration timer
      Thread.Sleep(TimeSpan.FromSeconds(22));
      contains = cacheManager.Contains(key);
      Assert.AreEqual(false, contains);
      Assert.AreEqual(0, cacheManager.Count);

      cachePolicy = new CachePolicy { SlidingExpiration = expiration };
      isAdded = cacheManager.Add(key, value, cachePolicy);
      Assert.AreEqual(true, isAdded);
      contains = cacheManager.Contains(key);
      Assert.AreEqual(true, contains);

      // waited for exiration timer
      Thread.Sleep(TimeSpan.FromSeconds(22));
      contains = cacheManager.Contains(key);
      Assert.AreEqual(false, contains);
      Assert.AreEqual(0, cacheManager.Count);

    }
    public void UpdatePolicyTest()
    {
      var cacheManager = new CacheManager();
      string key = "key" + DateTime.Now.Ticks;
      object value = "value" + DateTime.Now.Ticks;
      TimeSpan expiration = TimeSpan.FromSeconds(2);

      DateTimeOffset absoluteExpiration = DateTimeOffset.Now.Add(expiration);

      var cachePolicy = new CachePolicy { AbsoluteExpiration = absoluteExpiration };

      bool isAdded = cacheManager.Add(key, value, cachePolicy);
      Assert.AreEqual(true, isAdded);
      bool contains = cacheManager.Contains(key);
      Assert.AreEqual(true, contains);

      var cacheItem = cacheManager.GetCacheItem(key);
      Assert.IsNotNull(cacheItem);
      Assert.AreEqual(absoluteExpiration, cacheItem.AbsoluteExpiration);

      DateTimeOffset newExpiration = DateTimeOffset.Now.AddMinutes(20);
      var newPolicy = new CachePolicy { AbsoluteExpiration = newExpiration };

      cacheManager.Set(key, value, newPolicy);

      var newItem = cacheManager.GetCacheItem(key);

      Assert.IsNotNull(newItem);
      Assert.AreEqual(newExpiration, newItem.AbsoluteExpiration);


    }
 public void RemoveTest()
 {
   var cacheManager = new CacheManager();
   string key = "key" + DateTime.Now.Ticks;
   object value = "value" + DateTime.Now.Ticks;
   cacheManager.Add(key, value);
   Assert.AreEqual(1, cacheManager.Count);
   var result = cacheManager.Remove(key);
   Assert.AreEqual(value, result);
   Assert.AreEqual(0, cacheManager.Count);
 }