예제 #1
0
        public async Task GetOrAddAsyncWithPostEvictionCallbacksReturnsTheOriginalCachedKeyEvenIfNotGettedBeforehand()
        {
            string callbackKey             = null;
            var    memoryCacheEntryOptions = new MemoryCacheEntryOptions
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100)
            };

            memoryCacheEntryOptions.RegisterPostEvictionCallback((key, value, reason, state) =>
            {
                callbackKey = key.ToString();
            });
            await sut.GetOrAddAsync(TestKey, () => Task.FromResult(123), memoryCacheEntryOptions);

            sut.Remove(TestKey); //force removed callback to fire
            while (callbackKey == null)
            {
                Thread.Sleep(500);
            }

            callbackKey.Should().Be(TestKey);
        }
예제 #2
0
        public async Task <ActionResult <LiveResultsResponse> > GetLatestResults([FromQuery] ResultsType type, string location)
        {
            try
            {
                var key    = $"results-{type.ConvertEnumToString()}-{location}";
                var result = await _appCache.GetOrAddAsync(
                    key, () => _resultsAggregator.GetResults(type, location), DateTimeOffset.Now.AddMinutes(5));

                if (result.IsFailure)
                {
                    _appCache.Remove(key);
                    _logger.LogError(result.Error);
                    return(BadRequest(result.Error));
                }
                return(result.Value);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception encountered while retrieving results");
                throw;
            }
        }
예제 #3
0
        public async Task <ActionResult <LiveResultsResponse> > GetResults([FromQuery] string electionId, string source = null, string county = null, FileType fileType = FileType.Results)
        {
            try
            {
                var resultsQuery = new ResultsQuery(fileType, source, county, electionId);
                var key          = resultsQuery.ToString();
                var result       = await _appCache.GetOrAddAsync(
                    key, () => _resultsAggregator.GetElectionResults(resultsQuery),
                    DateTimeOffset.Now.AddSeconds(_config.Value.IntervalInSeconds));

                if (result.IsFailure)
                {
                    _appCache.Remove(key);
                    _logger.LogError(result.Error);
                    return(BadRequest(result.Error));
                }
                return(result.Value);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception encountered while retrieving results");
                throw;
            }
        }
        public override async Task <int> CreateAsync(Todo entity)
        {
            var id = await base.CreateAsync(entity);

            if (id > 0)
            {
                _cache.Remove(CACHE_KEY);
            }
            return(id);
        }
예제 #5
0
        public void Invalidate(Type classType, string cacheKey)
        {
            var keys     = _cacheProvider.GetKeys();
            var typeName = classType.Name.Replace("Proxy", "");

            cacheKey = $"{typeName}.{cacheKey}";
            var key = keys.FirstOrDefault(x => x.StartsWith(cacheKey));

            if (key == null)
            {
                CachedAttributesOptions.Log("Cannot find key in cache:" + key);
                return;
            }

            _cacheProvider.Remove(key);
        }
예제 #6
0
        public async Task <Evaluation> Submit(Guid profileId, Guid chapterId, int pageIndex, string solution)
        {
            var profile = await _profiles.Get(profileId, UserId);

            var submit     = new Submit(chapterId, pageIndex, solution);
            var evaluation = await _evaluator.Evaluate(profile, submit);

            if (!profile.Equals(evaluation.Profile))
            {
                var cachedId = profile.Id.ToString();

                _cache.Remove(cachedId);
                _cache.Add(cachedId, profile);
            }

            return(evaluation);
        }
예제 #7
0
 public void Remove(string id)
 {
     _appCache.Remove(id);
 }
예제 #8
0
 public bool PurgeCache()
 {
     _cache.Remove("videos");
     return(true);
 }
예제 #9
0
 public async Task RemoveAsync(string key)
 => _cache.Remove(key);
 protected override void Handle(ClearCustomPrefixRequest request)
 => _cache.Remove(GetCacheKey(request.Id));
예제 #11
0
 public void RemoveUserCache(Guid userId)
 {
     _cache.Remove(CacheKey(userId));
 }
예제 #12
0
 public static void ClearRegisteredSips(this IAppCache cache)
 {
     log.Debug("Removing registered sips from cache");
     cache.Remove(RegisteredSipsKey);
 }
예제 #13
0
 public static void ResetSettings(this IAppCache cache)
 {
     log.Debug("Removing settings from cache");
     cache.Remove(SettingsKey);
 }
예제 #14
0
 public static void ResetProfiles(this IAppCache cache)
 {
     log.Debug("Removing profiles from cache");
     cache.Remove(ProfilesKey);
 }
예제 #15
0
 public static void ResetAvailableFilters(this IAppCache cache)
 {
     log.Debug("Removing available filters from cache");
     cache.Remove(AvailableFiltersKey);
 }
예제 #16
0
 public static void ResetLocationNetworks(this IAppCache cache)
 {
     log.Debug("Removing location networks from cache");
     cache.Remove(LocationNetworksKey);
 }
예제 #17
0
 public static void ClearProfileGroups(this IAppCache cache)
 {
     log.Debug("Removing profile groups from cache");
     cache.Remove(ProfileGroupsKey);
 }
예제 #18
0
 public void TearDown()
 {
     cache.Remove(code);
 }
예제 #19
0
        public void RemovePageCache(int pageId)
        {
            var cacheKey = $"{CacheVariable.CacheKeyPrefixPage}_{pageId}";

            _cache.Remove(cacheKey);
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            try
            {
                var token = GetTokenFromAuthHeader();

                if (string.IsNullOrEmpty(token))
                {
                    return(AuthenticateResult.Fail("The Headstart bearer token was not provided in the Authorization header."));
                }

                var jwt      = new JwtSecurityToken(token);
                var clientId = jwt.GetClientID();
                var usrtype  = jwt.GetUserType();

                if (clientId == null)
                {
                    return(AuthenticateResult.Fail("The provided bearer token does not contain a 'cid' (Client ID) claim."));
                }

                // we've validated the token as much as we can on this end, go make sure it's ok on OC

                var cid = new ClaimsIdentity("OrderCloudIntegrations");
                cid.AddClaim(new Claim("clientid", clientId));
                cid.AddClaim(new Claim("accesstoken", token));

                var allowFetchUserRetry = false;
                var user = await _cache.GetOrAddAsync(token, () => {
                    try {
                        // TODO: winmark calls this from other oc environments so we cant use sdk
                        // remove once winmark uses cms api
                        //var user = await Options.OrderCloudClient.Me.GetAsync(token);
                        return($"{jwt.GetApiUrl()}/v1/me".WithOAuthBearerToken(token).GetJsonAsync <MeUser>());
                    }
                    catch (FlurlHttpException ex) when((int?)ex.Call.Response?.StatusCode < 500)
                    {
                        return(null);
                    }
                    catch (Exception) {
                        allowFetchUserRetry = true;
                        return(null);
                    }
                }, TimeSpan.FromMinutes(5));

                if (allowFetchUserRetry)
                {
                    _cache.Remove(token); // not their fault, don't make them wait 5 min
                }
                if (user == null || !user.Active)
                {
                    return(AuthenticateResult.Fail("Authentication failure"));
                }

                cid.AddClaim(new Claim("username", user.Username));
                cid.AddClaim(new Claim("userid", user.ID));
                cid.AddClaim(new Claim("email", user.Email ?? ""));
                cid.AddClaim(new Claim("buyer", user.Buyer?.ID ?? ""));
                cid.AddClaim(new Claim("supplier", user.Supplier?.ID ?? ""));
                cid.AddClaim(new Claim("seller", user?.Seller?.ID ?? ""));

                cid.AddClaims(user.AvailableRoles.Select(r => new Claim(ClaimTypes.Role, r)));
                var roles = jwt.Claims.Where(c => c.Type == "role").Select(c => new Claim(ClaimTypes.Role, c.Value)).ToList();
                roles.Add(new Claim(ClaimTypes.Role, BaseUserRole));
                cid.AddClaims(roles);

                var ticket       = new AuthenticationTicket(new ClaimsPrincipal(cid), "OrderCloudIntegrations");
                var ticketResult = AuthenticateResult.Success(ticket);
                return(ticketResult);
            }
            catch (Exception ex)
            {
                return(AuthenticateResult.Fail(ex.Message));
            }
        }
예제 #21
0
 private void ClearCache()
 {
     _lazyCache.Remove(SettingsKey);
 }
 private void ClearCache() => _cache.Remove("books_in_cache");
        public async Task <bool> Delete(string key)
        {
            await Task.Run(() => _cache.Remove(key)).ConfigureAwait(false);

            return(true);
        }
        public Task RemoveAsync <TKey, TValue>(TKey cacheKey) where TKey : CacheKey <TValue>
        {
            _appCache.Remove(cacheKey);

            return(Task.CompletedTask);
        }
        public async Task <TmdbConfigurationModelResult> GetTmdbConfiguration(int retryCount = 0, int delayMilliseconds = 1000, bool fromCache = true)
        {
            string key = "$" + nameof(GetTmdbConfiguration);

            if (!fromCache)
            {
                _cache.Remove(key);
            }

            var result = _cache.Get <TmdbConfigurationModelResult>(key) ?? await _networkClient.GetTmdbConfiguration(retryCount, delayMilliseconds);

            if (result.HttpStatusCode.IsSuccessCode())
            {
                _cache.Add(key, result, System.TimeSpan.FromDays(1));
            }

            return(result);
        }
예제 #26
0
 public static void ClearProfiles(this IAppCache cache)
 {
     log.Debug("Removing all profile names and sdp from cache");
     cache.Remove(AllProfileNamesAndSdpKey);
 }
예제 #27
0
 public static void Remove(string keyName)
 {
     LogHandler.Info($"Cache - Removeing {keyName}");
     cache.Remove(keyName);
 }
예제 #28
0
 public static void ClearSipAccounts(this IAppCache cache)
 {
     log.Debug("Removing sip accounts from cache");
     cache.Remove(SipAccountsKey);
 }
예제 #29
0
 public void Remove(string key)
 {
     _cache.Remove(key);
 }
예제 #30
0
 public static void ClearCallHistory(this IAppCache cache)
 {
     log.Debug("Removing call history from cache");
     cache.Remove(CallHistoryKey);
 }