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('-');
}
Delete duplicates, keep the latest
Finds rows that share an e-mail address and removes all but the newest one. Run it as a SELECT first to see what would go.
SQLcleanupwindow-functions
DELETE FROM customers
WHERE id IN (
SELECT id FROM (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, id DESC) AS rn
FROM customers
) t
WHERE rn > 1
);
Running total
A cumulative sum in date order without a self-join, using a window function.
SQLreportingwindow-functions
SELECT order_date, amount,
SUM(amount) OVER (ORDER BY order_date, id) AS running_total
FROM orders
ORDER BY order_date, id;
Top 3 per group
The three most expensive products in every category, with a stable tie-break on id.
SQLreportingwindow-functions
SELECT category, name, price
FROM (
SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC, id) AS rn
FROM products
) t
WHERE rn <= 3
ORDER BY category, rn;
Find gaps in a sequence
Lists the first missing number of every gap, for example to audit invoice or ticket numbers.
SQLauditjoins
SELECT a.id + 1 AS first_missing
FROM numbers a
LEFT JOIN numbers b ON b.id = a.id + 1
WHERE b.id IS NULL AND a.id < (SELECT MAX(id) FROM numbers)
ORDER BY a.id;