Helpers Catalog

Developer resources

Helpers Catalog

Use this maintained reference library for focused implementation patterns across .NET, WordPress, Python, JavaScript, PowerShell and SQL. The examples are complete, readable, and designed to be adapted inside real systems.

Production reference library

Working helpers you can inspect, copy and download

Every entry below contains complete code for a focused task. Search by problem, filter by language or category, then copy the code or download it as a text file.

26
working helpers
7
languages
10
categories

C#Files

Atomic file write

Writes through a temporary file and replaces the destination only after the write succeeds.

View code
public static void WriteAllTextAtomic(string path, string content, Encoding? encoding = null)
{
    encoding ??= new UTF8Encoding(false);
    var fullPath = Path.GetFullPath(path);
    Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
    var tempPath = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
    try
    {
        File.WriteAllText(tempPath, content, encoding);
        File.Move(tempPath, fullPath, true);
    }
    finally
    {
        if (File.Exists(tempPath)) File.Delete(tempPath);
    }
}
C#Files

SHA-256 file hash

Calculates a lowercase SHA-256 hash without loading the full file into memory.

View code
public static string Sha256File(string path)
{
    using var stream = File.OpenRead(path);
    using var sha = SHA256.Create();
    return Convert.ToHexString(sha.ComputeHash(stream)).ToLowerInvariant();
}
C#Security

Safe child path

Prevents a user-controlled relative path from escaping an approved root folder.

View code
public static string SafeChildPath(string root, string relativePath)
{
    var rootPath = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
    var candidate = Path.GetFullPath(Path.Combine(rootPath, relativePath));
    if (!candidate.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase))
        throw new UnauthorizedAccessException("Path escapes the approved root.");
    return candidate;
}
C#HTTP

Typed JSON HTTP GET

Fetches and deserializes JSON with cancellation and a useful failure message.

View code
public static async Task<T> GetJsonAsync<T>(HttpClient client, string url, CancellationToken token)
{
    using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
    var body = await response.Content.ReadAsStringAsync(token);
    if (!response.IsSuccessStatusCode)
        throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {body}");
    return JsonSerializer.Deserialize<T>(body, new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true
    }) ?? throw new JsonException("The response body was empty.");
}
C#Reliability

Async retry with backoff

Retries transient work with cancellation-aware exponential backoff.

View code
public static async Task<T> RetryAsync<T>(Func<CancellationToken, Task<T>> action, int attempts, CancellationToken token)
{
    if (attempts < 1) throw new ArgumentOutOfRangeException(nameof(attempts));
    Exception? last = null;
    for (var attempt = 1; attempt <= attempts; attempt++)
    {
        try { return await action(token); }
        catch (Exception ex) when (attempt < attempts && ex is not OperationCanceledException)
        {
            last = ex;
            await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt - 1)), token);
        }
    }
    throw last ?? new InvalidOperationException("Retry failed.");
}
C#Data

RFC-style CSV row

Escapes quotes, commas and line breaks when exporting a row.

View code
public static string CsvRow(IEnumerable<object?> values)
{
    return string.Join(",", values.Select(value =>
    {
        var text = Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty;
        return text.IndexOfAny(new[] { ',', '"', '\r', '\n' }) >= 0
            ? "\"" + text.Replace("\"", "\"\"") + "\""
            : text;
    }));
}
C#Collections

Batch an enumerable

Streams items in fixed-size batches without copying the full source.

View code
public static IEnumerable<IReadOnlyList<T>> Batch<T>(IEnumerable<T> source, int size)
{
    if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size));
    var batch = new List<T>(size);
    foreach (var item in source)
    {
        batch.Add(item);
        if (batch.Count != size) continue;
        yield return batch;
        batch = new List<T>(size);
    }
    if (batch.Count > 0) yield return batch;
}
C#Database

Nullable database value

Reads a nullable typed value from an IDataRecord safely.

View code
public static T? GetNullable<T>(this IDataRecord record, string column) where T : struct
{
    var ordinal = record.GetOrdinal(column);
    if (record.IsDBNull(ordinal)) return null;
    return (T)Convert.ChangeType(record.GetValue(ordinal), typeof(T), CultureInfo.InvariantCulture);
}
C#Security

Secure XML reader

Parses XML with DTD and external entity resolution disabled.

View code
public static XDocument LoadXmlSecure(Stream input)
{
    var settings = new XmlReaderSettings
    {
        DtdProcessing = DtdProcessing.Prohibit,
        XmlResolver = null,
        MaxCharactersInDocument = 20_000_000
    };
    using var reader = XmlReader.Create(input, settings);
    return XDocument.Load(reader, LoadOptions.None);
}
C#Files

Copy stream with progress

Copies a stream asynchronously and reports cumulative bytes.

View code
public static async Task CopyWithProgressAsync(Stream source, Stream target, IProgress<long>? progress, CancellationToken token)
{
    var buffer = new byte[81920];
    long total = 0;
    int read;
    while ((read = await source.ReadAsync(buffer.AsMemory(0, buffer.Length), token)) > 0)
    {
        await target.WriteAsync(buffer.AsMemory(0, read), token);
        total += read;
        progress?.Report(total);
    }
}
VB.NETFiles

Atomic file write

VB.NET atomic text replacement with temporary-file cleanup.

View code
Public Sub WriteAllTextAtomic(path As String, content As String)
    Dim fullPath = IO.Path.GetFullPath(path)
    IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(fullPath))
    Dim tempPath = fullPath & "." & Guid.NewGuid().ToString("N") & ".tmp"
    Try
        IO.File.WriteAllText(tempPath, content, New Text.UTF8Encoding(False))
        IO.File.Move(tempPath, fullPath, True)
    Finally
        If IO.File.Exists(tempPath) Then IO.File.Delete(tempPath)
    End Try
End Sub
VB.NETFiles

SHA-256 file hash

Hashes large files through a stream.

View code
Public Function Sha256File(path As String) As String
    Using stream = IO.File.OpenRead(path), sha = Security.Cryptography.SHA256.Create()
        Return Convert.ToHexString(sha.ComputeHash(stream)).ToLowerInvariant()
    End Using
End Function
VB.NETDatabase

Nullable database string

Returns Nothing for SQL NULL and a string otherwise.

View code
Public Function GetNullableString(record As IDataRecord, column As String) As String
    Dim ordinal = record.GetOrdinal(column)
    If record.IsDBNull(ordinal) Then Return Nothing
    Return record.GetString(ordinal)
End Function
VB.NETSecurity

Safe child path

Restricts a relative path to an approved root.

View code
Public Function SafeChildPath(root As String, relativePath As String) As String
    Dim rootPath = IO.Path.GetFullPath(root).TrimEnd(IO.Path.DirectorySeparatorChar) & IO.Path.DirectorySeparatorChar
    Dim candidate = IO.Path.GetFullPath(IO.Path.Combine(rootPath, relativePath))
    If Not candidate.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase) Then
        Throw New UnauthorizedAccessException("Path escapes the approved root.")
    End If
    Return candidate
End Function
VB.NETData

Read typed JSON file

Reads UTF-8 JSON into a typed model with case-insensitive property matching.

View code
Public Function ReadJsonFile(Of T)(path As String) As T
    Dim json = IO.File.ReadAllText(path, Text.Encoding.UTF8)
    Dim options = New Text.Json.JsonSerializerOptions With {.PropertyNameCaseInsensitive = True}
    Dim value = Text.Json.JsonSerializer.Deserialize(Of T)(json, options)
    If value Is Nothing Then Throw New Text.Json.JsonException("JSON produced no value.")
    Return value
End Function
PHP / WordPressWordPress

Secure WordPress form action

Checks authentication, capability, nonce and sanitized input before changing state.

View code
add_action('admin_post_jvr_save_item', function () {
    if (!current_user_can('manage_options')) {
        wp_die('Not allowed.', 403);
    }
    check_admin_referer('jvr_save_item');
    $name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
    if ($name === '') {
        wp_safe_redirect(add_query_arg('error', 'missing_name', wp_get_referer()));
        exit;
    }
    update_option('jvr_item_name', $name, false);
    wp_safe_redirect(add_query_arg('updated', '1', wp_get_referer()));
    exit;
});
PHP / WordPressWordPress

Permission-checked REST route

Registers a REST endpoint whose permission is enforced server-side.

View code
add_action('rest_api_init', function () {
    register_rest_route('jvr/v1', '/status', array(
        'methods' => WP_REST_Server::READABLE,
        'callback' => function () {
            return rest_ensure_response(array('ok' => true, 'time' => current_time('mysql')));
        },
        'permission_callback' => function () {
            return current_user_can('manage_options');
        },
    ));
});
PHP / WordPressPerformance

Cached WordPress query

Caches an expensive query and returns IDs to keep the transient small.

View code
function jvr_recent_job_ids() {
    $key = 'jvr_recent_job_ids_v1';
    $ids = get_transient($key);
    if ($ids !== false) return $ids;
    $ids = get_posts(array(
        'post_type' => 'post', 'post_status' => 'publish',
        'posts_per_page' => 50, 'fields' => 'ids', 'no_found_rows' => true,
    ));
    set_transient($key, $ids, 10 * MINUTE_IN_SECONDS);
    return $ids;
}
PythonFiles

Atomic JSON save

Writes JSON safely in the destination directory and atomically replaces the old file.

View code
from pathlib import Path
import json, os, tempfile

def save_json_atomic(path, value):
    target = Path(path).resolve()
    target.parent.mkdir(parents=True, exist_ok=True)
    fd, temp = tempfile.mkstemp(dir=target.parent, prefix=target.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(value, handle, ensure_ascii=False, indent=2)
            handle.flush(); os.fsync(handle.fileno())
        os.replace(temp, target)
    finally:
        if os.path.exists(temp): os.unlink(temp)
PythonReliability

Retry with exponential backoff

Retries transient synchronous work and preserves the final exception.

View code
import time

def retry(action, attempts=4, retry_if=lambda exc: True):
    if attempts < 1:
        raise ValueError("attempts must be positive")
    for attempt in range(attempts):
        try:
            return action()
        except Exception as exc:
            if attempt + 1 == attempts or not retry_if(exc):
                raise
            time.sleep(2 ** attempt)
JavaScriptBrowser

Fetch with timeout

Combines a caller signal with a timeout and throws on non-success HTTP status.

View code
export async function fetchWithTimeout(url, options = {}, timeoutMs = 10000) {
  const timeout = AbortSignal.timeout(timeoutMs);
  const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
  const response = await fetch(url, { ...options, signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response;
}
JavaScriptBrowser

Debounce an input handler

Delays rapid calls while preserving arguments and this binding.

View code
export function debounce(callback, delay = 250) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => callback.apply(this, args), delay);
  };
}
JavaScriptBrowser

Clipboard copy with fallback

Copies text in secure browsers and provides an older-browser fallback.

View code
export async function copyText(text) {
  if (navigator.clipboard && window.isSecureContext) {
    await navigator.clipboard.writeText(text);
    return;
  }
  const area = Object.assign(document.createElement('textarea'), { value: text });
  area.style.position = 'fixed'; area.style.opacity = '0';
  document.body.append(area); area.select();
  try { document.execCommand('copy'); } finally { area.remove(); }
}
PowerShellReliability

PowerShell retry wrapper

Retries a script block with exponential backoff and rethrows the final error.

View code
function Invoke-WithRetry {
    param([Parameter(Mandatory)][scriptblock]$Action, [int]$Attempts = 4)
    for ($attempt = 1; $attempt -le $Attempts; $attempt++) {
        try { return & $Action }
        catch {
            if ($attempt -eq $Attempts) { throw }
            Start-Sleep -Seconds ([math]::Pow(2, $attempt - 1))
        }
    }
}
PowerShellFiles

Create SHA-256 manifest

Builds a reproducible hash list for all files below a release folder.

View code
param([Parameter(Mandatory)][string]$Root)
$resolved = (Resolve-Path -LiteralPath $Root).Path
Get-ChildItem -LiteralPath $resolved -File -Recurse |
    Sort-Object FullName |
    ForEach-Object {
        [pscustomobject]@{
            Path = $_.FullName.Substring($resolved.Length).TrimStart('\')
            SHA256 = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
        }
    }
SQLDatabase

MariaDB atomic upsert

Inserts a keyed value or updates it atomically without a select-then-write race.

View code
INSERT INTO app_settings (setting_key, setting_value, updated_at)
VALUES (?, ?, UTC_TIMESTAMP())
ON DUPLICATE KEY UPDATE
    setting_value = VALUES(setting_value),
    updated_at = VALUES(updated_at);
Need a helper for your system?

Describe the input, required output, language and runtime. JVR Software can turn it into tested implementation work.

Request implementation

Recovered original collection

Complete C# and VB.NET helper archive

The original JVR Software helper site is restored here without replacing the curated production snippets above. Implementation and research/concept references are labelled separately; review dependencies and runtime requirements before production use.

151
helpers
296
source files
256
documentation pages

Loading the recovered archive...

Reference notice: archive code is provided as recovered technical material. Inspect package requirements, APIs, validation, and platform support before use.