Small, useful pieces of C# and SQL with an explanation, ready to copy.
Every C# snippet is the exact code that is unit tested for this site. The SQL is tested on SQLite; it is standard window-function SQL but may need small changes for SQL Server or another database. Always try it on a copy of your data first.
Retries a flaky call a few times, doubling the wait with a little random jitter so many clients do not retry at the same moment.
C#asyncresiliencehttp
public static async Task<T> RetryAsync<T>(Func<CancellationToken, Task<T>> action, int maxAttempts = 4, TimeSpan? baseDelay = null,
Func<Exception, bool>? shouldRetry = null, CancellationToken ct = default)
{
var delay = baseDelay ?? TimeSpan.FromMilliseconds(200);
for (var attempt = 1; ; attempt++)
{
try { return await action(ct); }
catch (Exception ex) when (attempt < maxAttempts && !ct.IsCancellationRequested && (shouldRetry?.Invoke(ex) ?? true))
{
var jitter = 0.875 + Random.Shared.NextDouble() * 0.25; // spread retries so clients do not stampede
await Task.Delay(TimeSpan.FromMilliseconds(delay.TotalMilliseconds * Math.Pow(2, attempt - 1) * jitter), ct);
}
}
}
Compare secrets in constant time
Compares two tokens without leaking, through timing, how many leading characters matched. Use it for tokens, keys and passcodes.
C#securitytokens
public static bool SecretsEqual(string? a, string? b)
{
if (a is null || b is null) return false;
return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b));
}
URL slug that folds accents
Turns a title into a lower-case URL name. Letters such as å, ä and ö become a and o, and anything else becomes a single dash.
C#textweb
public static string Slugify(string? title)
{
if (string.IsNullOrWhiteSpace(title)) return "";
var sb = new StringBuilder();
foreach (var ch in title.Normalize(NormalizationForm.FormD))
{
if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.NonSpacingMark) continue;
if (char.IsAsciiLetterOrDigit(ch)) sb.Append(char.ToLowerInvariant(ch));
else if (sb.Length > 0 && sb[^1] != '-') sb.Append('-');
}
return sb.ToString().Trim('-');
}