Skip to content

Instantly share code, notes, and snippets.

View madmonkey's full-sized avatar

Andrew Del Preore madmonkey

View GitHub Profile
public static class FileContentResultGenerator
{
public static byte[] ToCsv(this DataSet ds)
{
var sb = new StringBuilder();
for (var i = 0; i < ds.Tables[0].Columns.Count; i++)
{
sb.Append(ds.Tables[0].Columns[i]);
if (i < ds.Tables[0].Columns.Count - 1)
{
public static int? NullableTryParseInt32(string text)
{
return int.TryParse(text, out var value) ? (int?)value : null;
}
public class SqlExceptionBuilder
{
private int errorNumber;
private string errorMessage;
public SqlException Build()
{
SqlError error = CreateError();
SqlErrorCollection errorCollection = CreateErrorCollection(error);
SqlException exception = CreateException(errorCollection);
public class GenericTypeHandler<T> : SqlMapper.TypeHandler<T>
{
public override T Parse(object value)
{
return JsonConvert.DeserializeObject<T>(value.ToString());
}
public override void SetValue(IDbDataParameter parameter, T value)
{
parameter.Value = JsonConvert.SerializeObject(value);
public static class DapperExtensions
{
public static readonly AsyncRetryPolicy RetryPolicy = GetPolicy;
internal static IEnumerable<TimeSpan> GenerateRetries(int maxRetries = 5, int maxSeconds = 26)
{
return Enumerable.Range(1, maxRetries)
.Select(_ => TimeSpan.FromSeconds(new Random().Next(maxSeconds - 5, maxSeconds + 5)));
}
public static class SqlServerTransientExceptionDetector
{
public static bool ShouldRetryOn(SqlException ex)
{
foreach (SqlError err in ex.Errors)
{
switch (err.Number)
{
// SQL Error Code: 49920
// Cannot process request. Too many operations in progress for subscription "%ld".
public static class AsyncEnumerableExtensions
{
public static Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return ExecuteAsync();
static class TaskExtensions
{
public static Task AsTask(this CancellationToken cancellationToken, bool useContext = false)
{
var tcs = new TaskCompletionSource<object>();
cancellationToken.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: useContext);
return tcs.Task;
}
}
static class LinqExtensions
{
public static IQueryable<TSource> WhereIf<TSource>(
this IQueryable<TSource> source,
bool condition,
Expression<Func<TSource, bool>> predicate)
{
return condition ? source.Where(predicate) : source;
}
public static List<T> Append<T>(this List<T> list, params T[] values)
static class TypeExtensions
{
public static bool HasProperty(this Type obj, string propertyName)
{
// ignore case and replace additional default binding parameters
return obj.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null;
}
public static bool TrySetProperty<TValue>(this object obj, string propertyName, TValue value)
{
var property = obj.GetType().GetProperty(propertyName,