public async Task <bool> ExecuteCommandAsync(Command command, CancellationToken cancellationToken) { if (command == null) { throw new ArgumentNullException(nameof(command)); } var result = false; try { var policyresult = await retryPolicy.ExecuteAndCaptureAsync <bool>(async() => { using (var sqlConnection = await OpenSqlConnectionAsync(cancellationToken)) using (var sqlCommand = CreateSqlCommand(sqlConnection, command)) { await sqlCommand.ExecuteNonQueryAsync(cancellationToken); return(true); } }); result = policyresult.Result; } catch (Exception) { } return(result); }
public static async Task <WebDirectory> ParseFtpAsync(string processor, WebDirectory webDirectory) { Context pollyContext = new Context { { "Processor", string.Empty }, { "WebDirectory", webDirectory } }; return((await RetryPolicy.ExecuteAndCaptureAsync(ctx => ParseFtpInnerAsync(processor, webDirectory), pollyContext)).Result); }
public static async Task <WebDirectory> ParseFtpAsync(string processor, WebDirectory webDirectory, string username, string password) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(TimeSpan.FromMinutes(5)); Context pollyContext = new Context { { "Processor", processor }, { "WebDirectory", webDirectory }, { "CancellationTokenSource", cancellationTokenSource } }; return((await RetryPolicyNew.ExecuteAndCaptureAsync(async(context, token) => { return await ParseFtpInnerAsync(processor, webDirectory, username, password, cancellationTokenSource.Token); }, pollyContext, cancellationTokenSource.Token)).Result); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // Request an access token if we don't have one yet or if it has expired. if (!_accessTokenAccessor.ValidateAccessToken()) { _logger.LogDebug("No valid access token; Authenticating"); await AuthenticateAsync(); } // 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(() => { request.Headers.Authorization = new AuthenticationHeaderValue(_accessTokenAccessor.Token.TokenType, _accessTokenAccessor.Token.Token); if (!request.Headers.Contains("x-dw-client-id")) { request.Headers.Add("x-dw-client-id", _accessTokenAccessor.Token.ClientId); } return(base.SendAsync(request, cancellationToken)); }); return(result.Outcome == OutcomeType.Failure ? result.FinalHandledResult : result.Result); }
public async Task ValidateLicenseAsync(string licenseKey, string moduleInstanceName, string hostName, string hubName, DateTime utcNow, CancellationToken cancellationToken) { var requestNonce = Guid.NewGuid().ToString("D"); var formValues = new Dictionary <string, string> { ["moduleAssembly"] = moduleAssemblyFullName, ["nonce"] = requestNonce, ["key"] = licenseKey }; var licenseJwsResult = await exponentialBackoffPolicy.ExecuteAndCaptureAsync(async (innerCancellationToken) => { var response = await httpClient.PostAsync("", new FormUrlEncodedContent(formValues), innerCancellationToken); response.EnsureSuccessStatusCode(); var jws = await response.Content.ReadAsStringAsync(); return(jws); }, cancellationToken); if (licenseJwsResult.Outcome != OutcomeType.Successful) { throw licenseJwsResult.FinalException; } JwsLicenseValidation.Validate(licenseJwsResult.Result, issuerPublicKey, expectedTokenId: requestNonce, validAudience: moduleAssemblyFullName, validIssuer: licensingServerUrl, utcNow, moduleInstanceName, hostName, hubName); }
public async Task <EventHistoryResponse> GetEventsHistoryAsync(string token, int eventId) { var result = await _retryPolicy.ExecuteAndCaptureAsync(() => _betsApiClient.GetEventsHistoryAsync(token, eventId)); return(result.Result); }
private async Task <FileStream> GetExclusiveFileStream() { var getStream = await _retryPolicy .ExecuteAndCaptureAsync(() => Task.FromResult(new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))); var stream = getStream.Result; return(stream); }
public static async Task <long?> GetUrlFileSizeAsync(this HttpClient httpClient, string url) { try { Context pollyContext = new Context { { "Url", url } }; return((await RetryPolicy.ExecuteAndCaptureAsync(ctx => GetUrlFileSizeInnerAsync(httpClient, url), pollyContext)).Result); } catch (Exception ex) { Logger.Error(ex, $"Error retrieving filesize for Url: '{url}'"); return(null); } }
public async Task <User> GetUserInformation(string username) { var request = new DefaultRequest() { Query = GithubOptions.UserAllTimeInformation, OperationName = GithubOptions.OperationName, Variables = new { login = username } }; var response = await _policy.ExecuteAndCaptureAsync(() => _client.PostAsJsonAsync("graphql", request, GithubOptions.DefaultJson)); if (response.Outcome != OutcomeType.Successful || !response.Result.IsSuccessStatusCode) { return(null); } var userInfo = await JsonSerializer.DeserializeAsync <DefaultResponse <UserData> >(await response.Result.Content.ReadAsStreamAsync(), GithubOptions.DefaultJson); return(userInfo?.Data.User); }
public async Task <CCGEntity> Get(string postcode) { var partitionKey = postcode?.Length > 1 ? postcode.Substring(0, 2).Trim() : "emptypostcode"; var retrieveOperation = TableOperation.Retrieve <CCGEntity>(partitionKey, postcode); // Use Polly to retry to catch transient Storage errors var res = await retryIfException.ExecuteAndCaptureAsync(() => _table.ExecuteAsync(retrieveOperation)); var retrievedResult = res.Result; return((CCGEntity)retrievedResult.Result); }
public async Task <PolicyResult <bool> > GroupExistsAsync(Guid objectId, Guid runId) { // make this fresh every time because the lambda has to capture the run ID _graphRetryPolicy = Policy.Handle <SocketException>().WaitAndRetryAsync(NumberOfGraphRetries, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), onRetry: async(ex, count) => { await _log.LogMessageAsync(new LogMessage { Message = $"Got a transient SocketException. Retrying. This was try {count} out of {NumberOfGraphRetries}.\n" + ex.ToString(), RunId = runId }); }); return(await _graphRetryPolicy.ExecuteAndCaptureAsync(() => _graphGroupRepository.GroupExists(objectId))); }
public async Task <IRestResponse> Execute(Uri uri, dynamic data, Data authentication) { IRestRequest request = new RestRequest(uri, Method.POST); request.AddHeader("token", JsonSerializer.Serialize(authentication)); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", JsonSerializer.Serialize(data), ParameterType.RequestBody); var result = await _result.ExecuteAndCaptureAsync(() => _restClient.ExecuteAsync(request)) .ConfigureAwait(false); return(result.Result); }
private async Task <HostSource> LoadHostFileAsync(string url) { var response = await _policy.ExecuteAndCaptureAsync(() => _httpClient.GetAsync(url)); if (response.Outcome == OutcomeType.Failure) { return(null); } var content = await response.Result.Content.ReadAsStringAsync(); var rawHosts = HostParser.Parse(content); return(new HostSource { Hosts = rawHosts }); }
private async Task <List <STPEntity> > LoadEntitiesIntoMemory() { TableContinuationToken token = null; var entities = new List <STPEntity>(); do { // Use Polly to retry to catch transient Storage errors TableQuery <STPEntity> partitionQuery = new TableQuery <STPEntity>().Where( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, _partitionKey)); var res = await retryIfException.ExecuteAndCaptureAsync(() => _table.ExecuteQuerySegmentedAsync(partitionQuery, token)); var queryResult = res.Result; entities.AddRange(queryResult.Results); token = queryResult.ContinuationToken; } while (token != null); return(entities); }
public async Task <Result <string> > Handle(GetRandomNumberCommand request, CancellationToken cancellationToken) { using var client = _httpClientFactory.CreateClient(); var policyResult = await _polly.ExecuteAndCaptureAsync(async() => await client.GetAsync(RandomStringApiUrl, cancellationToken)); if (policyResult.Outcome == Polly.OutcomeType.Successful) { var httpResponse = policyResult.Result; if (httpResponse.IsSuccessStatusCode) { var randomString = await httpResponse.Content.ReadAsStringAsync(); return(Result.Success <string>(randomString)); } else { return(Result.Failure <string>($"Failed to call {RandomStringApiUrl} : {httpResponse.StatusCode} ; {httpResponse.ReasonPhrase}")); } } else { return(Result.Failure <string>($"Polly Retry Failed {policyResult.FinalException.GetBaseException().Message}")); } }
/// <summary> /// Helper method to GET data from a RESTful Web API /// </summary> /// <typeparam name="T">Result type</typeparam> /// <param name="url">URL of the service</param> /// <returns>Async result returned from the Web API</returns> private async Task <T> GetFromServiceAsync <T>(string url) { var resultString = await RetryPolicy.ExecuteAndCaptureAsync(async() => await HttpClient.GetStringAsync(url)); return(JsonConvert.DeserializeObject <T>(resultString.Result)); }