コード例 #1
0
        public async Task <GetContactsQueryResponse> Handle(GetContactsQuery query, CancellationToken cancellation)
        {
            var user = new User();

            try {
                var data = await _responseCacheService.ManageTokenAsync(query.Token);

                if (data != null)
                {
                    user = JsonConvert.DeserializeObject <User> (data);
                }
            } catch (Exception ex) {
                return(new GetContactsQueryResponse()
                {
                });
            }

            var response = new GetContactsQueryResponse();

            try {
                var cachedValue = await _responseCacheService.GetCachedResponseAsync(user.Email);

                if (cachedValue != null)
                {
                    var cachedResponse = JsonConvert.DeserializeObject <IEnumerable <Contact> > (cachedValue);
                    response.Contacts = cachedResponse;
                    response.Success  = true;
                }
            } catch (Exception ex) {
                throw ex;
            }

            return(response);
        }
コード例 #2
0
ファイル: UserService.cs プロジェクト: kuunal/BookStoreCore
        public async Task <int> ResetPassword(string password, string token)
        {
            ClaimsPrincipal claims = _tokenManager.Decode(token, Encoding.ASCII.GetBytes(_configuration.GetSection("Jwt")["ResetPasswordSecretKey"]));
            var             claim  = claims.Claims.ToList();
            string          email  = claim[1].Value;

            var(user, _) = await _repository.AuthenticateUser(email);

            if (await _caching.GetCachedResponseAsync(token) != null)
            {
                await _caching.RemoveCacheByKeyAsync(token);

                return(await _repository.ResetPassword(user, BCrypt.Net.BCrypt.HashPassword(password)));
            }
            return(0);
        }
コード例 #3
0
        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));
        }
コード例 #4
0
        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
            });
        }
コード例 #5
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var cachedConfigurationProvider = context.ServiceProvider.GetService <IOptionsMonitor <FilterCachedConfiguration> >();
            var configCache = context.GetCacheConfigurationByMethodName(cachedConfigurationProvider.CurrentValue);

            var methodReturnType = context.ProxyMethod.ReturnType;

            if (
                configCache == null ||
                methodReturnType == typeof(void) ||
                methodReturnType == typeof(Task) ||
                methodReturnType == typeof(ValueTask)
                )
            {
                await next(context);

                return;
            }

            if (string.IsNullOrWhiteSpace(CacheName))
            {
                CacheName = context.GetGenerateKeyByMethodNameAndValues();
            }

            ResponseCacheService = context.ServiceProvider.GetService <IResponseCacheService>();

            var returnType = context.IsAsync() ? methodReturnType.GenericTypeArguments.FirstOrDefault() : methodReturnType;

            var cachedValue = await ResponseCacheService.GetCachedResponseAsync(CacheName, returnType);

            if (cachedValue != null)
            {
                context.SetReturnType(methodReturnType, cachedValue);
                return;
            }

            await next(context);

            await ResponseCacheService
            .SetCacheResponseAsync(
                CacheName,
                await context.GetReturnValueAsync(),
                TimeSpan.FromSeconds(configCache.TimeToLiveSeconds ?? TimeToLiveSeconds)
                );
        }
コード例 #6
0
        public async Task <GetUserQueryResponse> Handle(GetUserQuery query, CancellationToken cancellation)
        {
            var users = new List <User> ();

            try {
                var cachedValue = await _responseCacheService.GetCachedResponseAsync("users");

                if (cachedValue != null)
                {
                    users = JsonConvert.DeserializeObject <List <User> > (cachedValue);
                }
            } catch (Exception ex) {
                return(new GetUserQueryResponse()
                {
                    Message = "Ocorreu um erro inesperado.", Success = false
                });
            }

            var loggedUser = users.FirstOrDefault(x => x.Email.Equals(query.Email) && x.Password.Equals(query.Password));

            if (loggedUser == null)
            {
                return new GetUserQueryResponse()
                       {
                           Message = "Senha ou email invalido", Success = false
                       }
            }
            ;

            try {
                loggedUser.Token = WindowsIdentity.GetCurrent().Token.ToString();
            } catch {
                loggedUser.Token = System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(loggedUser.Email + loggedUser.Name));
            }
            loggedUser.Role = "user";

            _responseCacheService.ManageTokenAsync(loggedUser.Token, loggedUser).ConfigureAwait(false);

            return(new GetUserQueryResponse()
            {
                Message = "", Success = true, User = loggedUser
            });;
        }
    }
コード例 #7
0
        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
            });
        }
    }
コード例 #8
0
        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));
            }
        }
コード例 #9
0
ファイル: SearchService.cs プロジェクト: eliranbl/Ewave_Test
 /// <summary>
 /// get search engine results from cache
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 private async Task <List <SearchEngineResult> > GetDataFromCache(string key)
 {
     return(await _cacheService.GetCachedResponseAsync <List <SearchEngineResult> >(key));
 }
コード例 #10
0
        /// <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);
        }
コード例 #11
0
        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
                }
                           ));
            }
        }
コード例 #12
0
        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));
                }
            }
        }
コード例 #13
0
        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
            });
        }