public async Task AddAsync(string key, CartResponseDto cart) { string cachedData = await _service .GetCachedResponseAsync(key); if (cachedData == null) { return; } CartDetailedResponseDto cartDetailed = JsonConvert .DeserializeObject <CartDetailedResponseDto>(cachedData ); cartDetailed.cartItems.Add(cart); await _service.CacheResponseAsync(key, cartDetailed, TimeSpan.FromSeconds(600)); }
public async Task <AddContactCommandResponse> Handle(AddContactCommand command, CancellationToken cancellation) { var user = new AddUserCommand(); try { var data = await _responseCacheService.ManageTokenAsync(command.Token); if (data != null) { user = JsonConvert.DeserializeObject <AddUserCommand> (data); } } catch (Exception ex) { return(new AddContactCommandResponse() { Message = "Você precisa logar!", Success = false }); } var contacts = new List <AddContactCommand> (); try { var cachedValue = await _responseCacheService.GetCachedResponseAsync(user.Email); if (cachedValue != null) { contacts = JsonConvert.DeserializeObject <List <AddContactCommand> > (cachedValue); } } catch (Exception ex) { return(new AddContactCommandResponse() { Message = "Erro ao adicionar o contato!", Success = false }); } contacts.Add(command); var expiration = Convert.ToInt32(Environment.GetEnvironmentVariable("DATA_EXPIRATION_SECONDS")); expiration = expiration < 1 ? 900 : expiration; _responseCacheService.CacheResponseAsync(user.Email, contacts, new TimeSpan(0, 0, expiration)).ConfigureAwait(false); return(new AddContactCommandResponse() { Message = "Usuario cadastrado com sucesso!", Success = true }); }
public async Task ForgotPassword(string email, string currentUrl) { var(user, password) = await _repository.AuthenticateUser(email); if (user == null) { throw new BookstoreException(ExceptionMessages.INVALID_USER, 404); } byte[] secretKey = Encoding.ASCII.GetBytes(_configuration.GetSection("Jwt")["ResetPasswordSecretKey"]); int expiryTime = Convert.ToInt32(_configuration.GetSection("Jwt")["ExpiryTime"]); string jwt = _tokenManager.Encode(user, expiryTime, secretKey); string url = "https://" + currentUrl + "/html/reset.html?token=" + jwt; Message message = new Message(new string[] { user.Email }, "Password Reset Email", $"<h6>Click on the link to reset password<h6><a href='{url}'>{"click me"}</a>"); _mqServices.AddToQueue(message); await _caching.CacheResponseAsync(jwt, email, TimeSpan.FromSeconds(expiryTime)); }
public async Task <AddUserCommandResponse> Handle(AddUserCommand command, CancellationToken cancellation) { var users = new List <AddUserCommand> (); try { var cachedValue = await _responseCacheService.GetCachedResponseAsync("users"); if (cachedValue != null) { users = JsonConvert.DeserializeObject <List <AddUserCommand> > (cachedValue); } } catch (Exception ex) { return(new AddUserCommandResponse() { Message = "Erro ao cadastrar usuario", Success = false }); } command.Image = "https://picsum.photos/300/"; if (!users.Any(x => x.Email.Equals(command.Email))) { users.Add(command); } else { return new AddUserCommandResponse() { Message = "Usuario ja cadastrado com este email.", Success = false } }; var expiration = Convert.ToInt32(Environment.GetEnvironmentVariable("DATA_EXPIRATION_SECONDS")); expiration = expiration < 1 ? 900 : expiration; _responseCacheService.CacheResponseAsync("users", users, new TimeSpan(0, 0, expiration)).ConfigureAwait(false); return(new AddUserCommandResponse() { Message = "Usuario Cadastrado com sucesso!", Success = true }); } }
private async Task GetOrCacheResponse(ActionExecutingContext context, ActionExecutionDelegate next, ILogger <CachedAttribute> logger, IResponseCacheService cacheService, string cacheKey) { if (!HttpMethods.IsGet(context.HttpContext.Request.Method)) { await next(); return; } var cachedResponse = await cacheService.GetCachedResponseAsync(cacheKey); if (!string.IsNullOrEmpty(cachedResponse)) { logger.LogInformation("Returing cached request for {CacheKey}", cacheKey); var contentResult = new ContentResult { Content = cachedResponse, ContentType = "application/json", StatusCode = 200 }; context.Result = contentResult; return; } logger.LogInformation("Response was not in Redis Cache!"); var result = await next(); if (result.Result is OkObjectResult okObjectResult) { logger.LogInformation("Caching request {CacheKey} for {Seconds} seconds in Redis", cacheKey, ttlSeconds); await cacheService.CacheResponseAsync(cacheKey, okObjectResult.Value, TimeSpan.FromSeconds(ttlSeconds)); } }
/// <summary> /// Set search engine results on cache /// </summary> /// <param name="key"></param> /// <param name="searchEngineResults"></param> /// <returns></returns> private async Task SetDataCache(string key, List <SearchEngineResult> searchEngineResults) { await _cacheService.CacheResponseAsync(key, searchEngineResults, TimeSpan.FromSeconds(TimeToLiveSeconds)); }
/// <summary> /// Check if the dates are available in the cache. /// Y: serve from cache, N: make a new request to external api, then cache them as well. /// Filter the data. /// From the cached results calculate the Min,Max and Avg statistics for the dates. /// </summary> /// <param name="statsRequest"></param> /// <returns>Statistics for provided dates</returns> /// public async Task <Statistics> GetStatsAsync(GetStatsRequest statsRequest) { List <ExchangeRates> poolOfExchangeRatesFromCache = new List <ExchangeRates>(); var cachedRespStr = await _responseCacheService.GetCachedResponseAsync(_cacheKey); if (!String.IsNullOrEmpty(cachedRespStr)) { poolOfExchangeRatesFromCache = JsonConvert.DeserializeObject <List <ExchangeRates> >(cachedRespStr); poolOfExchangeRatesFromCache = poolOfExchangeRatesFromCache.Where(d => statsRequest.Dates.Contains(d.CurrenyOnDate)).ToList(); } // Get only the non-cached dates statsRequest.Dates = statsRequest.Dates.Except(poolOfExchangeRatesFromCache.Select(d => d.CurrenyOnDate)); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = cancellationTokenSource.Token; // Get new exchange rates from external source foreach (var queryDate in statsRequest.Dates) { string apiUrl = Utility.Utility.GetExchangeRatesApiUrlWithParameters(_exchangeRatesApiUrl, queryDate, statsRequest.CurrencyConversion); var currencyRatesForDate = await GetExchangeRateDataFromStreamAsync(token, apiUrl); // Remove the entries that don't have exchange rates for the queried date currencyRatesForDate = currencyRatesForDate.Where(c => c.CurrenyOnDate == queryDate).ToList(); if (currencyRatesForDate.Any()) { // Store this value in the cache await _responseCacheService.CacheResponseAsync(_cacheKey, currencyRatesForDate, new TimeSpan(0, 1, 0)); // cache it for 1 minute } // Merge the newly cached results with the existing results poolOfExchangeRatesFromCache.AddRange(currencyRatesForDate); } if (!poolOfExchangeRatesFromCache.Any()) { return(new Statistics()); } var leastValue = poolOfExchangeRatesFromCache .OrderBy(o => o.CurrenyOnDate) .Min(m => m.ToCurrencyValue); var leastValueDate = poolOfExchangeRatesFromCache .OrderBy(o => o.CurrenyOnDate) .Where(m => m.ToCurrencyValue == leastValue) .Select(m => m.CurrenyOnDate) .FirstOrDefault(); var maxValue = poolOfExchangeRatesFromCache .OrderBy(o => o.CurrenyOnDate) .Max(m => m.ToCurrencyValue); var maxValueDate = poolOfExchangeRatesFromCache .OrderBy(o => o.CurrenyOnDate) .Where(m => m.ToCurrencyValue == maxValue) .Select(m => m.CurrenyOnDate) .FirstOrDefault(); var avgValue = poolOfExchangeRatesFromCache .Average(m => m.ToCurrencyValue); var stats = new Statistics() { Min = leastValue, MinDate = leastValueDate, Max = maxValue, MaxDate = maxValueDate, Avg = avgValue }; return(stats); }
private async Task <DataResponseModel> GetDataFromEndpoint() { HttpResponseMessage response; // the number of parallel request that can be made to the data endpoint. int maxParallelism = Convert.ToInt16(_config["maxParallelism"]); var dataResponse = new DataResponseModel(); // The number of days the response from the data endpoint int timeToLiveSeconds = Convert.ToInt32(_config["DataUrlTimeToLive"]); var cachedResponse = await _iResponseCacheService.GetCachedResponseAsync(_dataUrl); if (string.IsNullOrEmpty(cachedResponse)) { // The handler for the number of requests var handler = new ThrottlingHandler(new SemaphoreSlim(maxParallelism), new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, }); using (var client = new HttpClient(handler)) { client.Timeout = Timeout; response = await client.GetAsync(_dataUrl); // This checks if the request was successfull or times out. if (response.IsSuccessStatusCode) { cachedResponse = response.Content.ReadAsStringAsync().Result; dataResponse = JsonConvert.DeserializeObject <DataResponseModel>( cachedResponse, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto } ); await _iResponseCacheService.CacheResponseAsync(_dataUrl, dataResponse, TimeSpan.FromSeconds(timeToLiveSeconds)); return(dataResponse); } else { throw new CustomResponseException("Endpoint Could not be reached."); } } } else { return(JsonConvert.DeserializeObject <DataResponseModel>( cachedResponse, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto } )); } }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var isResponseCacheEnabled = false; try { var responseCacheSettings = context .HttpContext .RequestServices .GetRequiredService <RedisCacheSettings>(); isResponseCacheEnabled = responseCacheSettings.IsEnabled; } catch (Exception ex) { // Log //throw; } if (!isResponseCacheEnabled) { await next(); return; } IResponseCacheService responseCacheService = null; try { responseCacheService = context .HttpContext .RequestServices .GetRequiredService <IResponseCacheService>(); } catch (Exception ex) { // Log //throw; } var responseCacheKey = GenerateCacheKeyFromRequest(context.HttpContext.Request); var willUseCache = responseCacheService != null && responseCacheKey != null; try { if (willUseCache) { var cachedResponse = await responseCacheService .GetCachedResponseAsync(responseCacheKey); if (!string.IsNullOrEmpty(cachedResponse)) { var contentResult = new ContentResult { Content = JToken.Parse(cachedResponse).ToString(Formatting.Indented), ContentType = "application/json", StatusCode = 200 }; context.Result = contentResult; return; } } } catch (Exception ex) { // Log //throw; } var executedContext = await next(); if (willUseCache) { //if (executedContext.Result is OkObjectResult okObjectResult) if (executedContext.Result is ObjectResult okObjectResult) { await responseCacheService .CacheResponseAsync( responseCacheKey, okObjectResult.Value, TimeSpan.FromSeconds(_timeToLiveSeconds)); } } }
public async Task <UpdateUserCommandResponse> Handle(UpdateUserCommand command, CancellationToken cancellation) { var sessionUser = new AddUserCommand(); try { var data = await _responseCacheService.ManageTokenAsync(command.Token); if (data != null) { sessionUser = JsonConvert.DeserializeObject <AddUserCommand> (data); } } catch (Exception ex) { return(new UpdateUserCommandResponse() { Message = "Você precisa logar!", Success = false }); } var users = new List <AddUserCommand> (); try { var cachedValue = await _responseCacheService.GetCachedResponseAsync("users"); if (cachedValue != null) { users = JsonConvert.DeserializeObject <List <AddUserCommand> > (cachedValue); } } catch (Exception ex) { return(new UpdateUserCommandResponse() { Message = "Erro ao alterar senha", Success = false }); } var user = users.FirstOrDefault(x => x.Email.Equals(command.Email)); if (user != null) { if (sessionUser.Email.Equals(user.Email)) { user.Password = command.Password; } else { return new UpdateUserCommandResponse() { Message = "Alteração não autorizada!", Success = false } }; } else { return(new UpdateUserCommandResponse() { Message = "Email não cadastrado", Success = false }); } var expiration = Convert.ToInt32(Environment.GetEnvironmentVariable("DATA_EXPIRATION_SECONDS")); expiration = expiration < 1 ? 900 : expiration; _responseCacheService.CacheResponseAsync("users", users, new System.TimeSpan(0, 0, expiration)).ConfigureAwait(false); return(new UpdateUserCommandResponse() { Message = "Senha alterada com sucesso!", Success = true }); }