Skip to content

Instantly share code, notes, and snippets.

View brunneus's full-sized avatar

Bruno Maschio Joaquim brunneus

  • Promob
  • Caxias do Sul
View GitHub Profile
@brunneus
brunneus / log-reader.cs
Last active January 19, 2024 14:39
log-reader
var logRecords = ReadLogFile(logFilePath);
var grouping = logRecords.GroupBy(l => l.StatusCode);
foreach (var group in grouping)
{
Console.WriteLine($"StatusCode: {group.Key} - Count: {group.Count()}");
}
var repository = new CustomerRepository();
var id = 1;
var existingCustomer = repository.GetCustomerById(id)
.Match(
some: (foundCustomer) => foundCustomer,
none: () => throw new Exception($"Customer with id {id} does not exists");
Console.WriteLine($"Hello customer {existingCustomer.Name}");
@brunneus
brunneus / CustomersRepository.cs
Created May 14, 2021 00:13
CustomersRepository
public class CustomerRepository
{
public Maybe<Customer> GetCustomerById(int id)
{
var customer = SomeDatabaseAbstraction.GetUser(id);
return new Maybe<Customer>(customer, customer != null);
}
}
@brunneus
brunneus / Maybe.cs
Last active May 13, 2021 23:54
Maybe
public class Maybe<T>
{
private T Value { get; }
private bool IsSome { get; }
public Maybe(T value, bool isSome)
{
Value = value;
IsSome = isSome;
@brunneus
brunneus / HttpClient.cs
Created March 29, 2021 11:49
ResilientHtttpClient
using Flurl.Http;
using Polly;
using Polly.Retry;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace ResilientHttpClient
{
public async Task<T> GetJsonAsync<T>(string url, object headers = null)
{
var policy = BuildRetryPolicy();
return await policy.ExecuteAsync(() => url
.WithHeaders(headers)
.GetJsonAsync<T>()
);
}
public async Task<T> GetJsonAsync<T>(string url, object headers = null)
{
return await url
.WithHeaders(headers)
.GetJsonAsync<T>();
}
@brunneus
brunneus / TransientError.cs
Last active March 26, 2021 00:10
TransientError
private bool IsTransientError(FlurlHttpException exception)
{
int[] httpStatusCodesWorthRetrying =
{
(int)HttpStatusCode.RequestTimeout, // 408
(int)HttpStatusCode.BadGateway, // 502
(int)HttpStatusCode.ServiceUnavailable, // 503
(int)HttpStatusCode.GatewayTimeout // 504
};
@brunneus
brunneus / RetryPolicy.cs
Created March 26, 2021 00:02
RetryPolicy
private AsyncRetryPolicy BuildRetryPolicy()
{
var retryPolicy = Policy
.Handle<FlurlHttpException>(IsTransientError)
.WaitAndRetryAsync(3, retryAttempt =>
{
var nextAttemptIn = TimeSpan.FromSeconds(Math.Pow(2, retryAttempt));
Console.WriteLine($"Retry attempt {retryAttempt} to make request. Next try on {nextAttemptIn.TotalSeconds} seconds.");
return nextAttemptIn;
});
@brunneus
brunneus / HttpClient.cs
Created March 25, 2021 23:57
HttpClient
public class HttpClient
{
public HttpClient()
{
}
}