/// <summary>
        /// Adds an object into cache based on the parameters provided.
        /// </summary>
        /// <param name="tag">The tag.</param>
        /// <param name="name">The name.</param>
        /// <param name="itemPolicy">The itemPolicy object.</param>
        /// <param name="value">The value to store in cache.</param>
        /// <param name="dispatch">The dispatch.</param>
        /// <returns></returns>
        public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
        {
            if (itemPolicy == null)
            {
                throw new ArgumentNullException("itemPolicy");
            }
            var updateCallback = itemPolicy.UpdateCallback;

            if (updateCallback != null)
            {
                updateCallback(name, value);
            }
            string regionName;

            Settings.TryGetRegion(ref name, out regionName);
            //
            Cache.Set(name, value, GetCacheDependency(tag, itemPolicy, dispatch), regionName);
            var registration = dispatch.Registration;

            if (registration != null && registration.UseHeaders)
            {
                var headerPolicy = new SystemCaching.CacheItemPolicy();
                headerPolicy.ChangeMonitors.Add(Cache.CreateCacheEntryChangeMonitor(new[] { name }, regionName));
                var header = dispatch.Header;
                header.Item = name;
                Cache.Set(name + "#", header, headerPolicy, regionName);
            }
            return(value);
        }
Exemplo n.º 2
0
        private void PrimeCache()
        {
            lock (_cache)
            {
                var policy = new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable };

                TexasHoldemOdds[] oddsList;

                using (var cacheFile = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PokerOdds.Web.OWIN.Cache.PrimeCache.json")))
                {
                    oddsList = JsonConvert.DeserializeObject<TexasHoldemOdds[]>(cacheFile.ReadToEnd());
                }

                foreach (var odds in oddsList)
                {
                    var keys = new string[0];

                    try
                    {
                        keys = _cache.GetKeys();
                    }
                    catch { }

                    if (!keys.Contains(odds.GetCacheKey()))
                    {
                        _cache.Add(odds.GetCacheKey(), odds, policy);
                    }
                }
            }
        }
        public async Task<IAnime> GetAnime(int id)
        {
            IAnime finalItem = null;
            var item = _animeCahce.Get(id.ToString());
            if (item == null)
            {
                Console.WriteLine($"{DateTime.Now} - [Cache] Cache miss [{id}]");

                var anime = await _animeRetriever.GetAnime(id);
                finalItem = anime;
                var cip = new CacheItemPolicy
                {
                    AbsoluteExpiration = DateTime.Now.AddHours(1),
                    RemovedCallback = RemovedCallback
                };
                lock (AnimePadlock.GetOrAdd(id.ToString(), new object()))
                {
                    item = _animeCahce.Get(id.ToString());
                    if (item == null)
                    {
                        _animeCahce.Add(id.ToString(), finalItem, cip);
                        Console.WriteLine($"{DateTime.Now} [Cache] Added to cache [{id}]");
                    }
                }
            }
            else
            {
                Console.WriteLine($"{DateTime.Now} - [Cache] Cache hit [{id}]");
                finalItem = (IAnime) item;
            }
            return finalItem;
        }
        public void Set(string key, object data, string filePath)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { filePath }));

            Cache.Add(new CacheItem(key, data), policy);
        }
Exemplo n.º 5
0
        public override void Set(string key, object value, TimeSpan? slidingExpireTime = null, TimeSpan? absoluteExpireTime = null)
        {
            if (value == null)
            {
                throw new AbpException("Can not insert null values to the cache!");
            }

            var cachePolicy = new CacheItemPolicy();

            if (absoluteExpireTime != null)
            {
                cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.Add(absoluteExpireTime.Value);
            }
            else if (slidingExpireTime != null)
            {
                cachePolicy.SlidingExpiration = slidingExpireTime.Value;
            }
            else if(DefaultAbsoluteExpireTime != null)
            {
                cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.Add(DefaultAbsoluteExpireTime.Value);
            }
            else
            {
                cachePolicy.SlidingExpiration = DefaultSlidingExpireTime;
            }

            _memoryCache.Set(key, value, cachePolicy);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        public void Add(string key, object obj)
        {
            var cacheItem = new CacheItem(GeneralKey(key), obj);

            var cacheItemPolicy = new CacheItemPolicy();
            cache.Add(cacheItem, cacheItemPolicy);
        }
        public void Add(TenantInstance instance, Action<string, TenantInstance> removedCallback)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            if (removedCallback == null)
            {
                removedCallback = delegate { };
            }

            // Add a cache entry for the instance id that will be used as a cache dependency
            // for the running instances
            var cacheDependencyPolicy = new CacheItemPolicy
            {
                // Make the "MaxAge" configurable - when the dependency is removed so are the instances
                AbsoluteExpiration = DateTimeOffset.UtcNow.AddHours(12)
            };

            var cacheDependency = new CacheItem(instance.Id.ToString(), instance.Id);

            // We need to add the dependency before we set up the instance change monitors,
            // otherwise they'll be removed from the cache immediately!
            cache.Set(instance.Id.ToString(), instance.Id, cacheDependencyPolicy);

            // Now cache the running instance for each identifier
            // The policies must be unique since the RemovedCallback can only be called once-per-policy
            foreach (var id in instance.Tenant.RequestIdentifiers)
            {
                cache.Set(new CacheItem(id, instance), GetCacheItemPolicy(removedCallback, cacheDependency));
            }
        }
Exemplo n.º 8
0
        protected override void Save(string key, object value, CacheItemPolicy policy)
        {
            try
            {
                var expiration = policy.SlidingExpiration;

                if (policy.SlidingExpiration == TimeSpan.MinValue)
                {
                    expiration = _default_duration;
                }

                var cache = GetCache();

                if (Exists(key))
                {
                    _cache.Put(key, value, expiration);
                }
                else
                {
                    cache.Add(key, value, expiration);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("Caching error; Message {0}  Trace {1}", ex.Message, ex.StackTrace));
            }
        }
Exemplo n.º 9
0
        public void SqlQuerySingleEntityFactoryCache()
        {
            var session = new DataSession("Tracker").Log(Console.WriteLine);
            session.Should().NotBeNull();

            string email = "*****@*****.**";
            string sql = "select * from [User] where EmailAddress = @EmailAddress";

            var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(5) };

            var user = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .UseCache(policy)
                .QuerySingle<User>();

            user.Should().NotBeNull();
            user.EmailAddress.Should().Be(email);

            var cachedUser = session.Sql(sql)
                .Parameter("@EmailAddress", email)
                .UseCache(policy)
                .QuerySingle<User>();

            cachedUser.Should().NotBeNull();
            cachedUser.EmailAddress.Should().Be(email);

        }
Exemplo n.º 10
0
        public static string GetConfig(string key)
        {
            string output = string.Empty;

            ObjectCache cache = MemoryCache.Default;
            Dictionary<string, string> textConfigs = cache[CACHE_KEY] as Dictionary<string, string>;

            if (textConfigs == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();

                List<string> filePaths = new List<string>();
                filePaths.Add(fileName);

                policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));

                textConfigs = File
                .ReadAllLines(fileName)
                .Select(x => x.Split('\t'))
                .Where(x => x.Length > 1)
                .ToDictionary(x => x[0].Trim(), x => x[(int)appEnv]);

                cache.Set(CACHE_KEY, textConfigs, policy);
            }

            output = textConfigs[key];

            return output;
        }
Exemplo n.º 11
0
 private static bool IsPolicyValid(CacheItemPolicy policy) {
     if (policy == null) {
         return false;
     }
     // see if any change monitors have changed
     bool hasChanged = false;
     Collection<ChangeMonitor> changeMonitors = policy.ChangeMonitors;
     if (changeMonitors != null) {
         foreach (ChangeMonitor monitor in changeMonitors) {
             if (monitor != null && monitor.HasChanged) {
                 hasChanged = true;
                 break;
             }
         }
     }
     // if the monitors haven't changed yet and we have an update callback
     // then the policy is valid
     if (!hasChanged && policy.UpdateCallback != null) {
         return true;
     }
     // if the monitors have changed we need to dispose them
     if (hasChanged) {
         foreach (ChangeMonitor monitor in changeMonitors) {
             if (monitor != null) {
                 monitor.Dispose();
             }
         }
     }
     return false;
 }
Exemplo n.º 12
0
		public void CachedLifetimeReturnsDifferentInstanceIfCacheExpired()
		{
			using (var container = new IocContainer())
			{
				var policy = new CacheItemPolicy()
				{
					SlidingExpiration = new TimeSpan(0, 0, 1)
				};

				container.Register<IFoo>(c => new Foo1()).WithCachedLifetime(policy);

				var result1 = container.Resolve<IFoo>();
				var result2 = container.Resolve<IFoo>();

				Thread.Sleep(1500);

				var result3 = container.Resolve<IFoo>();

				// Assert
				Assert.IsNotNull(result1);
				Assert.IsNotNull(result2);
				Assert.IsNotNull(result3);

				Assert.AreSame(result1, result2);
				Assert.AreNotSame(result1, result3);
			}
		}
Exemplo n.º 13
0
 public void Agregar(string key, object valor)
 {
     Condicion.ValidarParametro(key).IsNotNullOrWhiteSpace("La llave no puede ser nula o vacia.");
     Condicion.ValidarParametro(valor).IsNotNull("El valor no puede ser nulo.");
     var politica = new CacheItemPolicy();
     _objectCache.Add(key, valor, politica);
 }
Exemplo n.º 14
0
        public IEnumerable<INamedColourDetail> GetNamedColourDetails()
        {
            ObjectCache cache = MemoryCache.Default;
            List<NamedColourDetail> namedColours =  cache["NamedColourDetailList"] as List<NamedColourDetail>;
            if ( namedColours == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = new DateTimeOffset(DateTime.UtcNow.AddMinutes(20)); // TODO read cache timeout from config

                string namedColourFileName = "NamedColours.json";

                if (!File.Exists(namedColourFileName))
                {
                    throw new ApplicationException("missing named colours file " + namedColourFileName);
                }

                string namedColoursJSON = File.ReadAllText(namedColourFileName);

                namedColours = JsonConvert.DeserializeObject<List<NamedColourDetail>>(namedColoursJSON);

                cache.Set("NamedColourDetailList", namedColours, policy);
            }

            return namedColours;
        }
        public static bool IsInMaintenanceMode()
        {
            bool inMaintenanceMode;
            string connStr = "Data Source=KIM-MSI\\KIMSSQLSERVER;Initial Catalog=MVWDataBase;User ID=sa;Password=mis123;MultipleActiveResultSets=True";
            if (MemoryCache.Default["MaintenanceMode"] == null)
            {
                Console.WriteLine("Hitting the database...");
                CacheItemPolicy policy = new CacheItemPolicy();
                SqlDependency.Start(connStr);
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    using (SqlCommand command = new SqlCommand("Select MaintenanceMode From dbo.MaintenanceMode", conn))
                    {
                        command.Notification = null;
                        SqlDependency dep = new SqlDependency();
                        dep.AddCommandDependency(command);
                        conn.Open();
                        inMaintenanceMode = (bool)command.ExecuteScalar();
                        SqlChangeMonitor monitor = new SqlChangeMonitor(dep);
                        policy.ChangeMonitors.Add(monitor);
                        dep.OnChange += Dep_OnChange;
                    }
                }

                MemoryCache.Default.Add("MaintenanceMode", inMaintenanceMode, policy);
            }
            else
            {
                inMaintenanceMode = (bool)MemoryCache.Default.Get("MaintenanceMode");
            }

            return inMaintenanceMode;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds an item to the cache.
        /// </summary>
        /// <param name="key">
        /// A unique identifier for the cache entry.
        /// </param>
        /// <param name="value">
        /// The object to insert.
        /// </param>
        /// <param name="policy">
        /// Optional. An <see cref="T:System.Runtime.Caching.CacheItemPolicy"/> object that contains eviction details for the cache entry. This object
        /// provides more options for eviction than a simple absolute expiration. The default value for the optional parameter
        /// is null.
        /// </param>
        /// <param name="regionName">
        /// Optional. A named region in the cache to which the cache entry can be added,
        /// if regions are implemented. The default value for the optional parameter
        /// is null.
        /// </param>
        /// <returns>
        /// True if the insertion try succeeds, or false if there is an already an entry
        ///  in the cache with the same key as key.
        /// </returns>
        public static bool AddItem(string key, object value, CacheItemPolicy policy = null, string regionName = null)
        {
            bool isAdded;
            using (new WriteLock(Locker))
            {
                if (policy == null)
                {
                    // Create a new cache policy with the default values
                    policy = new CacheItemPolicy();
                }

                try
                {
                    Cache.Set(key, value, policy, regionName);
                    isAdded = true;
                }
                catch
                {
                    isAdded = false;
                }

                if (isAdded)
                {
                    CacheItems[key] = regionName;
                }
            }

            return isAdded;
        }
        public void Set(string key, object data, int cacheTime)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);

            Cache.Add(new CacheItem(key, data), policy);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Insert or update a cache value with an expiry date
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiresAt"></param>
        protected override void SetInternal(string key, object value, DateTime expiresAt)
        {
            var policy = new sys.CacheItemPolicy();

            policy.AbsoluteExpiration = expiresAt;
            Set(key, value, policy);
        }
Exemplo n.º 19
0
        public static void Set(string key, object value, int minutesToCache = 20, bool slidingExpiration = true)
        {
            if (minutesToCache <= 0)
            {
                throw new ArgumentOutOfRangeException("minutesToCache",
                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));
            }
            else if (slidingExpiration && (minutesToCache > 365 * 24 * 60))
            {
                // For sliding expiration policies, MemoryCache has a time limit of 365 days. 
                throw new ArgumentOutOfRangeException("minutesToCache",
                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_LessThanOrEqualTo, 365 * 24 * 60));
            }

            CacheItemPolicy policy = new CacheItemPolicy();
            TimeSpan expireTime = new TimeSpan(0, minutesToCache, 0);

            if (slidingExpiration)
            {
                policy.SlidingExpiration = expireTime;
            }
            else
            {
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesToCache);
            }

            MemoryCache.Default.Set(key, value, policy);
        }
        public static void AddServerToCache(string server, ServerInfo si, CacheItemPolicy cip)
        {
            if (si != null && si.port != 0)
            {

                //ServerInfo si = alo.result.serverInfos[server];

                if (si.players != null)
                {
                    if (si.players.Count > 2)
                    {
                        si.normalTeamGame = checkIfTeamGame(si);
                    }

                    if (si.normalTeamGame)
                    {
                        si.players.Sort(PlayersSort.TeamSort);

                    }
                    else
                    {
                        si.players.Sort(PlayersSort.ScoreSort);
                    }

                }
                oc.Set(server, si, cip);
            } //or maxplayers == -1 or numPlayers, etc
            else
            {
                Debug.WriteLine("[{0}] {1} \t No response", DateTime.Now, server);
            }

            //string id = Ext.CreateReadableID(server, si.hostPlayer);
            //context.Clients.All.addServer(id, server, si);
        }
Exemplo n.º 21
0
 public override object AddOrGetExisting(string key, object value, CacheItemPolicy policy, string regionName = null)
 {
     return this.AddOrInsert(
         HttpContext.Current.Cache.Add,
         key, value, policy, regionName
     );
 }
Exemplo n.º 22
0
        public static StatisticsRootObject GetStatistics(DateTime from, DateTime to, string lang, int count = 15)
        {
            if (MemoryCache.Default["GetStat_"+lang] != null)
                return MemoryCache.Default["GetStat_" + lang] as StatisticsRootObject;
            string basePath = GetPath();
            //Alla
            //http://localhost:83/secret/Find/proxy/_stats/query/top?from=2016-02-23T09%3A00%3A00Z&to=2016-02-24T09%3A00%3A00Z&interval=day&type=top&size=30&dojo.preventCache=1456301878242
            //Utan träffar
            //http://localhost:83/secret/Find/proxy/_stats/query/top?from=2016-02-23T09%3A00%3A00Z&to=2016-02-24T09%3A00%3A00Z&interval=day&type=null&size=30&dojo.preventCache=1456301993480
            //Utan relevanta träffar (dvs ingen klickad på ...)
            //http://localhost:83/secret/Find/proxy/_stats/query/top?from=2016-02-23T09%3A00%3A00Z&to=2016-02-24T09%3A00%3A00Z&interval=day&type=nullclick&extended=true&size=25&dojo.preventCache=1456302059188
            var requestAll = (HttpWebRequest)WebRequest.Create(basePath + "_stats/query/top?from=" + from.ToString("yyyy-MM-dd") + "&to=" + to.AddDays(1).ToString("yyyy-MM-dd") + "&interval=day&type=top&tags=language%3A"+lang+"&size=" + count + "&dojo.preventCache=" + DateTime.Now.Ticks);
            var responseAll = (HttpWebResponse)requestAll.GetResponse();
            var responseString = new StreamReader(responseAll.GetResponseStream()).ReadToEnd();

            var requestNull = (HttpWebRequest)WebRequest.Create(basePath + "_stats/query/top?from=" + from.ToString("yyyy-MM-dd") + "&to=" + to.AddDays(1).ToString("yyyy-MM-dd") + "&interval=day&type=null&tags=language%3A" + lang + "&size=" + count + "&dojo.preventCache=" + DateTime.Now.Ticks);
            var responseNull = (HttpWebResponse)requestNull.GetResponse();
            var responseStringNull = new StreamReader(responseNull.GetResponseStream()).ReadToEnd();

            var resultAll = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString, typeof(StatisticsRootObject));
            var resultNull = Newtonsoft.Json.JsonConvert.DeserializeObject(responseStringNull, typeof(StatisticsRootObject));
            List<Hit> modifiedHitList = new List<Hit>();
            if (resultAll != null && resultNull != null)
            {
                modifiedHitList = ((StatisticsRootObject)resultAll).hits.Except(((StatisticsRootObject)resultNull).hits).ToList();
                ((StatisticsRootObject)resultAll).hits = modifiedHitList;
            }

            //Insert data cache item with sliding timeout using changeMonitors
            CacheItemPolicy itemPolicy = new CacheItemPolicy();
            itemPolicy.SlidingExpiration = new TimeSpan(0, 5, 0);
            MemoryCache.Default.Add("GetStat_" + lang, resultAll as StatisticsRootObject, itemPolicy, null);

            return resultAll as StatisticsRootObject;
        }
Exemplo n.º 23
0
        private CacheItemPolicy CreatePolicy(IEnumerable<CacheExpirationInfo> expirationConfigs)
        {
            var policy = new CacheItemPolicy();

            foreach (CacheExpirationInfo config in expirationConfigs) {
                switch (config.Type) {
                    case "never":
                        policy.Priority = CacheItemPriority.NotRemovable;
                        break;

                    case "file":
                        if (!string.IsNullOrEmpty(config.Param)) {
                            policy.ChangeMonitors.Add(new HostFileChangeMonitor(new[] { config.Param }));
                        }
                        break;

                    case "absolute":
                        TimeSpan absoluteSpan;
                        if (TimeSpan.TryParse(config.Param, out absoluteSpan)) {
                             policy.AbsoluteExpiration = DateTimeOffset.Now.Add(absoluteSpan);
                        }
                        break;

                    case "sliding":
                        TimeSpan slidingSpan;
                        if (TimeSpan.TryParse(config.Param, out slidingSpan)) {
                            policy.SlidingExpiration = slidingSpan;
                        }
                        break;
                }
            }

            return policy;
        }
 private void AddWithoutCheck(DataCacheObject obj)
 {
   CacheItemPolicy policy = new CacheItemPolicy();
   policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(obj.CacheTime);
   lock (Cache)
     Cache.Add(new CacheItem(GetKey(obj), obj.Data), policy);
 }
Exemplo n.º 25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ObjectCache cache = MemoryCache.Default;

            string usernameFromXml = cache["userFromXml"] as string;

            if (usernameFromXml == null)
            {
                List<string> userFilePath = new List<string>();
                userFilePath.Add(@"C:\Username.xml");

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.ChangeMonitors.Add(new HostFileChangeMonitor(userFilePath));

                XDocument xdoc = XDocument.Load(@"C:\Username.xml");
                var query = from u in xdoc.Elements("usernames")
                            select u.Value;

                usernameFromXml = query.First().ToString();

                cache.Set("userFromXml", usernameFromXml, policy);
            }

            Label1.Text = usernameFromXml;
        }
Exemplo n.º 26
0
        public DealsDto[] GetAllActiveDeals(bool canLoadCachedDeals)
        {
            try
            {
                var configLoader = new ConfigHelper();
                if (!canLoadCachedDeals)
                {
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration =
                    DateTimeOffset.Now.AddMinutes(configLoader.GetAppSettingsIntlValue("DealCacheDuration"));
                    var dealsToBind = dDal.GetAllActiveDeals();
                    cacheDealObject.Set("Deals", dealsToBind, policy);
                    return dealsToBind;
                }

                DealsDto[] dealsToBindFromCache = cacheDealObject["Deals"] as DealsDto[];
                if (dealsToBindFromCache == null)
                {
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration =
                    DateTimeOffset.Now.AddMinutes(configLoader.GetAppSettingsIntlValue("DealCacheDuration"));
                    dealsToBindFromCache = dDal.GetAllActiveDeals();
                    cacheDealObject.Set("Deals", dealsToBindFromCache, policy);

                }
                return dealsToBindFromCache;
            }
            catch (Exception ex)
            {
                lBal.LogMessage(ex.InnerException.Message + "at " + ex.StackTrace, LogMessageTypes.Error);
                return null;
            }
        }
Exemplo n.º 27
0
        public static string GetHtmlPageContent(string path)
        {
            var key = HtmlPageContentKeyPrefix + path;
            var cache = MemoryCache.Default;
            var cachedPage = (string)cache.Get(key);

            if (cachedPage != null)
                return cachedPage;

            lock (CacheLock)
            {
                cachedPage = (string)cache.Get(key);

                if (cachedPage != null)
                    return cachedPage;

                var htmlPath = HttpContext.Current.Server.MapPath(path);
                cachedPage = File.ReadAllText(htmlPath, Encoding.UTF8);
                // создаём политику хранения данных
                var policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(Settings.Default.HtmlPageCacheAge);
                // сохраняем данные в кэше
                cache.Add(key, cachedPage, policy);

                return cachedPage;
            }
        }
        private void ExecuteSearch(string searchTerm)
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                var searchTermEncode = HttpUtility.UrlEncode(searchTerm);
                var key = String.Format("{0}:{1}", GetType().Name, searchTermEncode);
                ObjectCache cache = MemoryCache.Default;
                var bowerPackagesFromMemory = cache.Get(key) as IEnumerable<string>;

                if (bowerPackagesFromMemory != null)
                {
                    _searchResults = bowerPackagesFromMemory;
                }
                else
                {
                    string url = string.Format(Constants.SearchUrl, searchTermEncode);
                    string result = Helper.DownloadText(url);
                    var children = GetChildren(result);

                    if (!children.Any())
                    {
                        _dte.StatusBar.Text = "No packages found matching '" + searchTerm + "'";
                        base.Session.Dismiss();
                        return;
                    }

                    _dte.StatusBar.Text = string.Empty;
                    _searchResults = children;
                    var cachePolicy = new CacheItemPolicy();
                    cache.Set(key, _searchResults, cachePolicy);
                }

                Helper.ExecuteCommand(_dte, "Edit.CompleteWord");
            });
        }
        public async Task<IAnime> GetAnime(int id)
        {
            IAnime finalItem;
            var item = _animeCahce.Get(id.ToString());
            if (item == null)
            {
                Log.Information("Cache miss for {AnimeId}", id);

                var anime = await _animeRetriever.GetAnime(id);
                finalItem = anime;
                var cip = new CacheItemPolicy
                {
                    AbsoluteExpiration = DateTime.Now.AddHours(1),
                    RemovedCallback = RemovedCallback
                };
                lock (_animePadlock.GetOrAdd(id.ToString(), new object()))
                {
                    item = _animeCahce.Get(id.ToString());
                    if (item == null)
                    {
                        _animeCahce.Add(id.ToString(), finalItem, cip);
                        Log.Information("Added {AnimeId} to cache", id);
                    }
                }
            }
            else
            {
                Log.Information("Cache hit for {AnimeId}", id);
                finalItem = (IAnime) item;
            }
            return finalItem;
        }
Exemplo n.º 30
0
        protected override void SetInternal(string key, object value, TimeSpan lifespan)
        {
            var policy = new sys.CacheItemPolicy();

            policy.SlidingExpiration = lifespan;
            Set(key, value, policy);
        }
Exemplo n.º 31
0
		public void AddItem(CacheItem item, double span)
		{
			CacheItemPolicy cp = new CacheItemPolicy();
			cp.SlidingExpiration.Add(TimeSpan.FromMinutes(span));

			cache.Add(item, cp);
		}
 /// <summary>
 /// Return all the CommonFilter
 /// </summary>
 /// <param name="bypassCache">Option to go directly to the DB default false</param>
 /// <returns>Return all the CommonFilter</returns>
 public IHttpActionResult Get(bool bypassCache = false)
 {
     try
     {
         var response = new List<CommonFilter>();
         var memCache = MemoryCache.Default.Get("CommonFilters");
         if ((bypassCache) || (memCache == null))
         {
             using (var context = new DbModel())
             {
                 response = context.CommonFilters.ToList();
             }
             var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(1) };
             MemoryCache.Default.Add("CommonFilters", response, policy);
         }
         else
         {
             response = (List<CommonFilter>)memCache;
         }
         return Ok(response);
     }
     catch (Exception e)
     {
         logger.Error(e);
         return InternalServerError(e);
     }
 }
Exemplo n.º 33
0
        void IDnsCache.Set(string key, byte[] bytes, int ttlSeconds)
        {
            CacheItem item = new CacheItem(key, bytes);
            CacheItemPolicy policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now + TimeSpan.FromSeconds(ttlSeconds)};

            _cache.Add(item, policy);
        }
Exemplo n.º 34
0
        public DataTable GetProdutos(string connection, ABUtil.ABCommandArgs AbArgs)
        {
            try
            {
                DataTable Produtos = cache["Produtos"] as DataTable;

                WriteLog.Log(System.Diagnostics.TraceLevel.Info, LogTypeName.TAT2Request, "GetProdutos  - TB196 ", AbArgs.USERNT, AbArgs.SN_HOSTNAME);

                //Vai lêr à tabela
                if (Produtos == null)
                {
                    OdbcConnection con = new OdbcConnection(connection);
                    DataSet        ds  = new DataSet();

                    try
                    {
                        OdbcDataAdapter ad = new OdbcDataAdapter("SELECT CELEMTAB1, GELEM30, NELEMC01, NELEMC02 FROM TB196 where NELEMC01 != '' AND NELEMC13 = 'S'  order by NELEMC01", con); //Tabela geral TB196
                        ad.Fill(ds);
                    }
                    finally
                    {
                        con.Close();
                    }

                    WriteLog.Log(System.Diagnostics.TraceLevel.Verbose, LogTypeName.TAT2Request, "Setting cache for [Produtos]", AbArgs.USERNT, AbArgs.SN_HOSTNAME);

                    //Set Cache
                    System.Runtime.Caching.CacheItemPolicy policy = new System.Runtime.Caching.CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddDays(1);
                    cache.Set("Produtos", ds.Tables[0], policy);

                    WriteLog.Log(System.Diagnostics.TraceLevel.Verbose, LogTypeName.TAT2Request, "Retun value count: " + ds.Tables[0].Rows.Count, AbArgs.USERNT, AbArgs.SN_HOSTNAME);

                    return(ds.Tables[0]);
                }
                //Devolver valor em cache
                else
                {
                    WriteLog.Log(System.Diagnostics.TraceLevel.Verbose, LogTypeName.TAT2Request, "Cache found for [Produtos] : " + Produtos.Rows.Count, AbArgs.USERNT, AbArgs.SN_HOSTNAME);
                    return(Produtos);
                }
            }
            catch (Exception ex)
            {
                WriteLog.Log(System.Diagnostics.TraceLevel.Error, MultilinhasObjects.LogTypeName.TAT2Request, ex, AbArgs.USERNT, AbArgs.SN_HOSTNAME);
                DataTable dt = new DataTable();

                return(dt);
            }
        }
Exemplo n.º 35
0
        public ASP.CacheItemPolicy GetCacheItemPolicy()
        {
            ASP.CacheItemPolicy policy = new ASP.CacheItemPolicy
            {
                AbsoluteExpiration = this._absoluteOffset == TimeSpan.Zero ? this.AbsoluteExpiration : DateTime.Now.Add(this._absoluteOffset),
                SlidingExpiration  = this.SlidingExpiration,
                Priority           = this.Priority,
                // TODO: Add Callback Support
            };

            // TODO: Add dependency tracking
            // if (this.Dependencies.CacheKeys != null && this.Dependencies.CacheKeys.Count() > 0)
            // {
            //     policy.ChangeMonitors.Add(ASP.MemoryCache.Default.CreateCacheEntryChangeMonitor(this.Dependencies.CacheKeys.Distinct()));
            // }

            // TODO: Add more Support for more ChangeMonitors (Files + SQL)

            return(policy);
        }
Exemplo n.º 36
0
    public static void SetMemoryCacheDefault(this string key, object obj, int seconds = 7200)
    {
        try
        {
            var cache = System.Runtime.Caching.MemoryCache.Default;

            var policy = new System.Runtime.Caching.CacheItemPolicy
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(seconds)
            };

            cache.Set(key, obj, policy);
        }
        catch (Exception ex)
        {
            Console.WriteLine(string.Format("异常[{0}]:{1}", System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName, ex.Message));
        }
        finally
        {
        }
    }
        private SystemCaching.CacheItemPolicy GetCacheDependency(object tag, CacheItemPolicy itemPolicy, ServiceCacheByDispatcher dispatch)
        {
            // item priority
            SystemCaching.CacheItemPriority itemPriority;
            switch (itemPolicy.Priority)
            {
            case CacheItemPriority.NotRemovable:
                itemPriority = SystemCaching.CacheItemPriority.NotRemovable;
                break;

            default:
                itemPriority = SystemCaching.CacheItemPriority.Default;
                break;
            }
            var removedCallback = (itemPolicy.RemovedCallback != null ? new SystemCaching.CacheEntryRemovedCallback(x => { itemPolicy.RemovedCallback(x.CacheItem.Key, x.CacheItem.Value); }) : null);
            var updateCallback  = (itemPolicy.UpdateCallback != null ? new SystemCaching.CacheEntryUpdateCallback(x => { itemPolicy.UpdateCallback(x.UpdatedCacheItem.Key, x.UpdatedCacheItem.Value); }) : null);
            var newItemPolicy   = new SystemCaching.CacheItemPolicy
            {
                AbsoluteExpiration = itemPolicy.AbsoluteExpiration,
                Priority           = itemPriority,
                RemovedCallback    = removedCallback,
                SlidingExpiration  = itemPolicy.SlidingExpiration,
                UpdateCallback     = updateCallback,
            };
            var changeMonitors = GetCacheDependency(tag, itemPolicy.Dependency, dispatch);

            if (changeMonitors != null)
            {
                var list = newItemPolicy.ChangeMonitors;
                foreach (var changeMonitor in changeMonitors)
                {
                    list.Add(changeMonitor);
                }
            }
            return(newItemPolicy);
        }
Exemplo n.º 38
0
 public virtual bool Add(CacheItem item, CacheItemPolicy policy)
 {
     return(AddOrGetExisting(item, policy) == null);
 }
Exemplo n.º 39
0
 public virtual bool Add(string key, object value, CacheItemPolicy policy, string regionName = null)
 {
     return(AddOrGetExisting(key, value, policy, regionName) == null);
 }
Exemplo n.º 40
0
 public abstract CacheItem AddOrGetExisting(CacheItem value, CacheItemPolicy policy);
Exemplo n.º 41
0
 public abstract object AddOrGetExisting(string key, object value, CacheItemPolicy policy, string regionName = null);
Exemplo n.º 42
0
 public Boolean Add(ASP.CacheItem item, ASP.CacheItemPolicy policy)
 {
     return(false);
 }
Exemplo n.º 43
0
        public override bool Add(CacheItem item, CacheItemPolicy policy)
        {
            CacheItem existingEntry = AddOrGetExisting(item, policy);

            return(existingEntry == null || existingEntry.Value == null);
        }
Exemplo n.º 44
0
 public override void Set(System.Runtime.Caching.CacheItem item, System.Runtime.Caching.CacheItemPolicy policy)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 45
0
 public override void Set(CacheItem item, CacheItemPolicy policy)
 {
     Add(item, policy);
 }
Exemplo n.º 46
0
 public override object AddOrGetExisting(string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
 {
     CacheItemPolicy policy = new CacheItemPolicy();
     policy.AbsoluteExpiration = absoluteExpiration;
     return AddOrGetExisting(key, value, policy, regionName);
 }
Exemplo n.º 47
0
 public abstract void Set(CacheItem item, CacheItemPolicy policy);
Exemplo n.º 48
0
        protected override void SetInternal(string key, object value)
        {
            var policy = new sys.CacheItemPolicy();

            Set(key, value, policy);
        }
Exemplo n.º 49
0
 public override object AddOrGetExisting(string key, object value, System.Runtime.Caching.CacheItemPolicy policy, string regionName = null)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 50
0
 public override System.Runtime.Caching.CacheItem AddOrGetExisting(System.Runtime.Caching.CacheItem value, System.Runtime.Caching.CacheItemPolicy policy)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 51
0
 public abstract void Set(string key, object value, CacheItemPolicy policy, string regionName = null);
Exemplo n.º 52
0
 public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
 {
     Add(key, value, policy, regionName);
 }
Exemplo n.º 53
0
 private void Set(string key, object value, sys.CacheItemPolicy policy)
 {
     _cache.Set(key, value, policy);
 }