BosonWareEnterprises
Back to insights

BosonWare C# Extensions

AuthorBobby
PublishedSeptember 2, 2026

BosonWare.Extensions

.NET 10.0 License: MIT

BosonWare.Extensions is a utility and infrastructure library for modern .NET applications. It provides high-performance components for application lifecycle and directory management, caching, cryptography, JSON persistence, and Terminal User Interface (TUI) console utilities.


Table of Contents


Features

  • 📁 Application Metadata & Path Resolver: Auto-creates cross-platform data directories, resolving relative file/folder paths with environment variable overrides.
  • Synchronous & Asynchronous Caching: Memory-cached factories (CacheFactory, AsyncCacheFactory) and static generic caches (GlobalCache<T>) with automatic expiration windows.
  • 🔐 Cryptography & Tokens: AES-256 (CBC/PKCS7), RSA (OAEP-SHA256, PEM loading), PBKDF2 key derivation, ephemeral key generation, and RSA digital signature creation/verification.
  • 💾 Disk Persistence: Strongly-typed auto-syncing PersistentList<T> and PersistentDictionary<TKey, TValue> serialized as pretty-printed JSON.
  • 🖥️ TUI & Console Utilities: Thread-safe SmartConsole with animated text rendering, password masking, markup parser ([CYAN], [BRIGHT], [RED]), and command history support (ReadLineWithHistory).

Installation

Add a project reference to BosonWare.Extensions.csproj or package reference:

dotnet add package BosonWare.Extensions

Requires .NET 10.0 or later.


Modules & API Reference

Application & Path Management

Decorate your assembly with [assembly: Application(...)] and call Application.Initialize<Program>() at startup. This automatically configures base directories and metadata.

using BosonWare.Extensions;

// Configure metadata at the assembly level
[assembly: Application("MyApp", Folder = Environment.SpecialFolder.UserProfile, Version = "1.2.0")]

// Initialize during startup
Application.Initialize<Program>();

Console.WriteLine($"Name: {Application.PrettyName}");   // "MyApp"
Console.WriteLine($"Version: {Application.Version}");    // 1.2.0
Console.WriteLine($"Data Path: {Application.DataPath}");  // e.g. /home/user/.MyApp

// Get paths (creates parent directories automatically)
string configFilePath = Application.GetPath("config", "settings.json");
string logsDir = Application.GetDirectory("logs", "2026");

Environment Override: Set the APPLICATION_PATH environment variable to override Application.DataPath.


Caching System

1. CacheFactory<TValue> & AsyncCacheFactory<TValue>

Caches values produced by a factory delegate with a defined TTL (Time-To-Live). Re-evaluates automatically upon expiration.

using BosonWare.Extensions.Caching;

var cache = new CacheFactory<string>
{
    Expiration = TimeSpan.FromMinutes(5),
    ValueFactory = () => FetchDataFromApi()
};

string data = cache.GetValue(); // Fetched on first call, cached for 5 minutes

Asynchronous variant:

var asyncCache = new AsyncCacheFactory<List<Item>>
{
    Expiration = TimeSpan.FromMinutes(10),
    ValueFactory = async ct => await Database.GetItemsAsync(ct)
};

var items = await asyncCache.GetValueAsync(cancellationToken);

2. GlobalCache<TValue>

Thread-safe, key-value based static cache using ConcurrentDictionary.

string value = GlobalCache<string>.Get(
    key: "user_session_123",
    expiration: TimeSpan.FromMinutes(15),
    valueFactory: () => LoadUserSession("123")
);

// Async lookup
string asyncVal = await GlobalCache<string>.GetAsync(
    key: "config_data",
    expiration: TimeSpan.FromHours(1),
    valueFactory: async ct => await LoadRemoteConfigAsync(ct)
);

Cryptography & Security

AES Encryption (AesEncryptionService)

Encrypts/decrypts byte arrays or Base64-encoded strings using AES-256 in CBC mode with PKCS7 padding. Encrypted payloads store the IV at the beginning of output.

using BosonWare.Extensions.Cryptography;

byte[] key = KeyUtility.ComputeKey(salt: "my-salt", password: "my-secret-password");
using var aes = new AesEncryptionService(key);

string cipherText = aes.EncryptText("Secret Data");
string plainText = aes.DecryptText(cipherText);

RSA Encryption & Signatures (RSAEncryptionService / SignatureUtility)

Supports importing RSA keys from PEM format.

// Encryption using RSA PEM key (OAEP-SHA256)
using var rsaService = RSAEncryptionService.FromPemKey(pemPrivateKeyString);
string encrypted = rsaService.EncryptText("Sensitive payload");
string decrypted = rsaService.DecryptText(encrypted);

// Digital Signature Creation and Verification (SHA-512 with PKCS1)
string token = SignatureUtility.CreateToken(pemPrivateKey, message: "Transaction Payload");
bool isValid = SignatureUtility.CheckSignature(token, pemPublicKey, message: "Transaction Payload");

Ephemeral Keys & Key Derivation (EphemeralKeys, KeyUtility)

Generates non-persistent in-memory keys using PBKDF2 with salt/sugar pairs.

// Get or create named ephemeral key (32 bytes default)
byte[] sessionKey = EphemeralKeys.Get("Session_42");

// Generate key using PBKDF2
byte[] key = KeyUtility.ComputeKey("salt", "password", iterations: 10000, derivedKeyLength: 32);

JSON File Persistence

Subclass PersistentObject<T> or use out-of-the-box collections (PersistentList<T>, PersistentDictionary<TKey, TValue>) to persist state directly to JSON disk files.

using BosonWare.Extensions.Persistence;

string filePath = Application.GetPath("data", "todos.json");

// Load existing or initialize new list
var todoList = await PersistentList<string>.CreateAsync(filePath, loc => new PersistentList<string>(loc));

// Modifications auto-save to disk
await todoList.AddAsync("Buy groceries");
await todoList.AddAsync("Write documentation");
await todoList.RemoveAsync("Buy groceries");

For persistent dictionaries:

string dictPath = Application.GetPath("data", "settings.json");
var config = await PersistentDictionary<string, string>.CreateAsync(dictPath, loc => new PersistentDictionary<string, string>(loc));

await config.Change(dict =>
{
    dict["Theme"] = "Dark";
    dict["AutoSave"] = "True";
});

TUI & Console Markup

Console Markup Codes (AnsiCodes)

Use embedded markup syntax [COLOR_NAME]text[/] in formatted text.

Supported markup tags:

  • [BRIGHT], [DIM]
  • [GREEN], [YELLOW], [RED], [DARKRED], [CRIMSON], [CYAN], [PURPLE], [MAGENTA], [VIOLET]
  • [/] (Resets formatting)

Escaping brackets: \[ and \].

using BosonWare.Extensions.TUI;

TUIConsole.WriteLine("[BRIGHT][CYAN]BosonWare[/] [YELLOW]Extensions[/] loaded successfully![/]");

SmartConsole & TUIConsole

Thread-safe console access with animation, history, and secure input masking:

// Thread-safe logging with pre-formatted levels
SmartConsole.LogInfo("Operation completed.");
SmartConsole.LogWarning("Disk space low.");
SmartConsole.LogError("Failed to connect.");

// Animated typing output
await TUIConsole.WriteAnimatedAsync("Processing data, please wait...", delayMilliseconds: 30);

// Read password securely with optional confirmation prompt
string password = SmartConsole.ReadPassword("Enter password: ", confirm: true);

// Interactive terminal prompt with Up/Down arrow history
var history = new List<string>();
string command = TUIConsole.ReadLineWithHistory("[CYAN]app> [/]", history);

JSON Extensions

Simple extension method for standard System.Text.Json serialization:

using BosonWare.Extensions;

var user = new { Name = "Alice", Role = "Admin" };
string json = user.ToJson(prettyPrint: true);

Building & Lab Project

Build Solution

dotnet build BosonWare.Extensions.slnx

Run Lab Demo Project

dotnet run --project BosonWare.Extensions.Lab

License

This project is licensed under the MIT License. Copyright (c) BosonWare Enterprises.