Beispiel #1
0
        public T Get <T>(string key)
        {
            // Look for cache key.
            var cacheEntry = _cache?.Get(key);

            if (cacheEntry == null)
            {
                return(default(T));
            }

            var raw = Encoding.UTF8.GetString(cacheEntry);

            _logger?.LogInformation(1001, "Getting item {ID}", raw);
            return(JsonConvert.DeserializeObject <T>(raw, config));
        }
        public IList <IServiceInstance> Get(string name)
        {
            var instanceData = _distributedCache?.Get(name);

            if (instanceData != null && instanceData.Length > 0)
            {
                return(DeserializeFromCache <List <SerializableIServiceInstance> >(instanceData).ToList <IServiceInstance>());
            }
            return(null);
        }
Beispiel #3
0
        public T Get <T>(string name)
        {
            var instanceData = _distributedCache?.Get(name);

            if (instanceData != null && instanceData.Length > 0)
            {
                return(DeserializeFromCache <T>(instanceData));
            }
            return(default(T));
        }
Beispiel #4
0
        private Weather checkCache(WeatherForCreationDto weatherForCreationDto)
        {
            // use zip as cache key else address
            var key = weatherForCreationDto.Zip == null
                ? weatherForCreationDto.Address
                : weatherForCreationDto.Zip.ToString();

            var cached = _cache.Get(key);

            if (cached == null)
            {
                return(null);
            }

            using (var ms = new MemoryStream(cached))
            {
                var cachedWeather = new BinaryFormatter()
                                    .Deserialize(ms) as Weather;

                return(cachedWeather);
            }
        }
Beispiel #5
0
        public RenderingContextResult BeginContext(string key)
        {
            bool authenticated = _principalAccessor.Principal.Identity.IsAuthenticated;
            var  cachedResult  = (authenticated) ? (string)null : _htmlCache.Get(key);

            if (cachedResult != null)
            {
                return new RenderingContextResult {
                           CachedResult = cachedResult
                }
            }
            ;

            var parentContext  = _requestCache.Get <RenderingContext>(ContextKey);
            var currentContext = new RenderingContext(parentContext, key);

            _requestCache.Set(ContextKey, currentContext);

            return(new RenderingContextResult {
                StartedContext = currentContext
            });
        }
        public IActionResult GetDataWithRedisCache()
        {
            string  cacheKey = "VietNamMapJson";
            JObject geoData;
            string  content;

            try
            {
                var redisCacheVietNamMap = _distributedCache.Get(cacheKey);
                if (redisCacheVietNamMap == null)
                {
                    ResponseModel response = VietNamMapCommon.LoadDataForVNMap(out geoData);
                    if (ResponseType.Success != response.Type)
                    {
                        content = JsonConvert.SerializeObject(new { success = false, data = string.Empty, message = response.Message });
                        return(Content(content, "application/json"));
                    }
                    DistributedCacheEntryOptions options = new DistributedCacheEntryOptions
                    {
                    };
                    _distributedCache.Set(cacheKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(geoData)));
                }
                else
                {
                    geoData = JObject.Parse(Encoding.UTF8.GetString(redisCacheVietNamMap));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }



            content = JsonConvert.SerializeObject(new { success = true, data = geoData });

            return(Content(content, "application/json"));
        }
Beispiel #7
0
        public IActionResult Get()
        {
            DateTime?cacheEntry;

            if (distributedCache.Get("Weather") == null)
            {
                cacheEntry = DateTime.Now;
                var cacheEntryOptions = new DistributedCacheEntryOptions()
                                        .SetSlidingExpiration(TimeSpan.FromSeconds(5))
                                        .SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
                distributedCache.SetString("Weather", cacheEntry.ToString(), cacheEntryOptions);
            }
            var cachedDate = distributedCache.GetString("Weather");
            var rng        = new Random();

            return(Ok(from temp in Enumerable.Range(1, 5)
                      select new
            {
                Date = cachedDate,
                TemperatureC = rng.Next(-20, 55),
                Summary = "Rainy day"
            }));
        }
Beispiel #8
0
        public T GetFromCache <T>(string key)
        {
            try
            {
                if (key == null)
                {
                    _logger.LogInformation($"Provided key is null.");
                    return(default(T));
                }

                var value  = _cache.Get(key);
                var result = FromByteArray <T>(value);

                _logger.LogDebug($"Retrieved obj value from cache. Key: {key} Value:{result}");

                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to retrieve value from cache. Key: {key} Exception:{ex}");
            }
            return(default(T));
        }
Beispiel #9
0
        public static IList <IServiceInstance> GetServiceInstancesWithCache(this IServiceDiscovery serviceDiscovery, string serviceId, IDistributedCache distributedCache, string serviceInstancesKeyPrefix = "ServiceDiscovery-ServiceInstances-")
        {
            // if distributed cache was provided, just make the call back to the provider
            if (distributedCache != null)
            {
                // check the cache for existing service instances
                var instanceData = distributedCache.Get(serviceInstancesKeyPrefix + serviceId);
                if (instanceData != null && instanceData.Length > 0)
                {
                    return(DeserializeFromCache <List <SerializableIServiceInstance> >(instanceData).ToList <IServiceInstance>());
                }
            }

            // cache not found or instances not found, call out to the provider
            var instances = serviceDiscovery.GetServiceInstances(serviceId);

            if (distributedCache != null)
            {
                distributedCache.Set(serviceInstancesKeyPrefix + serviceId, SerializeForCache(MapToSerializable(instances)));
            }

            return(instances);
        }
        public IActionResult Index()
        {
            //var data = cache.GetString("data");
            //if (!string.IsNullOrEmpty(data))
            //{
            //    ViewBag.Message = data;
            //}
            //else
            //{
            //    ViewBag.Message = "Nothing in cache";
            //    cache.SetString("data", "This is cache data");
            //}
            var data = cache.Get("data");

            if (data != null)
            {
                var mgs = Encoding.UTF8.GetString(data);
                ViewBag.Message = mgs;
            }
            else
            {
                ViewBag.Message = "Nothing in cache";
                var text  = "This is sample text data";
                var value = Encoding.UTF8.GetBytes(text);
                cache.Set("data", value);
            }
            var msg = Encoding.UTF8.GetBytes("This is Session data");

            HttpContext.Session.Set("message", msg);
            HttpContext.Session.SetInt32("count", 150);
            HttpContext.Session.SetString("name", "Apple");

            ViewBag.Flag = HttpContext.Items["flag"].ToString();

            return(View());
        }
Beispiel #11
0
        public IActionResult IndexDistributed()
        {
            string currentTime;

            byte[] value = _distributedCache.Get(CURRENT_DATE);

            if (value != null)
            {
                currentTime = Encoding.UTF8.GetString(value);
            }
            else
            {
                currentTime = DateTime.Now.ToString("dd/MM/yyyy hh:mm");

                DistributedCacheEntryOptions cacheEntryOptions = new DistributedCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromSeconds(60)
                };

                _distributedCache.Set(CURRENT_DATE, Encoding.UTF8.GetBytes(currentTime), cacheEntryOptions);
            }

            return(Content(currentTime));
        }
Beispiel #12
0
        public IActionResult Index()
        {
            List <Product> products      = null;
            var            cachedProduct = _distributedCache.Get("product");//cache_product

            if (cachedProduct == null)
            {
                products = GetProducts();
                var stringproduct = JsonConvert.SerializeObject(products);
                var bytes         = Encoding.UTF8.GetBytes(stringproduct);
                _distributedCache.Set("product", bytes
                                      , new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(500)
                });
                return(Ok(products));
            }
            else
            {
                var bytesAsString = Encoding.UTF8.GetString(cachedProduct);
                products = JsonConvert.DeserializeObject <List <Product> >(bytesAsString);
                return(Ok(products));
            }
        }
Beispiel #13
0
        /// <summary>
        /// 获取或刷新在线用户信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>在线用户信息</returns>
        public virtual OnlineUser GetOrRefresh(string userName)
        {
            string key = $"Identity_OnlineUser_{userName}";

            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(30));
            return(_cache.Get <OnlineUser>(key,
                                           () =>
            {
                return ServiceLocator.Instance.ExcuteScopedWork <OnlineUser>(provider =>
                {
                    UserManager <TUser> userManager = provider.GetService <UserManager <TUser> >();
                    TUser user = userManager.FindByNameAsync(userName).Result;
                    if (user == null)
                    {
                        return null;
                    }
                    IList <string> roles = userManager.GetRolesAsync(user).Result;
                    return GetOnlineUser(user, roles.ToArray());
                });
            },
                                           options));
        }
        public dynamic InformacionPantallaError(string sesion)
        {
            if (!String.IsNullOrEmpty(sesion))
            {
                JObject ObjTitulo    = JsonConvert.DeserializeObject <JObject>(CacheFunction.LeerByte(cache.Get(sesion + "-TituloError")));
                JObject ObjSubTitulo = JsonConvert.DeserializeObject <JObject>(CacheFunction.LeerByte(cache.Get(sesion + "-SubTituloError")));

                string titulo;
                try { titulo = ObjTitulo["Mensaje"].ToString(); } catch { throw; };
                string subtitulo;
                try { subtitulo = ObjSubTitulo["Mensaje"].ToString(); } catch { throw; };
                string origen;
                try { origen = CacheFunction.LeerByte(cache.Get(sesion + "-Origen")); } catch { throw; };

                return(new JObject
                {
                    { "TituloError", titulo },
                    { "SubTituloError", subtitulo },
                    { "Origen", origen }
                });
            }
            return(string.Empty);
        }
 public IActionResult GetDistributedCache()
 {
     return(Ok(Encoding.UTF8.GetString(_cache.Get(_cacheKey))));
 }
Beispiel #16
0
 public byte[] Get(string key)
 {
     return(_cache.Get(key));
 }
        public IActionResult ImageUrl()
        {
            byte[] imgByte = _distributedCache.Get("image");

            return(File(imgByte, "image/jpg"));
        }
        public Task <AuthenticationTicket> RetrieveAsync(string key)
        {
            var ticket = DeserializeFromBytes(_cache.Get(key));

            return(Task.FromResult(ticket));
        }
        public void Set_Get_Test()
        {
            string     key    = "key001";
            TestEntity entity = new TestEntity()
            {
                Name = "osharp", IsDeleted = true, AddDate = DateTime.Now, Id = 1
            };

            _cache.Set(key, entity);
            TestEntity newEntity = _cache.Get <TestEntity>(key);

            newEntity.ShouldNotBeNull();
            newEntity.Name.ShouldBe(entity.Name);
            newEntity.AddDate.ShouldBe(entity.AddDate);
            _cache.Remove(key);
            _cache.Get <TestEntity>(key).ShouldBeNull();

            key = "key002";
            _cache.Set(key, entity, 5);
            newEntity = _cache.Get <TestEntity>(key);
            newEntity.ShouldNotBeNull();
            newEntity.Name.ShouldBe(entity.Name);
            _cache.Remove(key);
            _cache.Get <TestEntity>(key).ShouldBeNull();

            IFunction function = new Function()
            {
                CacheExpirationSeconds = 10, IsCacheSliding = false
            };

            key = "key003";
            _cache.Set(key, entity, function);
            newEntity = _cache.Get <TestEntity>(key);
            newEntity.ShouldNotBeNull();
            newEntity.Name.ShouldBe(entity.Name);
            _cache.Remove(key);
            _cache.Get <TestEntity>(key).ShouldBeNull();

            function.CacheExpirationSeconds = 0; //过期时间为0不缓存
            _cache.Set(key, entity, function);
            newEntity = _cache.Get <TestEntity>(key);
            newEntity.ShouldBeNull();

            key       = "key004";
            newEntity = _cache.Get(key, () => entity, 10);
            newEntity.ShouldNotBeNull();
            newEntity.Name.ShouldBe(entity.Name);
            _cache.Remove(key);
            _cache.Get <TestEntity>(key).ShouldBeNull();

            key       = "key005";
            newEntity = _cache.Get(key, () => entity, function);
            newEntity.ShouldNotBeNull();
            newEntity.Name.ShouldBe(entity.Name);
            _cache.Remove(key);
            _cache.Get <TestEntity>(key).ShouldBeNull();
        }
 private List <CategoryViewModel> GetCache()
 => _cache.Get <List <CategoryViewModel> >(_key);
 /// <summary>
 /// 获取缓存,反序列化成对象返回
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="key">key</param>
 /// <returns>对象</returns>
 public static object GetObject(this IDistributedCache cache, string key)
 {
     return(Deserialize(cache.Get(key)));
 }
Beispiel #22
0
        public static T GetFromCache <T>(string cacheKey, IDistributedCache cache)
        {
            var cachedObj = cache.Get(cacheKey.ToUpper());

            return(cachedObj == null ? default : BytesToObject <T>(cachedObj));
        }
Beispiel #23
0
        /// <summary>
        /// 获取指定角色名与实体类型的数据权限过滤规则
        /// </summary>
        /// <param name="roleName">角色名称</param>
        /// <param name="entityTypeFullName">实体类型名称</param>
        /// <returns>数据过滤条件组</returns>
        public FilterGroup GetFilterGroup(string roleName, string entityTypeFullName)
        {
            string key = $"Security_EntityRole_{roleName}_{entityTypeFullName}";

            return(_cache.Get <FilterGroup>(key));
        }
 private StoreKey[] ReadTempStoredKeys()
 {
     return(cache.Get("TEMP_" + instanceKeyService.RetrieveKey().ToString()).DeserializeStoreKeys());
 }
Beispiel #25
0
        public async Task <IActionResult> Go(string id)
        {
            if (id == null)
            {
                return(NotFound("Link does not valid!"));
            }

            var getCache   = _cache.Get(id);
            var cachedLink = Encoding.UTF8.GetString(getCache);

            if (cachedLink != null)
            {
                Redirect(cachedLink);
            }

            var links = await _context.Links
                        .FirstOrDefaultAsync(l => l.shortLink == id);

            if (links == null)
            {
                return(NotFound("There is no any result!"));
            }


            var views = await _context.Views
                        .FirstOrDefaultAsync(w => w.ip == GetLocalIPAddress() && w.link == id);

            if (views == null)
            {
                try
                {
                    links.views = links.views + 1;
                    _context.Update(links);
                    await _context.SaveChangesAsync();

                    var viewsModel = new View();
                    viewsModel.ip   = GetLocalIPAddress();
                    viewsModel.link = id;
                    viewsModel.date = DateTime.Now;
                    _context.Add(viewsModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return(NotFound("'View' error!"));
                }
            }
            try
            {
                links.hits = links.hits + 1;

                await _hubContext.Clients.Group(id).SendAsync("ReceiveStatus", links.hits, links.views);

                _context.Update(links);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                return(NotFound("'Hits' error!"));
            }

            return(Redirect(links.fullLink));
        }
 private void BeforeAccessNotification(TokenCacheNotificationArgs args)
 {
     Deserialize(_cache.Get(GetCacheKey()));
 }
Beispiel #27
0
 /// <inheritdoc/>
 public byte[] Get(string key)
 {
     FusioCacheChaosUtils.MaybeChaos(ChaosMinDelay, ChaosMaxDelay, ChaosThrowProbability);
     return(_innerCache.Get(key));
 }
Beispiel #28
0
 /// <summary>
 /// Sync Get
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public byte[] Get(string key)
 {
     return(_syncPolicy.Execute(() => _distributedCache.Get(key)));
 }
        public T Get <T>(String cacheKey)
        {
            var retorno = Deserialize <T>(cache.Get(cacheKey));

            return(retorno);
        }
Beispiel #30
0
        /// <summary>
        /// 获取指定角色名与实体类型的数据权限过滤规则
        /// </summary>
        /// <param name="roleName">角色名称</param>
        /// <param name="entityTypeFullName">实体类型名称</param>
        /// <returns>数据过滤条件组</returns>
        /// <param name="operation">数据权限操作</param>
        public virtual FilterGroup GetFilterGroup(string roleName, string entityTypeFullName, DataAuthOperation operation)
        {
            string key = GetKey(roleName, entityTypeFullName, operation);

            return(_cache.Get <FilterGroup>(key));
        }