Skip to content

Instantly share code, notes, and snippets.

View rgueldenpfennig's full-sized avatar

Robin Güldenpfennig rgueldenpfennig

View GitHub Profile
@rgueldenpfennig
rgueldenpfennig / TaskExtensions.cs
Created March 27, 2023 16:30
Various Task extension methods
public static class TaskExtensions
{
/// <summary>
/// The given task will be retried a given number of times. In case of failure a delay is introduced before executing the retry.
/// </summary>
public static async Task<T> Retry<T>(
this Func<Task<T>> taskFactory,
int maxRetries,
TimeSpan delay)
{
@rgueldenpfennig
rgueldenpfennig / Paging.cs
Last active March 19, 2021 08:01
Simple paging functionality for Entity Framework queries
public static class PagingExtensions
{
public static IQueryable<T> Page<T>(this IQueryable<T> query, int pageIndex, int pageSize)
{
if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(pageSize), "Must be greater than zero.");
if (pageIndex < 0) throw new ArgumentOutOfRangeException(nameof(pageIndex), "Must not be negative.");
if (pageIndex != 0) query = query.Skip(pageIndex * pageSize);
return query.Take(pageSize);
@rgueldenpfennig
rgueldenpfennig / RawXmlInputFormatter.cs
Created April 24, 2020 15:15
A raw XML based input formatter for ASP .NET Core applications
// Implementation
public class RawXmlInputFormatter : TextInputFormatter
{
public RawXmlInputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
SupportedEncodings.Add(Encoding.UTF8);
}
protected override bool CanReadType(Type type)
@rgueldenpfennig
rgueldenpfennig / StartupExample.cs
Last active July 14, 2021 14:51
Configure JSON serializer settings to convert Enums to strings and ignorre null values in an ASP.NET Core application
public void ConfigureServices(IServiceCollection services)
{
// when using Newtonsoft JSON
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
@rgueldenpfennig
rgueldenpfennig / ServiceCollectionsExtensions.cs
Last active September 8, 2020 15:44
Get all types that implement an (generic) interface and register them in .NET Core dependency injection
public static class ServiceCollectionExtensions
{
public static void AddImplementationsOf<T>(
this IServiceCollection services,
Assembly[] assemblies = null,
ServiceLifetime lifetime = ServiceLifetime.Scoped)
{
var serviceType = typeof(T);
services.AddImplementationsOf(serviceType, assemblies, lifetime);
}