private async Task <PolicyResult <IEnumerable <Merchant> > > GetMerchants(int amount)
 {
     return(await merchantPolicy.ExecuteAndCaptureAsync(async (context) =>
     {
         return await merchantService.GetMerchantsAsync(amount);
     }, new Context("MerchantApi")));
 }
 private async Task <PolicyResult <Promotion> > GetSinglePromotion(int id)
 {
     return(await sidePromotionPolicy.ExecuteAndCaptureAsync(async (context) =>
     {
         return await promotionService.GetPromotionByIdAsync(id);
     }, new Context($"PromoApi{id}")));
 }
Exemplo n.º 3
0
        /// <summary>
        /// request with specific http method
        /// </summary>
        /// <param name="method">http verb</param>
        /// <returns>operation result with data</returns>
        public async Task <OperationResult <T> > ExecuteAsync <T>(Method method)
        {
            try
            {
                _request.Method = method;
                var retryResult = await _retryPolicy.ExecuteAndCaptureAsync(async() =>
                {
                    var response = await _client.ExecuteTaskAsync <T>(_request);
                    if (SuccessStatusCodes.Contains(response.StatusCode))
                    {
                        try
                        {
                            if (response.Data == null && !string.IsNullOrEmpty(response.Content))
                            {
                                return(JsonConvert.DeserializeObject <T>(response.Content));
                            }
                        }
                        catch { }
                        return(response.Data);
                    }
                    else
                    {
                        throw new Exception($"{method} {_client.BaseUrl} failed with {response.StatusCode}: {response.Content}");
                    }
                });

                if (retryResult.Outcome == OutcomeType.Successful)
                {
                    return(new OperationResult <T> {
                        Success = true, Data = retryResult.Result
                    });
                }
                else
                {
                    return(new OperationResult <T> {
                        Success = false, Message = retryResult.FinalException.Message
                    });
                }
            }
            catch (Exception ex)
            {
                return(new OperationResult <T> {
                    Success = false, Message = ex.Message, Exception = ex
                });
            }
        }
 private async Task <PolicyResult <Promotion> > GetMainPromotion()
 {
     return(await mainPromotionPolicy
            .ExecuteAndCaptureAsync(async (context) =>
     {
         return await promotionService.GetPromotionByIdAsync(1);
     }, new Context("PromoApi1")));
 }
Exemplo n.º 5
0
        public async Task <NewDeckOfCardsCommandResult> Handle(NewDeckOfCardsCommand command, CancellationToken cancellationToken)
        {
            var commandResult = new NewDeckOfCardsCommandResult();

            try
            {
                IAsyncPolicy <int> policy = _policyRegistry.Get <IAsyncPolicy <int> >("DbCommand");
                var policyResult          = await policy
                                            .ExecuteAndCaptureAsync(async() =>
                {
                    using (var session = _db.OpenAsyncSession())
                    {
                        // get all Card Templates - this ultimately defines what 'standard' cards really are
                        session.Advanced.DocumentStore.AggressivelyCache();
                        QueryStatistics queryStats;
                        var allCardTemplatesQuery = session
                                                    .Query <CardTemplate>()
                                                    .Statistics(out queryStats);
                        List <CardTemplate> cardTemplates = await allCardTemplatesQuery.ToListAsync();

                        // call into the Deck Aggregate to create us a deck entity object
                        var deck = Deck.Standard52CardDeck(cardTemplates);

                        // persist
                        await session.StoreAsync(deck);
                        await session.SaveChangesAsync();
                        commandResult.Deck = deck;
                        return(1);
                    }
                });

                if (policyResult.Outcome == OutcomeType.Failure)
                {
                    return(ServiceUnavailableCommandResult());
                }
                else
                {
                    commandResult.ResultStatus = CQRS.CommandResultStatus.SuccessfullyProcessed;
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception caught and logged.");
                commandResult.ResultStatus = CQRS.CommandResultStatus.CriticalError;
            }
            finally
            {
                // - will remove when logging and validation pipelines are completed in the Dispatch layer
            }
            return(commandResult);
        }
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_authenticationHeader == null)
            {
                Authenticate(false);
            }

            // Try to perform the request, re-authenticating gracefully if the call fails due to an expired or revoked access token.
            var result = await _policy.ExecuteAndCaptureAsync(async() =>
            {
                request.Headers.Authorization = _authenticationHeader;
                return(await base.SendAsync(request, cancellationToken));
            });

            return(result.Result ?? result.FinalHandledResult);
        }
        /// <summary>
        /// Opens the asynchronous.
        /// </summary>
        /// <param name="policy">The policy.</param>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public async Task <PolicyResult> CaptureOpenAsync(IAsyncPolicy policy, CancellationToken token = default)
        {
            //Check for null
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }
            //Check if cancelled
            if (token.IsCancellationRequested == true)
            {
                token.ThrowIfCancellationRequested();
            }

            //Return thsi back to the caller
            return(await policy.ExecuteAndCaptureAsync(async (token) => await ExecuteSQL.Connection.OpenAsync(token), token).ConfigureAwait(false));
        }
        /// <summary>
        /// Utility method for executing an Ad-Hoc query or stored procedure without a transaction
        /// </summary>
        /// <param name="policy"></param>
        /// <param name="token">Structure that propogates a notification that an operation should be cancelled</param>
        /// <param name="query">The query command text or name of stored procedure to execute against the data store</param>
        /// <returns>Returns the number of rows affected by this query as a <see cref="Task{Int32}"/></returns>
        public async Task <PolicyResult <int> > CaptureNonQueryAsync(string query, IAsyncPolicy policy, CancellationToken token = default)
        {
            //Check for null
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }
            //Check if cancelled
            if (token.IsCancellationRequested == true)
            {
                token.ThrowIfCancellationRequested();
            }

            //Return this back to the caller
            return(await policy.ExecuteAndCaptureAsync(async (token) => await ExecuteSQL.ExecuteNonQueryAsync(QueryCommandType, query, token), token).ConfigureAwait(false));
        }
        /// <summary>
        /// Captures the get data object enumerable asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query">The query.</param>
        /// <param name="policy">The policy.</param>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">policy</exception>
        public async Task <PolicyResult <List <T> > > CaptureGetDataObjectEnumerableAsync <T>(string query, IAsyncPolicy policy, CancellationToken token = default) where T : class
        {
            //Check for null
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }
            //Check if cancelled
            if (token.IsCancellationRequested == true)
            {
                token.ThrowIfCancellationRequested();
            }

            //Return this back to the caller
            return(await policy.ExecuteAndCaptureAsync(async (token) => await ExecuteSQL.GetDataObjectListAsync <T>(QueryCommandType, query, token), token).ConfigureAwait(false));
        }
Exemplo n.º 10
0
        /// <inheritdoc />
        public async Task <TOutput> HandleAsync(TCommand command)
        {
            Guard.NotNull(() => command, command);
            if (_policy == null)
            {
                _policies.Registry.TryGet(TransportPolicyDefinitions.RetryCommandHandlerAsync, out _policy);
            }
            if (_policy != null)
            {
                var result = await _policy.ExecuteAndCaptureAsync(() => _decorated.HandleAsync(command)).ConfigureAwait(false);

                if (result.FinalException != null)
                {
                    throw result.FinalException;
                }
                return(result.Result);
            }
            return(await _decorated.HandleAsync(command).ConfigureAwait(false));
        }
Exemplo n.º 11
0
        public async Task InvokeAsync(TContext context, RequestDelegate <TContext> next)
        {
            var executeNext = false;

            var result = await _policy.ExecuteAndCaptureAsync(() => _middleware.InvokeAsync(context, (c) =>
            {
                executeNext = true;
                return(Task.CompletedTask);
            }));

            if (result.FinalException != null)
            {
                throw result.FinalException;
            }

            if (executeNext)
            {
                await next(context);
            }
        }
        private async Task <HttpResponseMessage> SendMessage(Func <HttpRequestMessage> createMessage)
        {
            var attempts = 0;

            var policyResult = await _retryPolicy.ExecuteAndCaptureAsync(
                async() => {
                attempts++;
                var message = createMessage();
                return(await _client.SendAsync(message));
            }
                );

            var result = policyResult.FinalHandledResult ?? policyResult.Result;

            if (result == null)
            {
                SyncLog.LogEvent(EventType.ERROR, "KenticoKontentPublishing", "REQUESTFAIL", $"Retry attempts: {attempts}");
            }

            return(result);
        }
Exemplo n.º 13
0
            static async Task UploadPackageAsync(PackageFile packageFile,
                                                 NuGetVersion nuGetVersion, string token, IAsyncPolicy <IRestResponse> retryPolicy, CancellationToken cancellationToken)
            {
                if (packageFile == null)
                {
                    throw new ArgumentNullException(nameof(packageFile));
                }

                cancellationToken.ThrowIfCancellationRequested();

                NuGetVersion packageVersion;

                var shouldRewriteNuspec = NuGetUtilities.ShouldRewriteNupkg(packageFile, nuGetVersion);

                if (shouldRewriteNuspec)
                {
                    NuGetUtilities.RewriteNupkg(packageFile, nuGetVersion);

                    var manifest = NuGetUtilities.ReadNupkgManifest(packageFile.FilenameAbsolutePath);
                    packageVersion = manifest.Metadata.Version;
                }
                else
                {
                    var manifest = NuGetUtilities.ReadNupkgManifest(packageFile.FilenameAbsolutePath);
                    packageVersion = manifest.Metadata.Version;
                }

                await using var packageStream = packageFile.FilenameAbsolutePath.ReadSharedToStream();

                Console.WriteLine($"[{packageFile.Filename}]: " +
                                  $"Repository url: {packageFile.RepositoryUrl}. " +
                                  $"Version: {packageVersion}. " +
                                  $"Size: {packageStream.Length} bytes. ");

                await retryPolicy.ExecuteAndCaptureAsync(retryCancellationToken =>
                                                         UploadPackageAsyncImpl(packageFile, packageStream, token, retryCancellationToken), cancellationToken);
            }
        public async Task <QueryResult <TResult> > ExecuteQuery <TResult>(IAsyncPolicy policy, Func <Task <TResult> > queryFunction)
        {
            try
            {
                var policyResult = await policy.ExecuteAndCaptureAsync(queryFunction);

                if (policyResult.Outcome == OutcomeType.Successful)
                {
                    return(new QueryResult <TResult>(policyResult.Result));
                }
                else
                {
                    logger.LogError(policyResult.FinalException, "An error occurred while attempted to execute the query.");

                    return(new QueryResult <TResult>(policyResult.FinalException));
                }
            }
            catch (Exception exc)
            {
                logger.LogError(exc, "An error occurred while attempted to execute the query.");

                return(new QueryResult <TResult>(exc));
            }
        }
 /// <summary>
 /// Captures the get data reader asynchronous.
 /// </summary>
 /// <param name="query">The query.</param>
 /// <param name="policy">The policy.</param>
 /// <param name="behavior">The behavior.</param>
 /// <param name="transact">The transact.</param>
 /// <param name="token">The token.</param>
 /// <returns></returns>
 public async Task <PolicyResult <DbDataReader> > CaptureGetDataReaderAsync(string query, IAsyncPolicy policy, CommandBehavior behavior = CommandBehavior.Default, DbTransaction transact = null, CancellationToken token = default)
 {
     return(await policy.ExecuteAndCaptureAsync(async (token) => await ExecuteSQL.GetDbDataReaderAsync(QueryCommandType, query, token, behavior, transact), token).ConfigureAwait(false));
 }