Beispiel #1
0
        /// <inheritdoc />
        public async Task <IEnumerable <StatisticsResult <PlayerInnings> > > ReadPlayerInnings(StatisticsFilter filter, StatisticsSortOrder sortOrder)
        {
            filter = filter ?? new StatisticsFilter();
            var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(CacheConstants.StatisticsPolicy);

            return(await cachePolicy.ExecuteAsync(async context => await _statisticsDataSource.ReadPlayerInnings(filter, sortOrder).ConfigureAwait(false), new Context(nameof(ReadPlayerInnings) + _statisticsFilterSerializer.Serialize(filter) + sortOrder.ToString())));
        }
        /// <inheritdoc />
        public async Task <IEnumerable <StatisticsResult <BestStatistic> > > ReadBestBattingAverage(StatisticsFilter filter)
        {
            filter = filter ?? new StatisticsFilter();
            var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(CacheConstants.StatisticsPolicy);

            return(await cachePolicy.ExecuteAsync(async context => await _statisticsDataSource.ReadBestBattingAverage(filter).ConfigureAwait(false), new Context(nameof(ReadBestBattingAverage) + _statisticsFilterSerializer.Serialize(filter))));
        }
Beispiel #3
0
        public async Task <BattingStatistics> ReadBattingStatistics(StatisticsFilter filter)
        {
            filter = filter ?? new StatisticsFilter();
            var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(CacheConstants.StatisticsPolicy);

            return(await cachePolicy.ExecuteAsync(async context => await _playerSummaryStatisticsDataSource.ReadBattingStatistics(filter).ConfigureAwait(false), new Context(nameof(ReadBattingStatistics) + _statisticsFilterSerializer.Serialize(filter))));
        }
Beispiel #4
0
        public async Task ToArms(
            [Option(ShortName = "r")] RetryPolicyKey retryPolicyKey     = RetryPolicyKey.NoRetry,
            [Option(ShortName = "c")] CachePolicyKey cachePolicyKey     = CachePolicyKey.NoCache,
            [Option(ShortName = "t")] TimeoutPolicyKey timeoutPolicyKey = TimeoutPolicyKey.NoTimeout,
            double?latitude = null, double?longitude = null)
        {
            var retryPolicy = _policyRegistry.Get <IAsyncPolicy>(retryPolicyKey.ToString());
            var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(cachePolicyKey.ToString());
            var meteoPolicy = Policy.WrapAsync(cachePolicy, retryPolicy);

            await _battery.ToArms(timeoutPolicyKey);

            var coords = new Coordinate(latitude ?? DefaultLatitude, longitude ?? DefaultLongitude);

            var meteoTask        = meteoPolicy.ExecuteAndCaptureAsync(_ => GetMeteo(coords), new Context("Get meteo"));
            var registrationTask = retryPolicy.ExecuteAndCaptureAsync(_ => RegisterAsync(coords), new Context("Register unit"));
            await Task.WhenAll(registrationTask, meteoTask);

            var registrationPolicyCapture = registrationTask.Result;
            var meteoPolicyCapture        = meteoTask.Result;

            if (registrationPolicyCapture.Outcome == OutcomeType.Failure)
            {
                _console.Out.WriteLine($"Register unit failed: {registrationPolicyCapture.FinalException.Message}");
            }
            else
            {
                _mainFiringDirection = registrationPolicyCapture.Result.MainFiringDirection;
            }

            if (meteoPolicyCapture.Outcome == OutcomeType.Failure)
            {
                _console.Out.WriteLine($"Get meteo failed: {meteoPolicyCapture.FinalException.Message}");
            }
        }
Beispiel #5
0
 private IAsyncPolicy <HttpResponseMessage> PolicySelector(IReadOnlyPolicyRegistry <string> policyRegistry, HttpRequestMessage request)
 {
     if (request.Method == HttpMethod.Get)
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleRetry"));
     }
     return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOp"));
 }
Beispiel #6
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var policyWrap = Policy.WrapAsync(
                _policyRegistry.Get <IAsyncPolicy>(CommandProcessor.CIRCUITBREAKERASYNC),
                _policyRegistry.Get <IAsyncPolicy>(CommandProcessor.RETRYPOLICYASYNC)
                );

            await policyWrap.ExecuteAsync(async() => { await _streamReader.ReadStream(stoppingToken); });
        }
        public HomeController(IMerchantService merchantService, IPromotionService promotionService, IReadOnlyPolicyRegistry <string> policyRegistry)
        {
            this.merchantService  = merchantService;
            this.promotionService = promotionService;

            mainPromotionPolicy = policyRegistry.Get <IAsyncPolicy <Promotion> >("PromoFallback");
            sidePromotionPolicy = policyRegistry.Get <IAsyncPolicy>("Promo");
            merchantPolicy      = policyRegistry.Get <IAsyncPolicy>("Merchant");
        }
Beispiel #8
0
        public IMDbApiService(ILogger <IMDbApiService> logger, Secrets.IMDbApi secrets, HttpClient httpClient, IReadOnlyPolicyRegistry <string> policyRegistry)
        {
            this.logger     = logger;
            this.secrets    = secrets;
            this.httpClient = httpClient;

            this.searchApiPolicy  = policyRegistry.Get <IAsyncPolicy <SearchResult> >(SearchPolicyKey);
            this.ratingsApiPolicy = policyRegistry.Get <IAsyncPolicy <RatingsResult> >(RatingsPolicyKey);
        }
Beispiel #9
0
        private static IAsyncPolicy <HttpResponseMessage> SelectPolicy(IReadOnlyPolicyRegistry <string> policyRegistry, HttpRequestMessage httpRequestMessage)
        {
            if (httpRequestMessage.Method == HttpMethod.Get)
            {
                return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleRetryPolicy"));
            }

            if (httpRequestMessage.Method != HttpMethod.Post)
            {
                return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("WaitRetryPolicy"));
            }

            return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy"));
        }
Beispiel #10
0
        /// <inheritdoc />
        public async Task <int> ReadTotalMatchLocations(MatchLocationFilter filter)
        {
            filter = filter ?? new MatchLocationFilter();

            if (CacheDisabled())
            {
                return(await _matchLocationDataSource.ReadTotalMatchLocations(filter).ConfigureAwait(false));
            }
            else
            {
                var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(CacheConstants.MatchLocationsPolicy);
                var cacheKey    = CacheConstants.MatchLocationsCacheKeyPrefix + nameof(ReadTotalMatchLocations) + _matchLocationFilterSerializer.Serialize(filter);
                return(await cachePolicy.ExecuteAsync(async context => await _matchLocationDataSource.ReadTotalMatchLocations(filter).ConfigureAwait(false), new Context(cacheKey)));
            }
        }
Beispiel #11
0
        /// <inheritdoc />
        public async Task <List <TeamListing> > ReadTeamListings(TeamListingFilter filter)
        {
            filter = filter ?? new TeamListingFilter();

            if (CacheDisabled())
            {
                return(await _teamListingDataSource.ReadTeamListings(filter).ConfigureAwait(false));
            }
            else
            {
                var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(CacheConstants.TeamsPolicy);
                var cacheKey    = CacheConstants.TeamListingsCacheKeyPrefix + nameof(ReadTeamListings) + _teamListingFilterSerializer.Serialize(filter);
                return(await cachePolicy.ExecuteAsync(async context => await _teamListingDataSource.ReadTeamListings(filter).ConfigureAwait(false), new Context(cacheKey)));
            }
        }
Beispiel #12
0
        public async Task <string> GetAsync()
        {
            var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.RetryWithLogging)
                              ?? Policy.NoOpAsync <HttpResponseMessage>();

            var context = new Context(
                $"{ContextNames.Logger}-{Guid.NewGuid()}",
                new Dictionary <string, object>
            {
                { ContextNames.Logger, _logger }
            });

            var response = await retryPolicy.ExecuteAsync(ctx => _client.GetAsync("/ds"), context);

            return(response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : "Error");
        }
Beispiel #13
0
        public WikipediaClient(HttpClient client, IReadOnlyPolicyRegistry <string> policyRegistry)
        {
            client.BaseAddress = new Uri("https://en.wikipedia.org");

            _client      = client;
            _cachePolicy = policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("WikipediaCachePolicy");
        }
 public RemoteStoreHttpClient(
     [NotNull] HttpClient client,
     IReadOnlyPolicyRegistry <string> policyRegistry)
 {
     _client      = client;
     _cachePolicy = policyRegistry.Get <IAsyncPolicy <TTenantInfo> >(typeof(TTenantInfo).Name);
 }
Beispiel #15
0
        private async Task <HttpResponseMessage> PostToApi(dynamic data, string apiUrl)
        {
            var client   = new HttpClient();
            var byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));

            var content = new ByteArrayContent(byteData);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry)
                              ?? Policy.NoOpAsync <HttpResponseMessage>();

            var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object>
            {
                { PolicyContextItems.Logger, _logger }
            });

            var retries = 0;
            // ReSharper disable once AccessToDisposedClosure
            var response = await retryPolicy.ExecuteAsync((ctx) =>
            {
                client.DefaultRequestHeaders.Remove("retries");
                client.DefaultRequestHeaders.Add("retries", new [] { retries++.ToString() });
                return(client.PostAsync(apiUrl, content));
            }, context);

            content.Dispose();

            return(response);
        }
Beispiel #16
0
        public async Task <IActionResult> FoodRestriction(UserServiceModel request)
        {
            try
            {
                var client      = new HttpClient();
                var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry)
                                  ?? Policy.NoOpAsync <HttpResponseMessage>();

                var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object>
                {
                    { PolicyContextItems.Logger, _logger }, { "UserServiceModel", request }
                });


                var response = await retryPolicy.ExecuteAsync(async() =>
                {
                    return(await UpsertFoodRestrictions(request));
                });


                return(Ok());
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
Beispiel #17
0
 public InserirFuncionarioGoogleCommandHandler(IMediator mediator, IConfiguration configuration, IReadOnlyPolicyRegistry <string> registry, VariaveisGlobaisOptions variaveisGlobais)
     : base(variaveisGlobais)
 {
     this.mediator      = mediator ?? throw new ArgumentNullException(nameof(mediator));
     this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
     this.policy        = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyGoogleSync);
 }
        public async Task <HttpResponseMessage> PublisherProductionAreaChanged()
        {
            //Teste para Polly
            var client = new HttpClient();

            var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry)
                              ?? Policy.NoOpAsync <HttpResponseMessage>();

            var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object>
            {
                { PolicyContextItems.Logger, _logger }, { "url", apiUrl }
            });

            var retries = 0;

            var response = await retryPolicy.ExecuteAsync((ctx) =>
            {
                client.DefaultRequestHeaders.Remove("retries");
                client.DefaultRequestHeaders.Add("retries", new[] { retries++.ToString() });

                var baseUrl = _baseUri;
                if (string.IsNullOrWhiteSpace(baseUrl))
                {
                    var uri = Request.GetUri();
                    baseUrl = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
                }

                var isValid = Uri.IsWellFormedUriString(apiUrl, UriKind.Absolute);

                return(client.GetAsync($"{baseUrl}{apiUrl}/PublisherProductionAreaChanged"));
            }, context);

            return(response);
        }
Beispiel #19
0
        private async Task <HttpResponseMessage> PostToApi(dynamic data, string apiUrl)
        {
            var client   = new HttpClient();
            var byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));

            var content = new ByteArrayContent(byteData);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry)
                              ?? Policy.NoOpAsync <HttpResponseMessage>();

            var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object>
            {
                { PolicyContextItems.Logger, _logger }, { "url", apiUrl }
            });

            var retries = 0;
            // ReSharper disable once AccessToDisposedClosure
            var response = await retryPolicy.ExecuteAsync((ctx) =>
            {
                client.DefaultRequestHeaders.Remove("retries");
                client.DefaultRequestHeaders.Add("retries", new [] { retries++.ToString() });

                var uri     = Request.GetUri();
                var baseUrl = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
                var isValid = Uri.IsWellFormedUriString(apiUrl, UriKind.Absolute);

                return(client.PostAsync(isValid ? apiUrl : $"{baseUrl}/api/Face", content));
            }, context);

            content.Dispose();

            return(response);
        }
        public JsonPlaceholderClient(HttpClient httpClient, IReadOnlyPolicyRegistry <string> policyRegistry)
        {
            _httpClient = httpClient;

            // Resolve the caching policy to be used with this client
            _cachePolicy = policyRegistry.Get <AsyncCachePolicy <string> >("jsonPlaceHolderClientCachePolicy");
        }
Beispiel #21
0
        public async Task <ActionResult <string> > Get()
        {
            try
            {
                var httpClient  = _clientFactory.CreateClient();
                var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.BasicRetry)
                                  ?? Policy.NoOpAsync <HttpResponseMessage>();

                var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary <string, object>
                {
                    { PolicyContextItems.Logger, _logger }
                });

                var response = await retryPolicy.ExecuteAsync(ctx =>
                                                              httpClient.GetAsync("http://example.com/returns-404-statuscode"), context);

                var result = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : "Error";

                return(Ok(result));
            }
            catch (Exception)
            {
                return(NotFound());
            }
        }
Beispiel #22
0
 public InativarAlunoGoogleCommandHandler(IMediator mediator,
                                          IReadOnlyPolicyRegistry <string> registry,
                                          VariaveisGlobaisOptions variaveisGlobais) : base(variaveisGlobais)
 {
     this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
     this.policy   = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyGoogleSync);
 }
Beispiel #23
0
 private IAsyncPolicy <HttpResponseMessage> PolicySelector(IReadOnlyPolicyRegistry <string> policyRegistry,
                                                           HttpRequestMessage httpRequestMessage)
 {
     if (httpRequestMessage.RequestUri.LocalPath.StartsWith("find"))
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleHttpRetryPolicy"));
     }
     else if (httpRequestMessage.RequestUri.LocalPath.StartsWith("create"))
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy"));
     }
     else
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleWaitAndRetryPolicy"));
     }
 }
Beispiel #24
0
 public ObterCursosGsaGoogleQueryHandler(IMediator mediator, IReadOnlyPolicyRegistry <string> registry, GsaSyncOptions gsaSyncOptions)
     : base()
 {
     this.mediator       = mediator ?? throw new ArgumentNullException(nameof(mediator));
     this.gsaSyncOptions = gsaSyncOptions;
     this.policy         = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyGoogleSync);
 }
        public WikiDataClient(HttpClient client, IReadOnlyPolicyRegistry <string> policyRegistry, ILogger <WikiDataClient> logger)
        {
            client.BaseAddress = new Uri("https://www.wikidata.org");

            this.Client      = client;
            this.cachePolicy = policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("WikiDataCachePolicy");
            this.logger      = logger;
        }
 private IAsyncPolicy <HttpResponseMessage> PolicySelector(
     IReadOnlyPolicyRegistry <string> policyRegistry,
     HttpRequestMessage httpRequestMessage)
 {
     if (httpRequestMessage.Method == HttpMethod.Get)
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleHttpRetryPolicy"));
     }
     else if (httpRequestMessage.Method == HttpMethod.Post)
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy"));
     }
     else
     {
         return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleWaitAndRetryPolicy"));
     }
 }
Beispiel #27
0
 public AbstractTratarFilaErrosUseCase(string filaErro, string filaProcesso, IConfiguration configuration, IMediator mediator, IReadOnlyPolicyRegistry <string> registry)
 {
     FilaErro       = filaErro;
     FilaProcesso   = filaProcesso;
     _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _mediator      = mediator ?? throw new ArgumentNullException(nameof(mediator));
     _policy        = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyPublicaFila);
 }
        /// <inheritdoc />
        public async Task <List <MatchListing> > ReadMatchListings(MatchFilter filter, MatchSortOrder sortOrder)
        {
            filter = filter ?? new MatchFilter();
            var cachePolicy = _policyRegistry.Get <IAsyncPolicy>(CacheConstants.MatchesPolicy);
            var cacheKey    = CacheConstants.MatchListingsCacheKeyPrefix + _matchFilterSerializer.Serialize(filter) + sortOrder.ToString();

            return(await cachePolicy.ExecuteAsync(async context => await _matchListingDataSource.ReadMatchListings(filter, sortOrder), new Context(cacheKey)));
        }
Beispiel #29
0
        public async Task ToArms(TimeoutPolicyKey policyKey)
        {
            var policy = _policyRegistry.Get <IAsyncPolicy>(policyKey.ToString());
            var watch  = new Stopwatch();

            watch.Start();

            await policy
            .ExecuteAndCaptureAsync(
                _ => Task.WhenAll(_howitzers.Select(howitzer => howitzer.ToArms())),
                new Context("Battery to arms."));

            _howitzers.RemoveAll(h => !h.IsOperational);

            watch.Stop();
            _console.Out.WriteLine($"Battery {Id} with {_howitzers.Count} howitzers reporting for duty within {watch.ElapsedMilliseconds} ms.");
        }
        /// <summary>
        /// Creates a policy to use for an HTTP request.
        /// </summary>
        /// <param name="registry">The policy registry to use.</param>
        /// <param name="request">The HTTP request to get the policy for.</param>
        /// <returns>
        /// The policy to use for <paramref name="request"/>.
        /// </returns>
        private static IAsyncPolicy <HttpResponseMessage> GetRequestPolicy(
            IReadOnlyPolicyRegistry <string> registry,
            HttpRequestMessage request)
        {
            string policyName = request.Method == HttpMethod.Get ? "ReadPolicy" : "WritePolicy";

            return(registry.Get <IAsyncPolicy <HttpResponseMessage> >(policyName));
        }