BosonWare.Extensions 1.1.0

dotnet add package BosonWare.Extensions --version 1.1.0
                    
NuGet\Install-Package BosonWare.Extensions -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BosonWare.Extensions" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BosonWare.Extensions" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="BosonWare.Extensions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BosonWare.Extensions --version 1.1.0
                    
#r "nuget: BosonWare.Extensions, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BosonWare.Extensions@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BosonWare.Extensions&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=BosonWare.Extensions&version=1.1.0
                    
Install as a Cake Tool

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);

Encoding and Decoding Extensions

Base58 encoding and decoding utilities:

using BosonWare.Extensions.Encoding;

var message = "Hello, World!";

var bytes = Encoding.UTF8.GetBytes(message);

var encoded = OptimizedBase58.EncodeData(bytes);

Console.WriteLine("Base58: " + encoded);

var decoded = OptimizedBase58.DecodeData(encoded);
var decodedString = Encoding.UTF8.GetString(decoded);

Note: OptimizedBase58 is a memory-optimized version of Base58. It uses UnmanagedMemory for performance and avoids unnecessary allocations. It is suitable for high-performance scenarios where Base58 encoding/decoding is frequently used.


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.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 110 9/4/2026
1.0.0 106 9/2/2026

Added Encoding and Base58 Encoding utilities.