Пример #1
0
        async Task WriteToCache <T>(ICacheEntry entry, string key, T obj)
        {
            try
            {
                if (!UseDistributedCache)
                {
                    entry.SetOptions(new MemoryCacheEntryOptions()
                    {
                        AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds)
                    });

                    // Set expiration tokens
                    entry.ExpirationTokens.Add(_cacheDependency.GetToken(key));
                    entry.SetValue(obj);
                    // need to manually call dispose instead of having a using
                    // statement in case the factory passed in throws, in which case we
                    // do not want to add the entry to the cache
                    entry.Dispose();

                    //_memoryCache.Set(entry.Key.ToString(), obj, DateTimeOffset.UtcNow.AddSeconds(expirationInSeconds));
                    return;
                }
                var toStore = JsonConvert.SerializeObject(obj);
                await _distributedCache.SetAsync(key, Encoding.UTF8.GetBytes(toStore), new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds)
                });
            }
            catch
            {
                // DistributedCache storage failed. Fail over to MemoryCache.

                entry.SetOptions(new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds)
                });

                // Set expiration tokens
                entry.ExpirationTokens.Add(_cacheDependency.GetToken(key));
                entry.SetValue(obj);
                // need to manually call dispose instead of having a using
                // statement in case the factory passed in throws, in which case we
                // do not want to add the entry to the cache
                entry.Dispose();
                //_memoryCache.Set(key, obj, DateTimeOffset.UtcNow.AddSeconds(expirationInSeconds));
            }
        }
Пример #2
0
        public async Task Login(string request_token)
        {
            string tokenExchangeEndpoint = $"{this._configuration.GetValue<string>("kiteApiBaseUrl")}{this._configuration.GetValue<string>("kiteAccessTokenUrl")}";
            KiteAccessTokenResponseRoot kiteAccessTokenResponseRoot = null;
            bool cacheFetchResult = this._cache.TryGetValue <KiteAccessTokenResponseRoot>("kite_access_token", out kiteAccessTokenResponseRoot);

            if (!cacheFetchResult)
            {
                try
                {
                    string accessTokenRequest     = $"{this._configuration.GetValue<string>("kiteApiKey")}{request_token}{this._configuration.GetValue<string>("kiteApiSecret")}";
                    string accessTokenRequestHash = CommonFunctions.ComputeSha256Hash(accessTokenRequest);
                    var    param = new Dictionary <string, dynamic>
                    {
                        { "api_key", this._configuration.GetValue <string>("kiteApiKey") },
                        { "request_token", request_token },
                        { "checksum", accessTokenRequestHash }
                    };

                    string      paramString = String.Join("&", param.Select(x => CommonFunctions.BuildParam(x.Key, x.Value)));
                    HttpContent accessTokenRequestContent = new StringContent(paramString, Encoding.UTF8, "application/x-www-form-urlencoded");
                    accessTokenRequestContent.Headers.Add("X-Kite-Version", "3");
                    HttpResponseMessage access_token_response = await this._httpClient.PostAsync(tokenExchangeEndpoint, accessTokenRequestContent);

                    if (access_token_response.IsSuccessStatusCode)
                    {
                        Stream responseStream = await access_token_response.Content.ReadAsStreamAsync();

                        var respose = new StreamReader(responseStream).ReadToEnd();
                        kiteAccessTokenResponseRoot = JsonSerializer.Deserialize <KiteAccessTokenResponseRoot>(respose);
                        MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions();
                        cacheOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(8));
                        cacheOptions.Priority           = CacheItemPriority.NeverRemove;
                        cacheOptions.RegisterPostEvictionCallback(new PostEvictionDelegate(this.CacheEvictionCallback));
                        cacheOptions.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));

                        using (ICacheEntry cacheEntry = this._cache.CreateEntry((object)"kite_access_token"))
                        {
                            cacheEntry.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));
                            cacheEntry.SetOptions(cacheOptions);
                            cacheEntry.SetValue(kiteAccessTokenResponseRoot);
                        }
                    }
                    else
                    {
                        this._logger.LogError(access_token_response.ReasonPhrase);
                    }
                }
                catch (Exception ex)
                {
                    this._logger.LogError(ex.Message);
                    throw new IntelliTradeException("An error occurred while trying to get access token from Kite.", ex);
                }
            }
        }
Пример #3
0
        public static TItem Set <TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)
        {
            using ICacheEntry entry = cache.CreateEntry(key);
            if (options != null)
            {
                entry.SetOptions(options);
            }

            entry.Value = value;

            return(value);
        }
Пример #4
0
        private async Task <User> CacheOutEntity(ICacheEntry cachedEntity)
        {
            cachedEntity.SetOptions(_cacheOptions);

            var foundUser = await _databaseContext.Users.FindAsync(cachedEntity.Key);

            if (foundUser == null)
            {
                throw new NoSuchEntityFoundException((int)cachedEntity.Key, $"Unable to find entity with id:{(int)cachedEntity.Key}.");
            }

            return(foundUser);
        }
        public static TItem Set <TKey, TItem>(this IMemoryCache <TKey> cache, TKey key, TItem value, MemoryCacheEntryOptions <TKey> options)
            where TKey : notnull
        {
            using ICacheEntry <TKey> entry = cache.CreateEntry(key);
            if (options != null)
            {
                entry.SetOptions(options);
            }

            entry.Value = value;

            return(value);
        }
Пример #6
0
        public static T Set <T>(this ICustomCache cache, object key, T value, MemoryCacheEntryOptions options)
        {
            using (ICacheEntry entry = cache.CreateEntry(key))
            {
                if (options != null)
                {
                    entry.SetOptions(options);
                }

                entry.Value = value;
            }

            return(value);
        }
Пример #7
0
        private void CacheEvictionCallback(object key, object value, EvictionReason reason, object state)
        {
            if (EvictionReason.Expired == reason)
            {
                KiteAccessTokenResponseRoot kiteAccessTokenResponseRoot = (KiteAccessTokenResponseRoot)value;
                MemoryCacheEntryOptions     cacheOptions = new MemoryCacheEntryOptions();
                cacheOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(8));
                cacheOptions.Priority           = CacheItemPriority.NeverRemove;
                cacheOptions.RegisterPostEvictionCallback(new PostEvictionDelegate(this.CacheEvictionCallback));
                cacheOptions.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));

                using (ICacheEntry cacheEntry = this._cache.CreateEntry((object)"kite_access_token"))
                {
                    cacheEntry.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));
                    cacheEntry.SetOptions(cacheOptions);
                    cacheEntry.SetValue(kiteAccessTokenResponseRoot);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Adds an object to distributed cache
        /// </summary>
        /// <param name="key">Cache Key</param>
        /// <param name="value">Cache object</param>
        /// <param name="options">Distributed cache options. <see cref="ExtendedDistributedCacheEntryOptions"/></param>
        public void Set(string key, byte[] value, ExtendedDistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            using (ICacheEntry cacheEntry = CreateEntry(key))
            {
                var memoryCacheEntryOptions = GetMemoryCacheEntryOptions(options, value.LongLength);
                cacheEntry.SetOptions(memoryCacheEntryOptions);
                if (memoryCacheEntryOptions.AbsoluteExpiration != null)
                {
                    cacheEntry.SetAbsoluteExpiration(memoryCacheEntryOptions.AbsoluteExpiration.Value);
                }
                if (memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow != null)
                {
                    cacheEntry.SetAbsoluteExpiration(memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow.Value);
                }
                if (memoryCacheEntryOptions.SlidingExpiration != null)
                {
                    cacheEntry.SetSlidingExpiration(memoryCacheEntryOptions.SlidingExpiration.Value);
                }
                cacheEntry.SetPriority(memoryCacheEntryOptions.Priority);
                cacheEntry.SetSize(value.LongLength);
                cacheEntry.SetValue(value);
            }
        }