public async Task InitAsync()
        {
            var productsString = await RetryPolicy.ExecuteAndCaptureAsync(
                async() => await HttpClient.GetStringAsync("api/products"));

            var prods = await HttpClient.GetStringAsync("/api/products");

            Products = JsonSerializer.Deserialize <ObservableCollection <Product> >(prods);
        }
Beispiel #2
0
        public async Task InitAsync()
        {
            // Here, we use the NuGet package Polly to get failure handling and
            // retry. This is optional. If you want to implement it without retry,
            // that's fine, too. However, in practice you want retry policies in
            // case of shaky networks.
            var productsString = await RetryPolicy.ExecuteAndCaptureAsync(
                async() => await HttpClient.GetStringAsync("/api/Products"));

            Products = JsonSerializer.Deserialize <ObservableCollection <Product> >(productsString.Result);
        }
Beispiel #3
0
        public async Task DoAsync(CancellationToken token)
        {
            IsStarted = true;
            while (!token.IsCancellationRequested)
            {
                var result = await _policy.ExecuteAndCaptureAsync(_work, token);

                if (result.Outcome == OutcomeType.Successful)
                {
                    _callback?.Invoke();
                }
                else
                {
                    FinalException = result.FinalException;
                }

                if (_loopDelay == null)
                {
                    break;
                }
                else
                {
                    token.WaitHandle.WaitOne(_loopDelay.Value);
                }
            }

            IsFinished = true;
        }
Beispiel #4
0
        private static async Task UnShare()
        {
            Console.WriteLine("Searching for users ");
            var control = (await policy.ExecuteAndCaptureAsync(() => api.Search.SearchForAsync <User>("created>2019-07-20"))).Result;

            Console.WriteLine($"\nFixing {control.Count} users ");

            var pb     = new ProgressBar(PbStyle.DoubleLine, (int)control.Count);
            var errors = new Dictionary <User, string>();

            int updatedCount = 0;

            for (int i = 0; i < control.TotalPages; ++i)
            {
                var users = (await policy.ExecuteAndCaptureAsync(() => api.Search.SearchForAsync <User>("created>2019-07-20", page: i))).Result;

                foreach (var u in users.Results)
                {
                    pb.Next(u.Name);

                    if (u.SharedPhoneNumber == true)
                    {
                        try
                        {
                            u.SharedPhoneNumber = false;
                            await policy.ExecuteAsync(() => api.Users.UpdateUserAsync(u));

                            updatedCount++;
                        }
                        catch (Exception e)
                        {
                            errors[u] = Parse(e);
                        }
                    }
                }
            }

            pb.Refresh((int)control.Count, "");

            Console.WriteLine($"Updated {updatedCount} users.");
            if (errors.Any())
            {
                Console.WriteLine($"There were {errors.Count()} errors...");
                var erlist = string.Join(Environment.NewLine, errors.Select(x => $"{x.Key.Name}, {(x.Value)}"));
                Console.WriteLine(erlist);
            }
        }
Beispiel #5
0
        public async Task OnCheckout()
        {
            var dto = ReceiptLines.Select(b => new ReceiptLineDto
            {
                ProductId = b.ProductID,
                Amount    = b.Amount
            }).ToList();

            using (var content = new StringContent(JsonSerializer.Serialize(dto), Encoding.UTF8, "application/json"))
            {
                var response = await RetryPolicy.ExecuteAndCaptureAsync(async() => await _client.PostAsync("/api/receipts", content));

                response.Result.EnsureSuccessStatusCode();
            }

            ReceiptLines.Clear();
        }
        public async Task <IActionResult> Get(CancellationToken cancellationToken)
        {
            var policyResult = await _distributedBulkhead.ExecuteAndCaptureAsync(async (ct) =>
            {
                await Task.Delay(15000, ct);
                return(4);
            }, cancellationToken);

            return(Ok(policyResult.Outcome.ToString("G")));
        }
Beispiel #7
0
        private async Task OnCheckout()
        {
            // Turn all items in the basket into DTO objects
            var dto = Basket.Select(b => new ReceiptLineDto
            {
                ProductID = b.ProductID,
                Amount    = b.Amount
            }).ToList();

            // Create JSON content that can be sent using HTTP POST
            using (var content = new StringContent(JsonSerializer.Serialize(dto), Encoding.UTF8, "application/json"))
            {
                // Send the receipt to the backend
                var response = await RetryPolicy.ExecuteAndCaptureAsync(async() => await HttpClient.PostAsync("/api/receipts", content));

                // Throw exception if something went wrong
                response.Result.EnsureSuccessStatusCode();
            }

            // Clear basket so shopping can start from scratch
            Basket.Clear();
        }
        public static Task <PolicyResult <TResult> > RaiseResultSequenceOnExecuteAndCaptureAsync <TResult>(this AsyncPolicy <TResult> policy, IDictionary <string, object> contextData, IEnumerable <TResult> resultsToRaise)
        {
            var enumerator = resultsToRaise.GetEnumerator();

            return(policy.ExecuteAndCaptureAsync(ctx =>
            {
                if (!enumerator.MoveNext())
                {
                    throw new ArgumentOutOfRangeException(nameof(resultsToRaise), "Not enough TResult values in resultsToRaise.");
                }

                return Task.FromResult(enumerator.Current);
            }, contextData));
        }
        public static async Task <IRestResponse <T> > ExecuteTaskAsyncWithPolicy <T>(this IRestClient client,
                                                                                     IRestRequest request, CancellationToken cancellationToken, AsyncPolicy <IRestResponse <T> > policy)
        {
            var policyResult =
                await policy.ExecuteAndCaptureAsync(ct => client.ExecuteTaskAsync <T>(request, ct), cancellationToken);

            return(policyResult.Outcome == OutcomeType.Successful
                ? policyResult.Result
                : new RestResponse <T>
            {
                Request = request,
                ErrorException = policyResult.FinalException
            });
        }
Beispiel #10
0
        public async Task <bool> Exec()
        {
            var result = await _clientPolicy.ExecuteAndCaptureAsync(() =>
            {
                return(_httpClient.PostAsync(_endpointUri, _callData, new JsonMediaTypeFormatter()
                {
                    SerializerSettings = new JsonSerializerSettings()
                    {
                        TypeNameHandling = TypeNameHandling.All
                    }
                }));
            });

            var response = result.Result;

            if (response?.StatusCode == HttpStatusCode.OK)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #11
0
        private async Task SendLogs(
            IRaftServer proxy,
            AsyncPolicy policy,
            Peer peer,
            long nextIndex,
            long matchIndex,
            int count)
        {
            var previousIndexTerm = -1L;

            if (nextIndex > 0)
            {
                if (nextIndex > _logPersister.LogOffset)
                {
                    previousIndexTerm = _logPersister.GetEntries(nextIndex - 1, 1).First().Term;
                }
                else
                {
                    Snapshot ss;
                    if (_snapshotOperator.TryGetLastSnapshot(out ss))
                    {
                        previousIndexTerm = ss.LastIncludedTerm;
                    }
                }
            }

            var request = new AppendEntriesRequest()
            {
                CurrentTerm       = State.CurrentTerm,
                Entries           = _logPersister.GetEntries(nextIndex, count).Select(x => x.Body).ToArray(),
                LeaderCommitIndex = _volatileState.CommitIndex,
                LeaderId          = State.Id,
                PreviousLogIndex  = nextIndex - 1,
                PreviousLogTerm   = previousIndexTerm
            };

            var result = await policy.ExecuteAndCaptureAsync(() => proxy.AppendEntriesAsync(request));

            if (result.Outcome == OutcomeType.Successful)
            {
                if (result.Result.IsSuccess)
                {
                    // If successful: update nextIndex and matchIndex for follower(§5.3)"
                    _volatileLeaderState.SetMatchIndex(peer.Id, nextIndex + count - 1);
                    _volatileLeaderState.SetNextIndex(peer.Id, nextIndex + count);
                    TheTrace.TraceInformation($"[{_meAsAPeer.ShortName}] Successfully transferred {count} entries from index {nextIndex} to peer {peer.Address} - Next Index is {_volatileLeaderState.NextIndices[peer.Id]}");
                    UpdateCommitIndex();
                }
                else
                {
                    // log reason only
                    TheTrace.TraceWarning($"AppendEntries for start index {nextIndex} and count {count} for peer {peer.Address} with address {peer.Address} in term {State.CurrentTerm} failed with reason type {result.Result.ReasonType} and this reason: {result.Result.Reason}");

                    if (result.Result.ReasonType == ReasonType.LogInconsistency)
                    {
                        var diff = nextIndex - (matchIndex + 1);
                        nextIndex = diff > _settings.MaxNumberOfDecrementForLogsThatAreBehind ?
                                    nextIndex - _settings.MaxNumberOfDecrementForLogsThatAreBehind :
                                    nextIndex - diff;

                        _volatileLeaderState.SetNextIndex(peer.Id, nextIndex);
                        TheTrace.TraceInformation($"[{_meAsAPeer.ShortName}] Updated (decremented) next index for peer {peer.Address} to {nextIndex}");
                    }
                }
            }
            else
            {
                // NUNCA!!
                // not interested in network, etc errors, they get logged in the policy
            }
        }
Beispiel #12
0
        private async Task <T> ExecuteAndCaptureAsync <T>(Func <Task <T> > action)
        {
            var policyResult = await _asyncPolicy.ExecuteAndCaptureAsync(action);

            return(policyResult.Result);
        }