public async Task GetOrAddAsyncAndThenGetAsyncObjectReturnsCorrectType() { await sut.GetOrAddAsync(TestKey, () => Task.FromResult(testObject)); var actual = await sut.GetAsync <ComplexTestObject>(TestKey); Assert.IsNotNull(actual); Assert.That(actual, Is.EqualTo(testObject)); }
private async Task <(IEnumerable <Country>, bool)> GetCountries() { IEnumerable <Country> countries = null; var cacheHit = false; try { countries = await _cache.GetAsync <IEnumerable <Country> >(CacheKeys.CountriesKey); } catch (RedisConnectionException ex) { _logger.LogCritical(300, ex, ex.Message); } // Cache miss if (countries == null) { countries = await _dataContext.Connection.QueryAsync <Country>(_sql); } else { cacheHit = true; } return(countries, cacheHit); }
public async Task <IActionResult> OnPost() { var connection = _context.GetDbConnection(); var user = await connection.QueryAsync <PhpbbUsers>("SELECT * FROM phpbb_users WHERE username_clean = @username", new { username = _utils.CleanString(UserName) }); var lang = LanguageProvider.GetValidatedLanguage(null, Request); Mode = LoginMode.Normal; if (user.Count() != 1) { ModelState.AddModelError(nameof(LoginErrorMessage), LanguageProvider.Errors[lang, "WRONG_USER_PASS"]); return(Page()); } var currentUser = user.First(); if (currentUser.UserInactiveReason != UserInactiveReason.NotInactive || currentUser.UserInactiveTime != 0) { ModelState.AddModelError(nameof(LoginErrorMessage), LanguageProvider.Errors[lang, "INACTIVE_USER"]); return(Page()); } if (currentUser.UserPassword != Crypter.Phpass.Crypt(Password !, currentUser.UserPassword)) { ModelState.AddModelError(nameof(LoginErrorMessage), LanguageProvider.Errors[lang, "WRONG_USER_PASS"]); return(Page()); } await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, await _userService.DbUserToClaimsPrincipal(currentUser), new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.Now.Add(_config.GetValue <TimeSpan?>("LoginSessionSlidingExpiration") ?? TimeSpan.FromDays(30)), IsPersistent = true, }); var key = $"UserMustLogIn_{currentUser.UsernameClean}"; if (await _cache.GetAsync <bool?>(key) ?? false) { _cache.Remove(key); } var returnUrl = HttpUtility.UrlDecode(ReturnUrl ?? "/"); if (returnUrl.StartsWith("/login", StringComparison.InvariantCultureIgnoreCase) || returnUrl.StartsWith("/logout", StringComparison.InvariantCultureIgnoreCase) || returnUrl.StartsWith("/confirm", StringComparison.InvariantCultureIgnoreCase)) { returnUrl = "/"; } return(Redirect(returnUrl)); }
public async Task <T> Get <T>(string key) { string result = await _cache.GetAsync <string>(key).ConfigureAwait(false); if (string.IsNullOrEmpty(result)) { result = string.Empty; } return(JsonConvert.DeserializeObject <T>(result)); }
public async Task <IEnumerable <TEntity> > GetAllEntitiesAsync() { var entities = await _cache.GetAsync <IEnumerable <TEntity> >(GET_ALL_CACHE_KEY); if (entities == null) { entities = await this.Repository.SelectAllAsync(); _ = _cache.AddAsync(GET_ALL_CACHE_KEY, entities); } return(entities); }
public async Task <Airport> GetAirportData(string code) { var result = await cacheService.GetAsync <Airport>(code); if (result == null) { result = await client.GetAirportData(code); cacheService.Add(code, result, TimeSpan.FromDays(1)); } return(result); }
public async Task <T> GetOrAddAsync <T>(string key, Func <Task <T> > addItemFactory) { var cachedItem = await _cache.GetAsync <T>(key); try { var expires = SystemTime.UtcNow().AddMinutes(_appSettings.StaticDataCacheExpiryMins); cachedItem = await _cache.GetOrAddAsync <T>(key, LoggingWrapper(addItemFactory), expires); } catch (Exception exception) { _logger.Error(exception, $"Failed to retrieve type '{typeof(T).Name}' from cache."); } return(cachedItem); }
internal static IAppCache SetUpCacheEntryGet <T>(this IAppCache mockedCachingService, string cacheEntryKey, T cacheEntryValue) { EnsureArgument.IsNotNull(mockedCachingService, nameof(mockedCachingService)); EnsureArgument.IsNotNullOrEmpty(cacheEntryKey, nameof(cacheEntryKey)); Logger.LogDebug("Setting up cache entry Get/GetOrAdd for '{cacheEntryKey}' (type: '{type}'; value: '{cacheEntryValue}')", cacheEntryKey, typeof(T), cacheEntryValue); mockedCachingService.Get <T>(Arg.Is <string>(s => s.Equals(cacheEntryKey))).Returns(cacheEntryValue).AndDoes(x => Logger.LogDebug("Cache Get invoked")); mockedCachingService.GetOrAdd(Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, T> >()) .Returns(cacheEntryValue) .AndDoes(x => Logger.LogDebug("Cache GetOrAdd invoked")); //Backwards compatibility if (ProjectReflectionShortcuts.GetOrAddWithMemoryCacheEntryOptionsMethod != null) { Logger.LogDebug("Setting up GetOrAddWithMemoryCacheEntryOptionsMethod"); ProjectReflectionShortcuts.GetOrAddWithMemoryCacheEntryOptionsMethod.MakeGenericMethod(typeof(T)) .Invoke(mockedCachingService.Configure(), new object[] { Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, T> >(), Arg.Any <MemoryCacheEntryOptions>() }) .Returns(cacheEntryValue) .AndDoes(x => Logger.LogDebug("Cache GetOrAdd invoked")); } mockedCachingService.GetAsync <T>(Arg.Is <string>(s => s.Equals(cacheEntryKey))) .Returns(Task.FromResult(cacheEntryValue)) .AndDoes(x => Logger.LogDebug("Cache GetAsync invoked")); mockedCachingService.GetOrAddAsync(Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, Task <T> > >()) .Returns(Task.FromResult(cacheEntryValue)) .AndDoes(x => Logger.LogDebug("Cache GetOrAddAsync invoked")); //Backwards compatibility if (ProjectReflectionShortcuts.GetOrAddAsyncWithMemoryCacheEntryOptionsMethod != null) { Logger.LogDebug("Setting up GetOrAddAsyncWithMemoryCacheEntryOptionsMethod"); ProjectReflectionShortcuts.GetOrAddAsyncWithMemoryCacheEntryOptionsMethod.MakeGenericMethod(typeof(T)) .Invoke(mockedCachingService.Configure(), new object[] { Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, Task <T> > >(), Arg.Any <MemoryCacheEntryOptions>() }) .Returns(Task.FromResult(cacheEntryValue)) .AndDoes(x => Logger.LogDebug("Cache GetOrAddAsync invoked")); } return(mockedCachingService); }
/// <summary> /// Requests data for current region from game api. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestUri"></param> /// <param name="namespace"></param> /// <param name="requestOptions"></param> /// <returns></returns> public async Task <T> GetAsync <T>(string requestUri, string @namespace, RequestOptions requestOptions = null) { // Use default region and locale if not specified in request scope var region = requestOptions?.Region ?? _defaultApiConfiguration.Region; var locale = requestOptions.UseRegionLocale ? region.GetDefaultLocale() : (requestOptions?.Locale ?? _defaultApiConfiguration.Locale); var useCache = requestOptions?.UseCache ?? _defaultApiConfiguration.UseCache; var cacheDuration = requestOptions?.CacheDuration ?? _defaultApiConfiguration.CacheDuration; // Refresh token var token = await RequestTokenAsync(region); // Build query string var queryParams = requestOptions?.QueryParams ?? new Dictionary <string, string>(); queryParams.Add("locale", locale.ToQueryString()); if (!string.IsNullOrEmpty(@namespace)) { queryParams.Add("namespace", $"{@namespace}-{region.ToQueryString()}"); } var finalUri = QueryHelpers.AddQueryString($"{_defaultApiConfiguration.GetGameApiUrl(region)}{requestUri}", queryParams); // Setup request authorization _gameApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken); // Send request var response = useCache ? await _cache.GetAsync <string>(finalUri) : null; if (response == null) { using var responseMessage = await _gameApiClient.GetAsync(finalUri); responseMessage.EnsureSuccessStatusCode(); response = await responseMessage.Content.ReadAsStringAsync(); if (useCache) { _cache.Add(finalUri, response, TimeSpan.FromSeconds(cacheDuration)); } } // Return response return(JsonConvert.DeserializeObject <T>(response)); }
public async Task <TResponse> RunAsync <TRequest, TResponse>(TRequest request, CancellationToken cancellationToken, Func <TRequest, CancellationToken, Task <TResponse> > next) where TRequest : IRequest <TResponse> { if (!(request is IEnableInterceptor <CacheResponseInterceptor>)) { return(await next.Invoke(request, cancellationToken)); } _logger.Debug("CacheResponseInterceptor started"); var cacheRequest = request as ICacheResponse; if (cacheRequest != null) { _logger.Debug($"Retrieving response from cache. Key: {cacheRequest.CacheKey}"); var responseFromCache = await _appCache.GetAsync <TResponse>(cacheRequest.CacheKey, cancellationToken, absoluteExpiration : cacheRequest.AbsoluteExpiration); if (!EqualityComparer <TResponse> .Default.Equals(responseFromCache, default)) { _logger.Debug("Returning response from cache"); _logger.Debug("CacheResponseInterceptor ended"); return(responseFromCache); } } var response = await next(request, cancellationToken); if (cacheRequest != null) { _logger.Debug($"Saving response in cache. Key: {cacheRequest.CacheKey}"); await _appCache.SetAsync(cacheRequest.CacheKey, response, cancellationToken, cacheRequest.AbsoluteExpiration); } if (request is IClearCachedResponse clearCacheRequest) { _logger.Debug($"Removing response from cache. Key: {clearCacheRequest.CacheKey}"); await _appCache.RemoveAsync(clearCacheRequest.CacheKey, cancellationToken); } _logger.Debug("CacheResponseInterceptor ended"); return(response); }
private async Task <IList <RosettaAgency> > RetrieveAgencies() { var agencies = await _cache.GetAsync <IList <AgencyFranchiseMap> >($"{_cacheKeyPrefix}agencies"); // note: if cache is empty, return an empty list if (agencies == null || !agencies.Any()) { return(new List <RosettaAgency>()); } return(agencies .Select(agency => new RosettaAgency { clear_care_agency = agency.clear_care_agency, franchise_numbers = agency.franchise_numbers.ToArray() }) .OrderBy(franchise => franchise.clear_care_agency) .ToList()); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (EXCLUDED_PAGES.Contains(context.Request.Path)) { await next(context); return; } AuthenticatedUserExpanded?user; try { if (context.User?.Identity?.IsAuthenticated != true) { user = _userService.ClaimsPrincipalToAuthenticatedUser(await SignInAnonymousUser(context)); } else { user = _userService.ClaimsPrincipalToAuthenticatedUser(context.User); } if (user is null) { _logger.Warning("Failed to log in neither a proper user nor the anonymous idendity."); await next(context); return; } } catch (Exception ex) { _logger.Warning(ex, "Failed to parse claims"); await next(context); return; } var(isAllowed, dbUser) = await GetDbUserOrAnonymousIfNotAllowed(user); if (!isAllowed) { await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); user = _userService.ClaimsPrincipalToAuthenticatedUser(await SignInAnonymousUser(context)); } var permissionsTask = _userService.GetPermissions(user !.UserId); var tppTask = GetTopicPostsPage(user.UserId); var foesTask = _userService.GetFoes(user.UserId); await Task.WhenAll(permissionsTask, tppTask, foesTask); if (dbUser is null) { var anonymousClaimsPrincipal = await SignInAnonymousUser(context); user = _userService.ClaimsPrincipalToAuthenticatedUser(anonymousClaimsPrincipal); } var sessionTrackingTimeout = _config.GetValue <TimeSpan?>("UserActivityTrackingInterval") ?? TimeSpan.FromHours(1); if (dbUser is not null && !user !.IsAnonymous && ( await _cache.GetAsync <bool?>($"ReloadUser_{user.UsernameClean}") == true || DateTime.UtcNow.Subtract(dbUser.UserLastvisit.ToUtcTime()) > sessionTrackingTimeout)) { var claimsPrincipal = await _userService.DbUserToClaimsPrincipal(dbUser); await Task.WhenAll( SignIn(context, claimsPrincipal), _context.GetDbConnection().ExecuteAsync( "UPDATE phpbb_users SET user_lastvisit = @now WHERE user_id = @userId", new { now = DateTime.UtcNow.ToUnixTimestamp(), user.UserId } ) ); user = _userService.ClaimsPrincipalToAuthenticatedUser(claimsPrincipal); } user !.AllPermissions = await permissionsTask; user.TopicPostsPerPage = await tppTask; user.Foes = await foesTask; context.Items[nameof(AuthenticatedUserExpanded)] = user; if (user.IsAnonymous && context.Request.Headers.TryGetValue(HeaderNames.UserAgent, out var header) && (context.Session.GetInt32("SessionCounted") ?? 0) == 0) { try { var userAgent = header.ToString(); var dd = new DeviceDetector(userAgent); dd.Parse(); var IsBot = dd.IsBot(); if (IsBot) { if (context.Connection.RemoteIpAddress is not null) { _sessionCounter.UpsertBot(context.Connection.RemoteIpAddress.ToString(), userAgent, sessionTrackingTimeout); } } else { context.Session.SetInt32("SessionCounted", 1); _sessionCounter.UpsertSession(context.Session.Id, sessionTrackingTimeout); } } catch (Exception ex) { _logger.Warning(ex, "Failed to detect anonymous session type."); } } await next(context); }
public Task <T> GetAsync <T>(string key) { return(_cache.GetAsync <T>(key)); }
public Task <TValue> GetAsync <TKey, TValue>(TKey cacheKey) where TKey : CacheKey <TValue> { return(_appCache.GetAsync <TValue>(cacheKey)); }
public virtual async Task GetAsync_ReturnsDefaultValue() { var actualResult = await CachingService.GetAsync <Guid>(Fixture.Create <string>()); Assert.That(actualResult, Is.EqualTo(default(Guid))); }