Exemple #1
0
        private CacheEntry PopulateFromEndpoint(AutoPopulateEndpoint endpoint = null)
        {
            var myMRE = GetManualResetEvent();

            try
            {
                myMRE.WaitOne();
                myMRE.Reset();

                endpoint = endpoint ?? GlobalSettings.AutoPopulateEndpoints.FirstOrDefault(x => x.authorization == Authorization && x.cacheKey == CacheKey);

                if (endpoint != null)
                {
                    var request = new APIRequest(endpoint.baseURL);
                    if (!string.IsNullOrWhiteSpace(endpoint.endpointAuthorizationKey))
                    {
                        request.AddHeader(endpoint.endpointAuthorizationKey, endpoint.endpointAuthorizationValue);
                    }

                    var result = request.Get <AutoPopulateResult>(endpoint.endpointMethod);

                    if (result.CacheSecondsOverride.HasValue && result.CacheSecondsOverride.Value >= 0)
                    {
                        CacheSeconds = result.CacheSecondsOverride.Value;
                    }
                    else if (endpoint.cacheLifespanSeconds.HasValue && endpoint.cacheLifespanSeconds.Value >= 0)
                    {
                        CacheSeconds = endpoint.cacheLifespanSeconds.Value;
                    }

                    object dataObj = GetDataObject(result.Data);

                    var entry = new CacheEntry(Authorization, CacheKey, dataObj, expirationSeconds: CacheSeconds);

                    lock (GenericMemLock)
                    {
                        var allKeys = GetAllKeys();
                        AddKeyToAllKeys(allKeys, entry);
                    }

                    MemoryCache.Set(GetAuthKey(CacheKey), entry, new MemoryCacheEntryOptions
                    {
                        AbsoluteExpirationRelativeToNow = CacheSeconds > 0 ? TimeSpan.FromSeconds(CacheSeconds) : (TimeSpan?)null
                    });

                    return(entry);
                }

                throw new Exception("cacheKey does not have a value");
            }
            finally
            {
                myMRE.Set();
            }
        }