Sphere10.Framework
3.2.0
dotnet add package Sphere10.Framework --version 3.2.0
NuGet\Install-Package Sphere10.Framework -Version 3.2.0
<PackageReference Include="Sphere10.Framework" Version="3.2.0" />
<PackageVersion Include="Sphere10.Framework" Version="3.2.0" />
<PackageReference Include="Sphere10.Framework" />
paket add Sphere10.Framework --version 3.2.0
#r "nuget: Sphere10.Framework, 3.2.0"
#:package Sphere10.Framework@3.2.0
#addin nuget:?package=Sphere10.Framework&version=3.2.0
#tool nuget:?package=Sphere10.Framework&version=3.2.0
π§ͺ Sphere10 Framework
Developer: Herman Schoenfeld
Copyright: Β© 2018-Present Herman Schoenfeld
License: MIT<br>
Status: Production-Ready
π Project Overview
Sphere10 Framework is a low-level, high-performance .NET utility library providing composable data structures and persistence primitives. It excels at scenarios requiring fine-grained control over memory, serialization, and transactional semanticsβthink blockchain systems, embedded databases, high-volume analytics, and custom storage layers.
Unlike general-purpose libraries, Sphere10 Framework doesn't provide application frameworks or abstractions. Instead, it offers:
- 50+ collection types (extended lists, stream-mapped, paged, recyclable, merkle-aware)
- Advanced serialization framework (polymorphism, references, versioning, constant-size encoding)
- Transactional ACID primitives (scopes, streams, collections with commit/rollback)
- Merkle-tree implementations (flat, simple, long, partial) for integrity proofs
- Cryptographic utilities (hashing, signatures, key derivation, VRF, post-quantum schemes)
- Clustered streams (multi-stream storage, dynamic allocation, attachments)
- Thread-safe concurrent collections and producer-consumer patterns
- 50+ string, enumerable, task, stream, and type extension methods
Key Attributes
- Language: C# targeting .NET 8, 9 and 10, plus .NET 11 when built with a .NET 11 SDK
- Dependencies: No package dependencies, and only an allowlisted set of .NET assemblies (see Allowed .NET assemblies)
- Platform Support: Windows, Linux, macOS, iOS, Android
- Philosophy: Composable, explicit, performance-conscious, extensible, correct
- Tests: Comprehensive test suite with 25+ subsystems and 2000+ tests
- Maturity: Production-ready (v3.1.3) with battle-tested core subsystems
π¦ Installation
dotnet add package Sphere10.Framework
Domains
Every folder of Sphere10.Framework is a domain with its own README, which lists all of its public types.
| Domain | What it provides | Source |
|---|---|---|
| Attributes | Declarative attributes for default dates, enum error messages and metadata, and file extensions. | source |
| Cache | Synchronized in-memory caches that fetch values on a miss and evict them under expiration, staleness and capacity policies. | source |
| Calendar | A recurrence rule, events with occurrences, and a calendar contract that a person's calendar, a job schedule or an operating system's tasks can each implement. | source |
| ClusteredStreams | Multiplexes any number of resizable logical streams onto one root Stream through linked chains of fixed-size clusters, with pluggable attachments for indexes and other reserved data. |
source |
| Collections | Provides long-indexed extended lists and collections, B-trees, paged, file-mapped and stream-mapped storage, and observable, synchronized and projected wrappers over lists, dictionaries, sets, queues and stacks. | source |
| Comparers | Reusable IComparer<T> and IEqualityComparer<T> implementations for sequences, byte arrays, tuples, projections and composed orderings. |
source |
| ComponentModel | Data-binding lists, type converters and value validators for editors that convert between display strings and typed values. | source |
| Conversion | Endian-aware conversion between primitive values and bytes, and exact decimal text for double values. |
source |
| Crypto | Hash functions, digital signature schemes, post-quantum one-time signatures, random number generators, key derivation, encryption and verifiable random functions. | source |
| DataSource | The IDataSource<TItem> CRUD, paging and change-notification contract, its synchronous and asynchronous base classes, list and array storage, and the refreshable and polling decorators. |
source |
| Disposables | Base classes and small adapters that implement IDisposable and IAsyncDisposable together, with a single cleanup hook in the direction the resource needs. |
source |
| Drawing | Platform-neutral enumerations that describe how an image is resized into a requested size. | source |
| Encoding | Text encodings of binary data in hexadecimal, Base32 and Base62. | source |
| Environment | Runtime and process facilities: external command execution, single-instance enforcement, the machine identifier contract, runtime queries and debugging scratch state. | source |
| Events | Sender-free event delegates, call-argument payloads and before and after event arguments for intercepted operations. | source |
| Exceptions | Argument and invariant guards, the SoftwareException hierarchy and helpers that run actions while capturing or ignoring their exceptions. |
source |
| Extensions | Extension methods over BCL and Framework types, from strings, dates, sequences and streams to the decorator activators that wrap collections, comparers and serializers. | source |
| Filter | A serializable filter and sort model that compiles into LINQ expressions for in-memory sequences and IQueryable sources. |
source |
| Framework | The module configuration contract through which a package initializes and finalizes its Framework services. | source |
| Functional | Generic arithmetic and comparison operators compiled from expression trees, and helpers that build and wrap delegates. | source |
| IO | File-system utilities, endian-aware binary readers and writers, file content caches, file descriptors for paged and transactional storage, and multi-file transactions. | source |
| Introspection | Compiled-expression reflection accessors with process-wide caches, and the Tools.Reflection helpers built on them. |
source |
| Keys | Value-type compound keys of two, three or four ordered components for dictionaries and B-tree indexes. | source |
| Loadable | The ILoadable contract for objects that load their state on demand, with base classes that pair synchronous and asynchronous loading. |
source |
| Logging | The ILogger abstraction with console, debug, file, rolling-file, text-writer and delegate sinks, prefixing and threading decorators, and the application-wide SystemLog. |
source |
| Mapping | Member models resolved from lambda expressions, with accessors that read and write a single member or a chain of members. | source |
| Maths | A Q31.32 fixed-point type, running statistics, numerical integration and arc length, fast approximations, pseudo-random generators and power-of-two partitions. | source |
| Memory | Memory-size units and conversions, readable byte counts, primitive sizes and a union that reinterprets one array reference as another element type. | source |
| Merkle | Dynamic merkle trees that hash leaf digests into a root and generate and verify existence, consistency, contains, update, append and delete proofs, with merkleized lists, sets, dictionaries and paged buffers. | source |
| Misc | Small shared policies, sort options, authentication results, a cycle detector, a decaying gauge, recursive data, UI target references and obfuscated URL identifiers. | source |
| Network | URL parsing and building, query strings, the MIME type table and video-sharing link detection, without any networking. | source |
| ObjectSpaces | An embedded, indexed store of typed CLR objects over clustered streams, in memory or in a transactional file. | source |
| ObjectStream | A list-like store of serialized objects over clustered streams, with observer hooks and projection indexes kept in attachments of the same storage. | source |
| Objects | Reflection-based object cloning, deep comparison, attribute-driven defaults, and the Tools.Object helpers that front them. |
source |
| Peripherals | Platform-neutral keyboard and mouse event models, key and scan codes, and the device-hook contracts that native hooks implement. | source |
| Persistable | The IPersistable contract for objects that both load and save their state, with sync, async and decorator bases. |
source |
| Repository | The IRepository<TEntity, TIdentity> CRUD contract with paired synchronous and asynchronous members, base classes, a dictionary adapter and decorators. |
source |
| Saveable | The ISaveable contract for objects that write their state on demand, with base classes that pair synchronous and asynchronous saving. |
source |
| Scheduler | Timer-driven scheduling of one-shot and recurring jobs, with fluent job builders and XML-serializable job surrogates. | source |
| Scopes | Disposable scope values that release a lock, rental, page, stream position or custom finalizer, plus call-context scopes that share one root across nested calls. | source |
| Serialization | Binary item serializers for values, collections, tuples, references and polymorphic object graphs, with a type-code registry, a member-by-member builder and item hashers and checksummers. | source |
| Sizing | Item sizers that compute the serialized byte size of values, the sizing half of every item serializer. | source |
| Spans | Endian-aware sequential reading of primitive values from byte spans, and span helpers in Tools.Spans. |
source |
| Streams | Stream implementations, stream decorators and Tools.Streams helpers for bounded, buffered, encrypted, hashed, concurrent, fragmented and blocking streams. |
source |
| Text | String formatting with named tokens, type-converter parsing, casing and inflection, tokenizing, keyword extraction, Unicode block ranges and a fluent regular-expression builder. | source |
| TextWriters | TextWriter sinks for the console, debug output, files, string builders and delegates, plus multicast, time-stamping and transforming decorators. |
source |
| Threading | Lock owners that hand out disposable scopes, serial and producer-consumer execution primitives, throttles and Tools.Threads helpers. |
source |
| Transactions | Commit and rollback contracts, nested call-context transactional scopes, and file-backed transactional buffers, streams, lists, dictionaries and hash sets. | source |
| Types | Runtime type helpers for resolving types by name, constructing instances, converting values, setting properties, switching on a value's type and supplying component-model type converters. | source |
| Values | Value types and helpers for deferred values, operation results, variable-length integers, GUID generation, bit manipulation, value ranges and the Tools.Time, Tools.Enums and Tools.Values utilities. |
source |
Project root
Types declared in the project folder itself:
| Type | Kind | Purpose |
|---|---|---|
Sphere10FrameworkDefaults |
static class | Library-wide default constants for buffer and page sizes, cluster sizes, container policies, endianness, hash function, B-tree orders, ObjectSpace settings, cache reap level and attachment names. |
Networking (Tools.Network, Tools.Mail, Tools.Web.Downloader, NetworkProbeDataSource and the Protocol types) is in Sphere10.Framework.Communications. Member encryption (EncryptedStringAttribute, ObjectEncryptor), ProcessDataSource and ProcessExtensions are in Sphere10.Framework.Application.
Allowed .NET assemblies
The core library compiles against an allowlist of .NET assemblies, so it stays free of UI, drawing and platform libraries. Sphere10.Framework.csproj lists them as AllowedFrameworkAssembly items, and the RestrictFrameworkAssemblies target in Directory.Build.targets removes every other Microsoft.NETCore.App reference before compiling. Using a type from an assembly that is not listed, such as System.Drawing.Color or System.Net.Http.HttpClient, is a compile error.
<ItemGroup>
<AllowedFrameworkAssembly Include="System.Collections" />
<AllowedFrameworkAssembly Include="System.Net.Primitives" />
</ItemGroup>
Two entries are deliberately narrow. System.Diagnostics.Process serves the current process's identity in Tools.Runtime and SoftwareException, and ProcessSentry. System.Net.Primitives supplies only the IPAddress and IPEndPoint value types that DeepObjectComparer compares. Add an assembly only when the core genuinely needs it; otherwise put the code in the project that owns the dependency. Any other project can opt in by listing its own AllowedFrameworkAssembly items.
Typed interface adapters
Generic contracts supply default implementations for their inherited non-generic
members. Implement the typed operations when creating an
IStreamMappedCollection<T>,
typed protocol handler (in Sphere10.Framework.Communications), IDigitalSignatureScheme<TPrivateKey, TPublicKey>,
IOTSAlgorithm<TConfig> or ICloneable<T>; the interface supplies the conversion
to the base contract. Protocol implementations continue to provide their own
MessageType, RequestType and ResponseType properties. Extended collection,
stack, queue, page and lookup
interfaces also supply their inherited collection adapters. IExtendedBTreeLookup<K, V>
provides shared LINQ lookup adapters while existing IBTreeLookup<K, V>
implementations retain their original contract.
IObjectSpaceDimensionBuilder<TBuilder> preserves fluent return types while
providing the non-generic builder view. ITransactionalScope<TRootScope> retains
the root's concrete type. Typed caches use an explicit ObjectCacheProjection adapter
when object access is required, and IJobSchedule
supplies its chronological comparison.
IStreamMappedDictionary<TKey, TValue> also inherits
IStreamMappedCollection<TKey, TValue>, a collection of logical key/value entries.
Its ObjectStream remains non-generic because standard dictionaries store pairs
and constant-length-key dictionaries store values with a separate key index.
Existing public class methods and inherited dispatch remain supported.
Compatibility adapters remain where class overrides, interface remapping,
backing storage or event subscriptions affect behavior. Interface bridges are
implemented directly in their Base Interface Bridges regions, preserving checked
collection counts and indexes. Class implementations take
precedence over interface defaults, and defaults are called through interface
references.
Scope ownership and composition
Small cleanup scopes implement IScope as structs and finalize directly. Use Tools.Scope.ExecuteOnDispose for an Action finalizer or Tools.Scope.ExecuteOnDisposeAsync for a Func<ValueTask> finalizer. Generic factories take the callback first and the item second, returning concrete ActionScope / ActionScope<T> or TaskScope / TaskScope<T> structs directly. Both support both disposal directions and retain a typed callback without runtime delegate-type selection. Generic constructors take the item first and a static callback second to avoid capturing that item. SyncScope / SyncScope<T> permit synchronous disposal only; AsyncScope / AsyncScope<T> permit asynchronous disposal only. Constructors guard required callbacks and resources; default required-resource scopes are invalid. NoOpScope and NoOpScope<T> explicitly perform no cleanup, and the generic form borrows its Item. Tools.Scope retains domain scope factories. Adapt existing tasks with new ValueTask(task) in an ExecuteOnDisposeAsync callback to preserve asynchronous completion.
Keep one owner and one normal disposal per acquisition. There are no lifecycle flags, reentry suppression, automatic retry or pending-operation caches; repeated explicit disposal invokes the finalizer again. Interface conversions and struct method groups can box or copy the same resource ownership. Context, transaction and serialization scopes retain their actual class identity and domain logic, without artificial struct facades or generic disposal-state classes.
ActionScope.Dispose() invokes its callback directly, while DisposeAsync() offloads through Task.Run. TaskScope.DisposeAsync() awaits its callback; synchronous disposal starts that callback on a worker outside the caller's synchronization context and waits for actual completion. Both preserve callback faults. Native monitor/read/write scopes require synchronous using and reject async disposal, as do synchronous-only DPI/token scopes. Control-backed UI cleanup queues to its owning dispatcher. Async cleanup must return before blocked work completes and represent the resource's actual completion.
ISynchronizedObject and ISynchronizedObject<TReadScope, TWriteScope> share only IReaderWriterLock.ThreadLock; they retain separate concrete scope return contracts. See resource scopes, synchronization and transaction ownership for ownership and execution boundaries.
π οΈ Tools.* Namespace β Global Tooling Framework
The Tools namespace is a defining feature of Sphere10 Framework, providing a global, IntelliSense-discoverable collection of static utility methods organized by domain. This acts as a single point of discovery for developersβinstead of searching for the right helper class, simply type Tools. and explore available operations across the entire framework.
π Getting Started: See the Tools Reference for the complete catalog and usage patterns.
Core Tools Classes
Framework-Wide Utilities
- Tools.Array β Array concatenation, cloning, filling and transposition
- Tools.Collection β Generation, repetition, partitioning, searching and array resizing
- Tools.Crypto β Secure random bytes, password hashing, AES helpers and secure erase
- Tools.Time β Unix-time conversion and date calculations
- Tools.Enums β Enumeration utilities, descriptions, conversion
- Tools.Exceptions β Exception handling, formatting, analysis
- Tools.Expressions β Compiled unary and binary operation factories
- Tools.FileSystem β File I/O, directory operations, temp file management
- Tools.Lambda β Delegate wrappers and setter expressions
- Tools.Maths / Tools.MathPlus β Mathematical operations and numeric calculations
- Tools.Memory β Memory metrics, primitive sizing and byte formatting
- Tools.Object β Object cloning, copying, inspection
- Tools.OperatorTool β Generic operator invocation (Add, Subtract, etc.)
- Tools.Parser β String parsing, type conversion
- Tools.Reflection β Reflection member access and invocation
- Tools.Runtime β Build flags, executable paths, entry-assembly access and design-mode checks
- Tools.Scope β Cleanup delegates and file/directory lifetime scopes
- Tools.Spans β Span and memory utilities
- Tools.Streams β Stream operations, routing, reading/writing and transformations
- Tools.Text β String manipulation, formatting, generation
- Tools.Threads β Threading utilities, synchronization, async helpers
- Tools.Url β URL parsing, encoding, manipulation
- Tools.Values β Value utilities, comparisons, clipping and futures
Platform-Specific Tools
Windows Integration
- Tools.Windows β Registry, services, security, processes, Win32 and shell facade (
Sphere10.Framework.Windows) - Tools.Windows.Forms β Cursor and window-settings utilities (
Sphere10.Framework.Windows.Forms)
Web & Networking
- Tools.Web.Html β HTML helpers (
Sphere10.Framework.Web) - Tools.Web.AspNetCore β ASP.NET Core helpers (
Sphere10.Framework.Web.AspNetCore) - Tools.Network β Local addresses, DNS, ping, traceroute, WHOIS, TCP port probes and DNS or TLS decoding (
Sphere10.Framework.Communications) - Tools.Mail β SMTP mail sending and address helpers (
Sphere10.Framework.Communications) - Tools.Web.Downloader β HTTP downloads (
Sphere10.Framework.Communications)
Database Access
- Tools.Data β Generic database helpers (
Sphere10.Framework.Data) - Tools.Sqlite β SQLite utilities (
Sphere10.Framework.Data.Sqlite) - Tools.MSSQL β SQL Server utilities (
Sphere10.Framework.Data.MSSQL) - Tools.NHibernate β String-mapping compatibility constant (
Sphere10.Framework.Data.NHibernate) - Tools.Xml β XML data helpers (
Sphere10.Framework.Data) - Tools.Json β JSON data helpers (
Sphere10.Framework.Data)
Mobile Platforms
- Tools.iOSTool β iOS-specific utilities (
Sphere10.Framework.iOS)
Application Framework
- Tools.Config β Application-setting reads (
Sphere10.Framework.Application) - Tools.NUnit β NUnit test helpers (
Sphere10.Framework.NUnit) - Tools.Drawing β Graphics and drawing helpers (
Sphere10.Framework.Drawing) - Tools.Debugger β Debug-time utilities (core
Sphere10.Framework)
Usage Pattern
using System.Linq.Expressions;
using Sphere10.Framework;
public static class ToolsUsageExample {
public static int[] GenerateAndGrow(int count) {
Guard.Argument(count >= 0, nameof(count), "Count must be nonnegative.");
var values = Tools.Collection.GenerateArray(count, index => index);
Tools.Collection.ResizeArray(ref values, checked((long)count + 1));
return values;
}
public static int Add(int left, int right)
=> Tools.Expressions.CreateExpression<int, int, int>(Expression.Add)(left, right);
public static byte[] HashData(byte[] data) {
Guard.ArgumentNotNull(data, nameof(data));
return Hashers.Hash(CHF.SHA2_256, data);
}
}
Tools is a global namespace. Select the existing facade and its owning project; importing Sphere10.Framework supplies contracts such as Guard and Hashers. Follow the utility practices and Tools Reference for the concrete API and ownership rules.
Design Philosophy
The Tools namespace embodies several key principles:
- Discovery-First: Type
Tools.to explore all available operations in IntelliSense - Consistency: Related operations grouped under consistent tool names
- Extensibility: Projects expose their owning APIs through Tools.* classes and static extensions (for example,
Tools.WindowsandTools.WinForms) - Composability: Tools methods work together seamlessly for complex operations
- Performance: Methods optimized for production use, with zero-allocation variants where possible
- Type Safety: Generic methods preserve type information, avoiding casts
Extending with Custom Tools
Extend the existing facade when it already owns the operation. A new domain can add a static class in namespace Tools;, following the framework's source headers, guards and naming conventions. See ArrayTool.cs for the declaring pattern and the Tools Reference for contributor guidance. The class becomes discoverable through Tools. when its owning project or package is referenced.
Platform assemblies can add C# 14 static extension members to an existing facade
without adding a reverse dependency. Tools.WinForms is supplied by the
Windows Forms assembly and requires using Tools; for extension lookup.
π Quick Navigation
Core Sphere10 Framework Library Domains
Data Structures & Collections
- π¦ Collections/ β Extended lists, stream-mapped, recyclable, paged, observable, synchronized variants
- π³ Merkle/ β Merkle-tree implementations: flat, simple, long, partial
- π ClusteredStreams/ β Multi-stream storage, attachments, dynamic allocation
Persistence & Serialization
- πΎ Serialization/ β Item serializers, polymorphism, references, versioning
- π ObjectSpaces/ β Typed dimensions, indexing, integrity proofs, transactions
- π ObjectStream/ β Stream-backed object storage with indexes
Transactions & Scoping
- π― Scopes/ β Transactional boundaries, commit/rollback, isolation levels
- π³ Transactions/ β Transaction management and coordination
Cryptography & Security
- π Crypto/ β Hashing, signatures, key derivation, VRF algorithms
Streams & I/O
- π Streams/ β Stream decorators, bounded, fragmented, extended memory
- π IO/ β File I/O operations and utilities
Utilities & Extensions
- βοΈ Text/ β String extensions, formatting, case operations, validation
- π€ Encoding/ β VarInt, CVarInt, compact integer encoding
- π§ Memory/ β Buffer operations, memory allocation, management
- β‘ Threading/ β Synchronization, producer-consumer patterns
- πΎ Cache/ β Action caches, reaping policies, session management
- ποΈ Repository/ β Repository pattern implementations
- π Mapping/ β Object mapping and transformation
- π² Conversion/ β Type conversions and parsing
- π Maths/ β Mathematical utilities
- π Values/ β Value types and structures
- ποΈ Comparers/ β Comparison and equality implementations
Type System & Reflection
- π Introspection/ β Reflection and type analysis
- π¦ Types/ β Type utilities and checks
- π·οΈ Attributes/ β Custom attributes
- π Framework/ β Framework abstractions
- π Extensions/ β Framework extension methods
Data & Resources
- π DataSource/ β Data source abstractions
- π Peripherals/ β Hardware peripherals access
- π Network/ β URL, query-string and MIME type utilities
- π― Environment/ β Environment and system information
- βοΈ Misc/ β Miscellaneous utilities
- π¦ Objects/ β Object utilities
- ποΈ Filter/ β Filtering abstractions
- π Functional/ β Functional programming utilities
- β»οΈ Disposables/ β Disposable pattern utilities
- π Events/ β Event handling utilities
- β οΈ Exceptions/ β Exception handling
- π Loadable/ β Loadable resource abstractions
- π Logging/ β Logging utilities
- πΎ Persistable/ β Persistence abstractions
- π§ Saveable/ β Save/load patterns
- β° Scheduler/ β Task scheduling
- π Calendar/ β Recurrence rules, calendar events and the calendar contract
- π Sizing/ β Size calculations and measurements
- π― Spans/ β Span and memory utilities
- π TextWriters/ β Text writing abstractions
Related Projects
Data Access & Persistence
- Sphere10.Framework.Data β Database abstraction layer (SQL Server, SQLite, Firebird)
- Sphere10.Framework.Data.Sqlite β SQLite-specific integration
- Sphere10.Framework.Data.MSSQL β SQL Server integration
- Sphere10.Framework.Data.Firebird β Firebird integration
- Sphere10.Framework.Data.NHibernate β NHibernate ORM integration
- Sphere10.Framework.Windows.LevelDB β High-performance embedded key-value store
Networking & Communications
- Sphere10.Framework.Communications β Typed message protocols, channels (pipes, TCP, UDP, WebSockets), JSON-RPC, and the network, mail and download tools
- Sphere10.Framework.Web.AspNetCore β ASP.NET Core integration and middleware
Cryptography & Consensus
- Sphere10.HashLib4CSharp β Hashes & checksums (SHA-1/2/3, BLAKE2, CRC; stream/file APIs)
- Sphere10.Framework.CryptoEx β Extended cryptography (ECDSA, ECIES, Schnorr, post-quantum)
- Sphere10.Framework.Consensus β Blockchain consensus mechanisms
Desktop & Platform Integration
- Sphere10.Framework.Windows β Windows utilities (registry, services, events, security)
- Sphere10.Framework.Windows.Forms β WinForms component integration
- Sphere10.Framework.Windows.Forms.Sqlite β SQLite integration for WinForms
- Sphere10.Framework.Windows.Forms.MSSQL β SQL Server integration for WinForms
- Sphere10.Framework.Windows.Forms.Firebird β Firebird integration for WinForms
- Sphere10.Framework.Drawing β Graphics and drawing utilities
Application Framework
- Sphere10.Framework.Application β Lifecycle management, DI, configuration, settings
Testing & Quality
- Sphere10.Framework.NUnit β NUnit testing utilities
- Sphere10.Framework.NUnit.DB β Database testing utilities
Cross-Platform & Generators
- Sphere10.Framework.Android β Android platform integration
- Sphere10.Framework.iOS β iOS platform integration
- Sphere10.Framework.macOS β macOS platform integration
- Sphere10.Framework.Generators β Code generation utilities
Test Suites
Core Library Tests
- Sphere10.Framework.Tests β Comprehensive test suite for all Sphere10 Framework domains
Related Project Tests
- Sphere10.Framework.Communications.Tests β Networking and protocol tests
- Sphere10.Framework.CryptoEx.Tests β Extended cryptography tests
- Sphere10.Framework.Data.Tests β Database integration tests
- Sphere10.Framework.Windows.Tests β Windows utilities tests
- Sphere10.Framework.Windows.LevelDB.Tests β LevelDB integration tests
- Sphere10.HashLib4CSharp.Tests β Cryptographic hash tests
π¨ Design Philosophy
Core Principles
Composability: The library is structured around small, focused abstractions that compose predictably. Decorators, adapters, and interfaces allow developers to layer functionality without tight coupling.
Explicit Control: Sphere10 Framework favors explicitness over magic. Memory allocation strategies, serialization formats, caching policies, and locking semantics are configurable rather than hidden behind opaque defaults.
Performance-Conscious: Many components are optimized for batch operations, memory locality, and reduced allocations. The library provides both in-memory and stream-backed variants of collections to accommodate different performance/capacity tradeoffs.
Extensibility: Core abstractions like IItemSerializer<T>, IExtendedList<T>, and ITransactionalScope are designed to be implemented or decorated by user code. The library provides building blocks rather than closed systems.
Correctness: Transaction-aware data structures emphasize ACID semantics where applicable. Merkle tree implementations prioritize cryptographic correctness. Thread-safety guarantees are explicit and documented.
β Non-Goals
- High-level Application Frameworks: Sphere10 Framework does not provide MVC frameworks, dependency injection containers, or application scaffolding.
- Platform Abstractions: The library does not abstract away platform-specific APIs beyond what .NET Standard requires.
- Opinionated Workflows: While the library enables patterns like repositories and transactional scopes, it does not enforce specific architectural patterns.
ποΈ Domains Covered
Collections
Sphere10 Framework provides an extensive suite of collection types that extend beyond the standard .NET collections:
- Extended Lists and Collections: Interfaces like
IExtendedList<T>andIExtendedCollection<T>support range-based operations (batch reads, writes, insertions, deletions) for improved performance when working with large datasets. - Stream-Mapped Collections: Collections such as
StreamMappedList<T>,StreamMappedDictionary<TKey, TValue>, andStreamMappedHashSet<T>persist their data to streams, enabling collections that exceed available memory while maintaining list/dictionary/set semantics. - Recyclable Lists:
IRecyclableList<T>and its implementations maintain a pool of reusable indices for deleted items, optimizing scenarios with frequent insertions and deletions. - Paged Collections: Both memory-paged and file-paged lists partition data into pages, supporting arbitrarily large datasets with configurable memory footprints.
- Observable Collections: Observable variants of standard collections expose events for monitoring mutations, supporting use cases like change tracking and logging.
- Synchronized Collections: Thread-safe variants like
SynchronizedExtendedList<T>,SynchronizedDictionary<TKey, TValue>, andProducerConsumerQueue<T>for concurrent scenarios. - Specialized Data Structures: Bloom filters, binary heaps, circular lists, bounded lists, and bidirectional dictionaries address specific algorithmic needs.
BoundedHistory<T> holds oldest-first observations with independent item-count and caller-defined cost bounds. TryAdd rejects an oversized observation and evicts oldest items until an accepted observation fits. Received, Discarded and RetainedCost distinguish admission/eviction from the current snapshot. Operations are synchronized; Snapshot() copies collection membership while borrowing item references. Use immutable/detached observations. Clear(false) releases retained observations while preserving counters; ordinary Clear() also resets them. Consumers choose meaningful byte/character costs rather than treating those units as interchangeable.
Tools.Network provides explicit asynchronous DNS, ICMP echo/traceroute and single-server WHOIS probes with cancellation/deadlines. Traceroute limits hops, reports actual ICMP status and separates probe elapsed time from successful-echo RTT. ReadWhoisAsync bounds its response and asks one server without following referrals. ReadWhoisChainAsync follows them from a first server over a bounded number of servers, finding each with FindWhoisReferral, and returns every answer. ProbeTcpPortAsync tries one TCP connection within a deadline and reports the port as Open, Closed or NoReply without sending anything on it. TryDecodeDnsMessage and TryDecodeTlsClientHello project bounded complete captured messages; they do not reassemble TCP streams or decrypt traffic. DNS names support bounded backward compression references, native RR codes and raw-prefix fallback for unsupported RR payloads. TLS records retain the legacy compatibility field separately from offered versions, observed SNI and ALPN.
Managed and stream-mapped B-tree, B+ and grouped lookup implementations expose family-specific new-tree defaults through Sphere10FrameworkDefaults. Stream constructors/factories that omit order require empty storage; existing trees require their original explicit order, serializer layout and endianness. The B-tree profiling guide explains the measured numeric and explicit wide-key settings, backend comparisons and limitations. These defaults do not migrate stored nodes or change generic ObjectStream index layouts.
Memorizing an enumerable
MemorizingIterator<T> lazily reads its source once and caches the values for repeated or interleaved traversals. Each traversal has its own position; struct copies and interface casts share the same cache. Its read-only collection members support Count, Contains, CopyTo, and LINQ materialization (ToArray/ToList). Count and CopyTo finish reading the source, retaining the memorized snapshot even if the original collection later changes.
The source enumerator is disposed when exhausted or when reading fails. A partial traversal keeps the source open so later traversals can continue; finish enumeration when the source owns resources. Source failures are replayed after the same cached prefix. Access from multiple threads requires external synchronization.
π Clustered Streams
The ClusteredStreams subsystem provides a sophisticated mechanism for managing multiple logical streams within a single underlying stream. This enables:
- Multi-Stream Storage: A single file or stream can host multiple independent logical streams, each with its own lifecycle and addressing.
- Dynamic Allocation: Streams grow and shrink dynamically, with clusters allocated and linked as needed.
- Metadata Storage: Headers and metadata are stored alongside stream data, supporting features like indexing and merkle-tree integration.
- Attachments: Pluggable
IClusteredStreamsAttachmentcomponents allow behaviors like indexing, merkle-tree maintenance, and key storage to be composed declaratively.
This architecture underpins the library's stream-mapped collections and object spaces, providing a flexible foundation for custom persistence schemes.
π Object Spaces
Object spaces abstract the storage and retrieval of typed objects across multiple "dimensions" (logical tables). Key capabilities include:
- Typed Dimensions: Each dimension stores objects of a specific type, with configurable serialization and indexing strategies.
- Indexing: Automatic or custom indexes accelerate lookups by projected keys. Both unique and non-unique indexes are supported.
- Merkle-Tree Integration: Optional merkle-tree attachments provide cryptographic proofs of data integrity.
- File Transactions:
FileObjectSpaceexposes explicit synchronous commit/rollback. Saved changes remain pending until commit; rollback invalidates previously tracked instances.
Object spaces provide structured embedded persistence. See the ObjectSpace guide for schemas, live-record enumeration, identity and ownership, unique/nonunique queries, autosave and current graph limitations. New stores use Sphere10FrameworkDefaults.ObjectSpaceIndexBTreeOrder (256), overridable through WithIndexBTreeOrder. Opening existing stores requires their original order or an already bound matching definition; historical default stores used 64. Follow the guide's storage-opening contract and preserve the original layout. The WinForms tester retains its original ObjectSpace screen. The ObjectSpace suite in the general profiling project compares storage and index settings using reproducible workloads.
π³ Merkle Trees
Sphere10 Framework includes multiple merkle-tree implementations optimized for different use cases:
- Flat Merkle Trees: Store all nodes in contiguous memory, optimized for fast random access and proof generation.
- Simple Merkle Trees: Lazily compute parent nodes, suitable for smaller trees where memory is less constrained.
- Long Merkle Trees: Designed for very large datasets, retaining only sub-root hashes in memory while supporting append and proof operations.
- Partial Merkle Trees: Maintain only a subset of nodes, useful for constructing and verifying multi-item proofs.
These implementations integrate with collections, enabling IMerkleList<T>, IMerkleDictionary<TKey, TValue>, and IMerkleSet<T> variants that maintain cryptographic integrity proofs alongside their data.
π Cryptography
The library provides cryptographic primitives and utilities:
- Hashing: The
Hashersregistry with SHA-1, SHA-2 (SHA-256, SHA-384, SHA-512), BLAKE2b andConcatBytes, plus MurMur3 checksums. SHA-3 and the other hash functions come from Sphere10.Framework.CryptoEx, which registers them. - Digital Signatures: Abstractions for signature schemes, including the stateless schemes base that CryptoEx's ECDSA and Schnorr implement, and post-quantum candidates (W-OTS, W-OTS#, AMS).
- Key Derivation: PBKDF2 and custom key derivation functions.
- Verifiable Random Functions (VRF): Primitives for generating cryptographically verifiable random outputs.
- Data Protection: Secure memory handling and encryption utilities for sensitive data.
π¦ Serialization
Sphere10 Framework's serialization framework is designed for efficiency, control, and extensibility:
- Item Serializers: The
IItemSerializer<T>abstraction enables custom serialization logic for any type. Serializers can be composed, decorated, and registered in aSerializerFactory. - Polymorphic Serialization: Support for serializing and deserializing class hierarchies with type discrimination using
[KnownSubType]attributes. - Reference Handling: Automatic tracking and resolution of object references and cycles within a serialization context.
- Constant-Size Serialization: Specialized serializers for fixed-width data, enabling efficient indexing and random access.
- Versioning: Support for versioned serialization strategies, allowing schemas to evolve over time.
The framework integrates deeply with the library's collections and storage primitives, ensuring that persistence strategies are explicit and customizable.
βοΈ Transactions
The transactional subsystem provides commit/rollback primitives for configured file-backed collections and custom backends:
- Transactional Scopes:
ITransactionalScopedefines begin/commit/rollback operations. Context-aware scopes coordinate nesting and ownership; the concrete backend determines isolation and participation. - Transactional Collections:
TransactionalList<T>,TransactionalDictionary<TKey, TValue>, andTransactionalHashSet<T>provide ACID semantics over persistent storage. - Transactional Streams:
TransactionalStreamwraps a stream with commit/rollback capabilities, enabling atomic multi-operation updates. - File Transactions:
FileTransactionandFileTransactionScopecoordinate file-system operations within a transactional boundary.
These primitives enable building robust, crash-recoverable data stores without relying on external database engines.
πΎ Caching
The caching subsystem offers flexible, policy-driven caching mechanisms:
- Action Caches: Populate cache entries on-demand using delegates.
- Bulk-Fetch Caches: Refresh all entries in a single operation when any entry becomes stale.
- Session Caches: Expire entries based on last-access time, suitable for session-style semantics.
- Reaping Policies: The typed cache engine selects victims and frees fractional headroom under capacity pressure.
PooledCacheReapercoordinates a shared budget across differently typed caches through the key/value-freeICacheBasecontract.
The generic engine stores keys and values directly; nongeneric CacheBase specializes it for objects. ReapLevel is a finite fraction strictly between zero and one (initial default 0.25), measured against capacity in the estimator's units. Read the cache guide for pinning, replacement accounting, shared pools and ownership.
π‘ Protocol and Communication
Typed message protocols (Protocol, ProtocolBuilder, ProtocolOrchestrator and ProtocolChannel) are in Sphere10.Framework.Communications, together with the pipe, TCP, UDP and WebSocket channels that carry them. The core library has no networking.
π² Streams and I/O
Sphere10 Framework extends .NET's stream abstractions with specialized implementations:
- Bounded Streams: Restrict read/write operations to a defined segment of an underlying stream.
- Fragmented Streams: Compose multiple disparate byte fragments into a single logical stream.
- Extended Memory Streams: Use
IBufferas the backing store instead of a contiguous byte array, enabling arbitrarily large in-memory streams with paging support. - Transactional Streams: Wrap streams with commit/rollback semantics.
- Decorator Streams: Read-only, write-only, non-closing, and profiling stream wrappers.
π Logging
A flexible, composable logging framework:
- Logger Abstractions:
ILoggerdefines a simple, level-based logging interface. - Decorators: Prefix, timestamp, thread-ID, and synchronization decorators compose to customize log output.
- Sinks: Built-in loggers for console, debug output, files, and custom delegates.
- Multicast Logging: Route log messages to multiple sinks simultaneously.
π Threading and Concurrency
Utilities for managing concurrency and synchronization:
- Custom Synchronization Primitives:
ProducerConsumerLock,NonReentrantLock,FastLock, and minimal semaphore implementations. - Serial Thread Pool: Execute actions serially on a background thread, with configurable lifecycle policies.
- Critical Sections:
Critical<T>andCriticalObjectencapsulate objects with lock-based access. - Producer-Consumer Queue:
ProducerConsumerQueue<T>provides bounded/unbounded thread-safe queuing with async support.
β° Scheduling
A job scheduling framework with support for various triggers:
- Job Definitions: Wrap actions or async functions as jobs.
- Schedules: Interval-based, day-of-week, and day-of-month schedules trigger job execution.
- Policies: Control job behavior on failure, completion, and rescheduling.
βοΈ Text Extensions & String Utilities
Comprehensive string manipulation and validation helpers:
- Case Conversion: Convert between camelCase, PascalCase, snake_case, kebab-case, and UPPERCASE_SNAKE_CASE.
- Truncation & Padding: Pad strings to exact lengths or truncate with ellipsis.
- Validation: Check for numeric, alphabetic, alphanumeric, hexadecimal, and custom patterns.
- Parsing: Safe parsing with tuple results, parse integers, GUIDs, decimals, and custom types.
- Whitespace Operations: Split on whitespace, trim variants, normalize line endings.
- String Replacement: Pattern-based and regex replacements with proper escaping.
π€ Encoding Utilities
Efficient, space-optimizing encoding schemes:
- Variable-Length Integer Encoding (VarInt): Compress small integers into fewer bytes, with sign-aware variants.
- Compact Variable-Length (CVarInt): Further optimize encoding for extremely small or sparse datasets.
- Binary Encoding: Efficient methods for encoding multiple values into contiguous buffers.
- Bidirectional Encoding: Reversible encoding schemes that preserve ordering properties for indexed storage.
π§ Memory Management
Utilities for controlling and optimizing memory usage:
- Buffer Abstractions:
IBufferrepresents a sequence of bytes that can be memory-resident or memory-mapped. - Memory Pools: Reusable memory pools to reduce allocation pressure in high-throughput scenarios.
- Buffer Decorators: Add synchronization, capacity tracking, or transaction support to buffers.
- Byte Array Utilities: Comparison, concatenation, and transformation helpers for byte arrays.
π Object Mapping & Transformation
Map and transform objects between representations:
- Property Mapping: Copy values between objects with matching or custom property mappings.
- Conversion Chains: Compose multiple converters to transform between unrelated types.
- Specialized Mappers: Collections, dictionary, and array mapping with configurable merge strategies.
π² Type Conversion & Parsing
Flexible conversion utilities for type coercion:
- Bidirectional Conversion: Convert between any two types using registered converters.
- Numeric Conversions: Safe conversions between integer types with overflow checking.
- Enum Conversions: String to/from enum with case-insensitive options.
- Collection Conversions: Convert between array, list, set, and dictionary representations.
- Custom Converters: Register converters for application-specific types.
π Mathematical Utilities
Low-level math helpers and calculations:
- Bit Manipulation: Bit-counting, set/clear operations, endian conversions.
- GCD and LCM: Greatest common divisor and least common multiple calculations.
- Prime Number Operations: Primality testing and prime enumeration.
- Modular Arithmetic: Modular exponentiation and inversion.
- Rounding: Floor, ceiling, and banker's rounding for financial calculations.
π Value Types & Structures
Utilities for working with value types and immutable structures:
- Date/Time Wrappers: Normalized date/time representations for storage.
- Numeric Types: Custom numeric wrappers for specialized domains (e.g., hash values, checksums).
- Struct Utilities: Struct cloning, comparison, and hashing helpers.
ποΈ Comparison & Equality
Build custom comparison and equality implementations:
- Comparer Factories: Create
IComparer<T>instances with fluent composition (field-by-field, descending, custom). - Equality Comparers: Implement
IEqualityComparer<T>for custom equality logic. - Structural Comparison: Compare complex objects field-by-field with customizable rules.
- Tolerance-Based Comparison: Compare floating-point values with configurable epsilon.
π Introspection & Reflection
Reflection utilities and type analysis:
- Type Discovery: Find derived types, implementations of interfaces, and generic arguments.
- Property/Field Analysis: Discover properties, fields, and their attributes with caching.
- Method Resolution: Find methods by name, signature, and attributes.
- Attribute Retrieval: Efficiently retrieve custom attributes from types, methods, and properties.
- Generic Type Analysis: Decompose and analyze generic type definitions and arguments.
π¦ Type Utilities
Helpers for type checks and resolution:
- Type Verification: Check if a type is numeric, nullable, enumerable, etc.
- Type Classification: Categorize types (value, reference, generic, etc.).
- Type Conversion Checks: Verify if one type can be converted to another.
- Default Value Generation: Create default instances for arbitrary types.
π·οΈ Attributes & Metadata
Custom attributes for annotating types and members:
- Serialization Attributes: Mark fields/properties for serialization with options.
- Validation Attributes: Declarative validation rules (required, length, range).
- Mapping Attributes: Customize property mapping behavior.
- Custom Attributes: Base classes for creating domain-specific attributes.
π Framework Abstractions
Core abstractions for building extensible frameworks:
- Loadable: Abstract base for objects with load/reload semantics.
- Persistable: Abstract base for objects that need to save/restore state.
- Saveable: Simplified save pattern for simpler scenarios.
- Disposables: Helpers for implementing safe disposal patterns.
- Environment: Abstract environment information (OS, runtime, configuration).
π Extension Methods on Core Types
Fluent extensions for .NET types:
- Enumerable Extensions:
Batch,Chunk,Distinct,GroupByvariants with custom comparers. - Dictionary Extensions:
TryAdd,AddOrUpdate,GetOrAddwith custom logic. - Task Extensions: Timeout, retry, async coordination helpers.
- Functional Extensions:
Map,FlatMap,Filterfor more expressive LINQ alternatives.
π Data Source Abstractions
IDataSource<T> supplies item/range CRUD, validation, count/capabilities and paged
reads. Choose the synchronous (SyncDataSourceBase<T>) or asynchronous (AsyncDataSourceBase<T>) lineage and
its item-first or batch-first base according to the source's actual primitive; every Sync* base has an Async*
dual. See the data-source practice.
- DataSourceFormatting is the shared search/sort text of inventory values. Sources built on these bases elsewhere include
NetworkProbeDataSourcein Sphere10.Framework.Communications andProcessDataSourcein Sphere10.Framework.Application. - ListDataSource<T> is the loadable list storage on the synchronous lineage (
ILoadableDataSource<T>:RequiresLoad,Load,LoadAsync(token)): it wraps an existing list or, derived, fetches one throughFetch(); its dual on the asynchronous lineage, AsyncListDataSource<T>, fetches throughFetchAsync(token); both search and sort before paging, notify committed CRUD and refresh rows throughRefreshMethod/RefreshMethodAsync.ActionListDataSource<T>/ActionAsyncListDataSource<T>compose a leaf from a callback. ProjectedDataSource<TFrom,TTo>adapts representations using forward/inverse maps.- ArrayDataSource<T> is the read-only store over one array a screen or control pushes (
ReplaceData), with property-based search, raw-value sorting, clamped paging andFormatValue/CopyItemForReadhooks, without a Windows or visual dependency. - RefreshableDataSourceBase<T,TConcrete> and PollingDataSource<T,TConcrete> are the feature decorators over
DataSourceDecorator; they are direction-agnostic and work over a synchronous or an asynchronous source. A refresh creates a fresh source through the template'sCreateDataSource()hook (ActionRefreshableDataSource takes a client factory), loads it in the caller's direction, swaps it in under the publication lock, disposes the old one and raisesChanged(Refresh,RefreshAsync,Current,Completion,CanPublish,Publish,DisposeAsync). Polling addsEnabled,AutoRefresh,RefreshInterval, one repeating FrameworkSchedulerjob,RefreshFailedand permanentStopAsync. See the data-source practice. - DebugExtensions adds
Debug.AssertNotMainThread()and message/detail overloads. SetDebug.MainThreadat the application entry point; the Debug-only check compares that captured thread with the executing thread. See foreground-thread assertions.
using System.Diagnostics;
using Sphere10.Framework;
using Sphere10.Framework.Application; // ProcessDataSource, from the Sphere10.Framework.Application package
var rows = new ArrayDataSource<Row>();
rows.ReplaceData(new[] { new Row(2, "Alpha"), new Row(1, "ALPHA") });
var page = rows.ReadRange("alpha", 1, 0, nameof(Row.Id), SortDirection.Ascending);
// page contains ID 1, Page 0 and TotalCount 2.
// The source an application activates: polling over a refreshable over loadable storage.
var processes = new PollingDataSource<Process>(new ActionRefreshableDataSource<Process>(() => new ProcessDataSource()));
processes.Enabled = true;
await processes.RefreshAsync();
public sealed record Row(int Id, string Name);
ArrayDataSource<T> and the list storage search public readable nonindexed instance
properties, with invariant default text and case-insensitive matching/string sorting;
derive and override FormatValue for specialized search text. Comparable raw values
retain their native ordering, so formatted numbers do not sort lexicographically; an
unknown sort name keeps the published order. Membership arrays are copied on
replacement and access; row object ownership remains with the caller. Configure
default sorting before publishing the source. Array mutation/validation operations
remain unsupported. Native consumers can bind a capture source through the WinForms
VisualGridArrayController<T>; core retains no visual dependency.
Array tests,
list tests,
refreshable tests and
polling tests
exercise query, ownership, concurrency, swap and lifecycle behavior.
A refresh never re-fetches into the served source: the fresh source loads on a
worker while the served one stays readable, an explicit Publish wins over an older
refresh, and a refresh that fails or is cancelled leaves the served source in place.
Native process, service, endpoint and storage sources in Framework.Windows are such
loadable storage, without imposing sampling timers or application display policy.
π Peripherals & Hardware Access
Utilities for hardware and peripheral interaction:
- Device Detection: Discover and enumerate hardware peripherals.
- Serial Communication: Serial port abstractions for embedded systems.
- GPIO Abstractions: General-purpose I/O operations (where applicable).
π Network Utilities
The core's Network domain covers addresses as text only:
- URLs:
Tools.Urlparses, combines and encodes URLs and makes slugs. - Query strings:
QueryStringBuilderrenders typed name and value pairs. - MIME types:
Tools.FileSystem.GetMimeTypeandTryGetMimeTypetake a file path, a file name or an extension ("report.pdf","png"or".png") and look the extension up in theMimeHelpertable, generated from mime-db and loaded on first use.
DNS, ping, traceroute, WHOIS, port probes, mail and downloads are in Sphere10.Framework.Communications.
π― Environment & System Information
Query system and runtime information:
- Runtime Detection: Detect .NET version, platform, architecture.
- Resource Availability: Check available memory, processor count, disk space.
- Configuration: Access environment variables, system settings.
- External Processes:
ProcessSentryruns a command and collects its output. The running-process data source and process-tree helpers are in Sphere10.Framework.Application.
βοΈ Miscellaneous Utilities
Catch-all category for specialized helpers:
- Range Calculations: Compute overlaps, unions, and intersections of value ranges.
- Enum Utilities: Enum iteration, flag manipulation, parsing.
- Bitfield Helpers: Work with bitfields and bit arrays.
- Weak References: Managed weak reference pools to track objects without preventing GC.
π¦ Object Utilities
Helpers for object manipulation and introspection:
- Cloning: Deep and shallow cloning with customizable strategies.
- Comparison: Object equality and comparison without reflection overhead (when possible).
- Hashing: Consistent hashing for distributed scenarios.
ποΈ Filtering Abstractions
Generic filtering framework:
- Predicates: Composable
IFilter<T>implementations for filtering collections. - Composite Filters: Combine filters with AND, OR, and NOT logic.
- Range Filters: Filter by numeric or comparable ranges.
π Functional Programming Utilities
Support for functional programming patterns:
- Monads: Maybe/Option and Result types for error handling.
- Function Composition: Compose functions with automatic currying.
- Lazy Evaluation: Lazy sequences and deferred computation.
- Partial Application: Bind arguments to create specialized functions.
β»οΈ Disposable Pattern Helpers
Simplify implementing proper disposal:
- Base Classes:
DisposableBaseandDisposableObjecthandle disposal protocol. - Safe Finalization: Finalization helpers to ensure cleanup occurs.
- Resource Guards: RAII-style resource management patterns.
π Event Handling Utilities
Framework for event routing and aggregation:
- Event Aggregators: Pub/sub patterns for decoupled event routing.
- Event Priorities: Route events in priority order.
- Event Filtering: Conditionally route events based on predicates.
β οΈ Exception Handling
Utilities for robust error handling:
- Exception Wrapping: Preserve stack traces while wrapping exceptions.
- Retry Policies: Exponential backoff, jitter, and custom retry strategies.
- Exception Aggregation: Collect multiple exceptions and report together.
- Error Context: Attach context information to exceptions for debugging.
π Loadable Resources
Framework for loading and caching resources:
- Resource Loaders: Abstract protocol for loading resources (files, embedded, remote).
- Caching Loaders: Cache loaded resources with expiration policies.
- Lazy Loading: Load resources on-demand with automatic caching.
π Logging Framework
Already covered above in detail.
πΎ Persistable Objects
Framework for objects that maintain persistent state:
- State Snapshots: Capture object state for persistence.
- Transactional Persistence: Integrate with transactional scopes.
- Version Tracking: Track object versions across saves.
π§ Save/Load Patterns
Simplified persistence for straightforward scenarios:
- Serialization Delegates: Custom load/save functions per type.
- Stream-Based Saving: Write objects to streams with format flexibility.
- File-Based Persistence: High-level API for file-based saves.
π Sizing Utilities
Calculate sizes and offsets:
- Byte Size Calculation: Determine how many bytes a serialized object requires.
- Alignment Calculation: Compute aligned offsets for memory layout optimization.
- Capacity Planning: Estimate total storage needed for collections.
π― Span & Memory Utilities
Efficient working with Span<T> and Memory<T>:
- Span Slicing: Safe slicing with bounds checking.
- Memory Pooling: Rent and return
Memory<T>from pools. - Span Conversion: Convert between
Span,Memory, and arrays safely.
π TextWriter Abstractions
Extensions and helpers for TextWriter:
- Formatted Output: Structured output writers (JSON, XML, CSV).
- Indented Writers: Automatic indentation for hierarchical data.
- Buffered Writers: Batch write operations for efficiency.
π οΈ Extensions & Utilities
50+ Extension Methods covering:
StringExtensions: Truncation, case handling, validation, parsing, formattingEnumerableExtensions: Filtering, grouping, transformation, batchingTaskExtensions: Async utilities, timeout handling, retry logicStreamExtensions: I/O operations, reading/writing helpersTypeExtensions: Reflection helpers, type resolution- And many more...
π‘ Key Concepts
Extended Lists
IExtendedList<T> extends the standard IList<T> interface with range-based operations: ReadRange, UpdateRange, InsertRange, and RemoveRange. These methods accept long indices and counts, supporting collections larger than 2GB. Implementations are expected to optimize batch operations rather than iterating element-by-element.
Stream-Mapped Collections
Stream-mapped collections persist their data to streams using serializers and cluster-based storage. They behave like standard collections but their contents reside on disk (or any stream) rather than entirely in memory. This enables collections to scale beyond available RAM while maintaining familiar APIs.
Object Streams
ObjectStream<T> is a low-level primitive for storing a sequence of serialized objects in a stream, along with metadata and indexes. It underpins stream-mapped collections and object spaces, providing features like:
- Recyclable item slots (deleted items can be reused)
- Pluggable indexes for fast lookups
- Merkle-tree integration for integrity proofs
- Metadata tracking (timestamps, checksums, etc.)
Serialization Context
SerializationContext tracks object references and cycles during serialization/deserialization. When a reference-type object is serialized, the context checks if it has been seen before. If so, a reference marker is emitted rather than re-serializing the object. This enables correct handling of cyclic graphs and repeated references.
Transactional Scopes
ITransactionalScope defines the lifecycle of a backend transaction:
BeginTransaction(): Start a new transaction.Commit(): Commit through the owning scope, respecting nested rollback votes.Rollback(): Roll back through the owning scope, or record a nested rollback vote.
The corresponding asynchronous methods are BeginTransactionAsync(), CommitAsync() and RollbackAsync(). BeginTransaction() returns void; the scope itself is consumed with using or await using.
Concrete transaction scopes are classes deriving from TransactionalScopeBase<TTransaction>, which extends ContextScope and coordinates transaction ownership and nesting within a logical call context. Isolation and which operations participate are determined by the concrete backend; sharing a context does not automatically enlist every ITransactionalObject. Disposal closes an owned transaction, but the common policy does not automatically call Rollback(). See resource scopes for ownership and cleanup rules.
Merkle Coordinates and Proofs
A MerkleCoordinate identifies a node within a merkle tree by its level and index. Merkle proofs are represented as sequences of MerkleNode instances, which can be verified against a root hash to confirm the presence and position of specific leaves. The library's merkle implementations expose methods for generating proofs and verifying them efficiently.
Decorators and Adapters
Many components follow the decorator pattern, allowing behavior to be layered:
StreamDecorator: Wrap a stream to add logging, profiling, or transaction support.ListDecorator<T>: Augment list behavior without reimplementing the entire interface.ItemSerializerDecorator<T>: Transform serialization logic (e.g., add null-handling or reference-tracking).
Adapters convert between related interfaces (e.g., IList<T> to IExtendedList<T>) to integrate external code with Sphere10 Framework's abstractions.
π― Typical Use Cases
Well-Suited Scenarios
- Embedded Databases: Build lightweight, file-based data stores with ACID transactions, indexing, and querying without a full database engine.
- Blockchain and Distributed Ledgers: Merkle-tree primitives and cryptographic utilities simplify integrity verification and proof generation.
- High-Volume Data Processing: Stream-backed collections and batch-optimized operations enable processing datasets larger than available memory.
- Custom Persistence Layers: Fine-grained control over serialization, storage layout, and transactional semantics.
- Cryptographic Applications: Post-quantum signature schemes and VRF implementations support advanced security requirements.
- Protocol Implementations: Structured communication for RPC, control protocols, or peer-to-peer messaging, with the protocol types from
Sphere10.Framework.Communications. - LevelDB Integration: Native Windows LevelDB wrapper for high-performance key-value storage.
π Less-Suited Scenarios
- Simple CRUD Applications: If standard Entity Framework or Dapper suffice, Sphere10 Framework's low-level primitives may introduce unnecessary complexity.
- Web APIs with Standard ORMs: The library does not integrate with ASP.NET or Entity Framework out-of-the-box.
- UI-Centric Applications: Sphere10 Framework focuses on data structures and persistence, not UI frameworks or bindings.
- Rapid Prototyping: The library's emphasis on explicitness and control trades off against rapid development convenience.
ποΈ Architecture Overview
Sphere10 Framework's architecture is organized into largely independent subsystems that compose through well-defined interfaces:
Collections Layer: Extended list and collection interfaces define the foundation. Implementations range from simple in-memory structures to complex stream-mapped and paged variants.
Storage Layer: Clustered streams provide the underlying mechanism for multi-stream persistence. Object streams layer serialization, indexing, and metadata on top of clustered streams.
Serialization Framework: A registry-based system (
SerializerFactory) maps types to serializers. Serializers compose via decorators for features like null-handling, polymorphism, and reference-tracking.Transactional Framework: Transactional scopes coordinate commit/rollback for the transaction they own and its enlisted operations. Transactional collections, streams and object spaces expose
ITransactionalObject; that contract alone does not enlist them in an unrelated scope.Merkle Trees: Separate implementations provide different tradeoffs. Merkle-aware collections integrate tree maintenance into their mutation operations.
Utilities and Extensions: Comparers, operators, logging, threading, and I/O utilities provide cross-cutting functionality without coupling to core abstractions.
Data typically flows from application code through collections or object spaces, which delegate to object streams for persistence. Object streams use clustered streams for storage and serializers for encoding. Transactional backends coordinate their participating mutations, and merkle trees provide integrity proofs where enabled.
π Getting Started
Installation
NuGet Packages:
# Core library
dotnet add package Sphere10.Framework
# Platform-specific (optional)
dotnet add package Sphere10.Framework.Windows # Windows utilities
dotnet add package Sphere10.Framework.Windows.Forms # WinForms integration
dotnet add package Sphere10.Framework.Windows.LevelDB # Native LevelDB wrapper
dotnet add package Sphere10.Framework.CryptoEx # Extended cryptography (ECDSA, ECIES)
dotnet add package Sphere10.Framework.Communications # Networking & protocols
dotnet add package Sphere10.Framework.Web.AspNetCore # ASP.NET Core integration
Or reference compiled assemblies directly in your project.
10-Second Example
using Sphere10.Framework;
using System.IO;
using System.Text;
// BinarySerializer: Object serialization with type registrations
var serializer = new BinarySerializer();
using var stream = new MemoryStream();
serializer.Serialize(stream, "Hello World");
stream.Position = 0;
var restored = (string)serializer.Deserialize(stream);
// StreamMappedList: List over a caller-owned backing stream
using var fileStream = new FileStream("data.bin", FileMode.Create, FileAccess.ReadWrite);
using var list = StreamMappedFactory.CreateList<string>(fileStream, 4096, StringSerializer.UTF8, autoLoad: true);
list.Add("Persisted Item 1");
list.Add("Persisted Item 2");
fileStream.Flush();
// FlatMerkleTree: Cryptographic proof of integrity
var tree = new FlatMerkleTree(CHF.SHA2_256);
tree.Leafs.AddRange(Encoding.UTF8.GetBytes("Block 1"), Encoding.UTF8.GetBytes("Block 2"));
var root = tree.Root; // Root hash proves all items
// Synchronized collections: Thread-safe variants
var syncList = new SynchronizedExtendedList<int>();
syncList.Add(42); // Automatically locked during mutation
π» Core Examples
BinarySerializer and Fixed-Size Item Serialization
using Sphere10.Framework;
using System.IO;
public static class BinarySerializationExamples {
public static object RoundTripObject(object value) {
var serializer = new BinarySerializer();
using var stream = new MemoryStream();
serializer.Serialize(stream, value);
stream.Position = 0;
return serializer.Deserialize(stream);
}
public static int ReadIndexedInteger(int[] values, int index) {
Guard.ArgumentNotNull(values, nameof(values));
Guard.Argument(index >= 0 && index < values.Length, nameof(index), "Index must identify an input value.");
var serializer = PrimitiveSerializer<int>.Instance;
using var stream = new MemoryStream();
using (var writer = new EndianBinaryWriter(EndianBitConverter.Little, stream.AsNonClosing())) {
foreach (var value in values)
serializer.Serialize(value, writer);
}
stream.Position = checked(index * serializer.ConstantSize);
using var reader = new EndianBinaryReader(EndianBitConverter.Little, stream.AsNonClosing());
return serializer.Deserialize(reader);
}
}
BinarySerializer is non-generic: its stream overloads write and read objects, including type-registration metadata and configured reference handling. It does not perform compression or promise a fixed byte size. The indexed example instead uses the constant-size PrimitiveSerializer<int> and an explicit endian reader/writer; AsNonClosing() lets those wrappers be disposed while the example retains ownership of its memory stream.
StreamMappedList: Disk-Backed Collections
Construct stream-mapped lists through StreamMappedFactory.CreateList<T>(). The Product model and CustomProductSerializer definitions appear below:
using System;
using System.Linq;
using Sphere10.Framework;
using System.IO;
static class StreamMappedListExample {
public static void CreateInventory(string filePath) {
using var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
using (var inventory = StreamMappedFactory.CreateList<Product>(stream, 4096, new CustomProductSerializer(), autoLoad: true)) {
inventory.Add(new Product { Id = 1, Name = "Widget", Price = 9.99m });
inventory.AddRange(new[] {
new Product { Id = 2, Name = "Gadget", Price = 19.99m },
new Product { Id = 3, Name = "Doohickey", Price = 14.99m }
});
}
stream.Flush();
}
public static Product[] ReadBatch(string filePath, long index, long count) {
using var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
using var inventory = StreamMappedFactory.CreateList<Product>(stream, 4096, new CustomProductSerializer(), autoLoad: true);
return inventory.ReadRange(index, count).ToArray();
}
public static long CreateTextLookup(string filePath) {
using var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
var serializer = SerializerFactory.Default.GetSerializer<string>();
using var list = StreamMappedFactory.CreateList<string>(
stream,
4096,
serializer,
itemComparer: StringComparer.Ordinal,
itemChecksummer: new ItemDigestor<string>(CHF.Blake2b_128, serializer, Endianness.LittleEndian),
reservedStreams: 2,
optionalItemChecksumIndexName: "TextChecksum",
autoLoad: true
);
list.Add("Important data");
return list.IndexOfL("Important data");
}
}
autoLoad: true initializes or loads the container before use. Collection mutations update the backing stream; there is no list Save() method. The factory owns the list's object/cluster containers, while these examples retain ownership of their FileStream and dispose it after the list. Reopening must use the same serializers, cluster layout, endianness and attachment configuration. ReadRange reads the selected items; materializing the result before disposal keeps the returned values usable. Metadata, indexes, selected items and runtime limits still require memory.
The checksum example registers a named lookup attachment and reserves streams for its forward and reverse stores. Checksums narrow lookup candidates; equality comparisons resolve collisions. This is not automatic payload-corruption verification. See StreamMappedFactory and collections/storage guidance.
StreamPagedList: Memory-Paged Disk Collections
using Sphere10.Framework;
using System.IO;
// StreamPagedList loads pages into memory as needed (more efficient for sequential access)
using var pagedStream = new FileStream("pages.dat", FileMode.Create, FileAccess.ReadWrite);
var pagedList = new StreamPagedList<string>(
new StringSerializer(Encoding.UTF8),
pagedStream,
pageSize: 4096 // 4KB pages, tuned for your access patterns
);
// Add thousands of items
for (int i = 0; i < 100_000; i++) {
pagedList.Add($"Item {i}");
}
// Sequential access is fast (page already in memory)
for (int i = 0; i < 10; i++) {
Console.WriteLine(pagedList[i]);
}
// Random access loads the needed page
var item50000 = pagedList[50000];
// For constant-size items, use constant-size serializer for direct indexing
var constSizeList = new StreamPagedList<string>(
new StringSerializer(Encoding.UTF8).AsConstantSize(50), // Fixed 50-byte strings
pagedStream,
pageSize: 4096
);
// Now can directly calculate position: position = itemIndex * itemSize
// Without scanning through variable-length items
FlatMerkleTree: Cryptographic Integrity Proofs
using Sphere10.Framework;
using System.Security.Cryptography;
// Create a flat merkle tree (all nodes in memory, optimal for proof generation)
var tree = new FlatMerkleTree(CHF.SHA2_256);
// Add data (hashed immediately)
var data = new[] {
Encoding.UTF8.GetBytes("Transaction 1"),
Encoding.UTF8.GetBytes("Transaction 2"),
Encoding.UTF8.GetBytes("Transaction 3"),
Encoding.UTF8.GetBytes("Transaction 4")
};
tree.Leafs.AddRange(data);
// Get root hash (proof that all items are included)
var rootHash = tree.Root;
Console.WriteLine($"Root: {Convert.ToHexString(rootHash)}");
// Generate proof for a specific item (prove item 2 is in tree)
var proof = tree.GenerateProof(2); // Generates merkle path
var leaf = tree.Leafs[2];
// Verify the proof (can be done independently)
bool verified = MerkleTreeUtilities.VerifyProof(
leaf,
proof,
rootHash,
CHF.SHA2_256
);
// FlatMerkleTree is ideal for:
// - Blockchain blocks (fixed number of transactions)
// - Smaller merkle trees where full tree fits in memory
// - Frequent proof generation
// Compare with LongMerkleTree for massive datasets
var longTree = new LongMerkleTree(CHF.SHA2_256);
// LongMerkleTree only keeps sub-root hashes in memory
// Can handle millions of items with minimal memory overhead
// But proof generation requires computing intermediate hashes
LongMerkleTree: Memory-Efficient Merkle Trees
using Sphere10.Framework;
// LongMerkleTree: For massive datasets (millions of items)
// Only stores sub-root hashes, not all nodes
var tree = new LongMerkleTree(CHF.SHA2_256);
// Append items efficiently
for (int i = 0; i < 1_000_000; i++) {
var data = Encoding.UTF8.GetBytes($"Item {i}");
tree.Leafs.AddRange(data);
}
// Root hash proves integrity of all million items
var root = tree.Root;
// Generate proof for an item
var proof = tree.GenerateProof(500_000);
// Verify proof (works same as FlatMerkleTree)
var leaf = tree.Leafs[500_000];
bool verified = MerkleTreeUtilities.VerifyProof(
leaf,
proof,
root,
CHF.SHA2_256
);
// LongMerkleTree advantages:
// - O(1) memory for append operations
// - Can handle unlimited items
// - Perfect for blockchain, event logs, append-only stores
// Size information
var size = tree.Size;
Console.WriteLine($"Leaf count: {size.LeafCount}");
Console.WriteLine($"Tree depth: {size.Depth}");
Synchronized Collections: Thread-Safe Wrappers
Use the existing synchronized decorators for shared collections. Individual members usually self-lock; an outer scope protects a compound operation or the consumption of a live view. See synchronization practices for enumeration, recursion, shared parent locks and thread-affinity rules.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sphere10.Framework;
// Each Add acquires its own write scope.
var syncList = new SynchronizedExtendedList<int>();
Parallel.For(0, 10, worker => {
for (var index = 0; index < 1000; index++)
syncList.Add(index);
});
Console.WriteLine($"Total items: {syncList.Count}"); // 10,000
// Copy the required data while the read scope protects enumeration.
var syncDict = new SynchronizedDictionary<string, Account>();
Parallel.For(0, 100, index => {
syncDict[$"account_{index}"] = new Account { Id = index, Balance = 100m };
});
KeyValuePair<string, decimal>[] balances;
using (syncDict.EnterReadScope())
balances = syncDict.Select(pair => new KeyValuePair<string, decimal>(pair.Key, pair.Value.Balance)).ToArray();
foreach (var balance in balances)
Console.WriteLine($"{balance.Key}: {balance.Value}");
// An outer write scope protects both the lookup and mutable account update.
using (syncDict.EnterWriteScope()) {
if (syncDict.TryGetValue("account_0", out var account))
account.Balance += 25m;
}
// The current SynchronizedSet members require explicit scopes.
var visited = new SynchronizedSet<int>();
using (visited.EnterWriteScope())
visited.Add(42);
// Wrap a real repository; the wrapper owns disposal of its inner repository.
using var syncRepo = new SynchronizedRepository<Product, int>(new DictionaryRepositoryAdapter<Product, int>(product => product.Id));
syncRepo.Create(new Product { Id = 1, Name = "Widget", Price = 9.99m });
if (syncRepo.TryGet(1, out var product))
Console.WriteLine(product.Name);
// Models also used by the stream-mapped collection example above.
class Account {
public int Id { get; set; }
public decimal Balance { get; set; }
}
class Product {
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
class CustomProductSerializer : ItemSerializerBase<Product> {
private readonly IItemSerializer<int> _idSerializer;
private readonly IItemSerializer<string> _nameSerializer;
private readonly IItemSerializer<decimal> _priceSerializer;
public CustomProductSerializer()
: this(SerializerFactory.Default) {
}
public CustomProductSerializer(SerializerFactory factory) {
Guard.ArgumentNotNull(factory, nameof(factory));
_idSerializer = factory.GetSerializer<int>();
_nameSerializer = factory.GetSerializer<string>();
_priceSerializer = factory.GetSerializer<decimal>();
}
public override long CalculateSize(SerializationContext context, Product item)
=> _idSerializer.CalculateSize(context, item.Id)
+ _nameSerializer.CalculateSize(context, item.Name)
+ _priceSerializer.CalculateSize(context, item.Price);
public override void Serialize(Product item, EndianBinaryWriter writer, SerializationContext context) {
_idSerializer.Serialize(item.Id, writer, context);
_nameSerializer.Serialize(item.Name, writer, context);
_priceSerializer.Serialize(item.Price, writer, context);
}
public override Product Deserialize(EndianBinaryReader reader, SerializationContext context)
=> new Product {
Id = _idSerializer.Deserialize(reader, context),
Name = _nameSerializer.Deserialize(reader, context),
Price = _priceSerializer.Deserialize(reader, context)
};
}
SynchronizedDictionary.Keys and Values retain the source dictionary's view
semantics; ordinary dictionary views are live, and their getters do not retain
a lock for later enumeration. The example instead copies keys and
balance values under an outer read scope and prints after releasing it. Mutable
entities returned by a dictionary or repository remain borrowed: users that
mutate them must participate in the same synchronization protocol.
SynchronizedCollection<T>, SynchronizedList<T>, SynchronizedExtendedList<T>,
SynchronizedDictionary<TKey, TValue>, SynchronizedQueue<T> and
SynchronizedHeap<T> provide self-locking ordinary operations. The current
SynchronizedSet<T> locks its enumerator but requires explicit scopes for its
ordinary methods and properties. Returned deferred range sequences likewise
need a scope covering their actual consumption.
SynchronizedRepository<TEntity, TIdentity> adds locking around an existing
IRepository<TEntity, TIdentity>; it does not add caching or a fetch delegate.
The example uses its synchronous Create and TryGet operations. Read
persistence and transaction practices
for repository composition and the existing async adapter limitations.
πΎ Persistence & Transactions
Read repository and persistence practices
for IRepository, ILoadable, ISaveable, IPersistable, directional bases,
nested transaction ownership and concrete backend guarantees. For collection
selection, read collection practices.
Advanced StreamMappedList Usage:
The StreamMappedList shown above demonstrates the core disk-backed storage pattern. For additional persistence options:
- Use
itemChecksummertogether withoptionalItemChecksumIndexNamefor an item lookup index; the checksum alone does not enable an index or verify payload integrity. - Allocate
reservedStreamsfor the configured index/metadata attachments and preserve that layout when reopening. - Configure
ClusteredStreamsPolicyto control cluster allocation
Transactional Scopes:
TransactionalDictionary<TKey, TValue> wraps stream-mapped storage and an ITransactionalObject. Construct its file backend with a Sphere10FrameworkFileDescriptor, load it, and explicitly call Commit() or Rollback(). It has no parameterless constructor or EnterScope() method:
using System;
using Sphere10.Framework;
public static class TransactionalDictionaryExample {
public static void UpdateBalances(string dataFile, string pagesDirectory) {
using var dictionary = Open(dataFile, pagesDirectory, FileAccessMode.OpenOrCreate);
dictionary.Load();
try {
dictionary["acc001"] = 1000m;
dictionary["acc002"] = 500m;
dictionary.Commit();
} catch (Exception operationError) {
try {
dictionary.Rollback();
} catch (Exception rollbackError) {
throw new AggregateException(operationError, rollbackError);
}
throw;
}
}
public static decimal ReadBalance(string dataFile, string pagesDirectory, string accountID) {
using var dictionary = Open(dataFile, pagesDirectory, FileAccessMode.Read);
dictionary.Load();
return dictionary[accountID];
}
private static TransactionalDictionary<string, decimal> Open(string dataFile, string pagesDirectory, FileAccessMode accessMode)
=> new(
Sphere10FrameworkFileDescriptor.From(dataFile, pagesDirectory),
SerializerFactory.Default.GetSerializer<string>(),
PrimitiveSerializer<decimal>.Instance,
keyChecksum: new ItemDigestor<string>(CHF.Blake2b_128, SerializerFactory.Default.GetSerializer<string>(), Endianness.LittleEndian),
reservedStreamCount: 3,
accessMode: accessMode
);
}
The caller supplies existing data/page directories; UpdateBalances commits before its dictionary is disposed, and ReadBalance opens the same backing file to read committed state. The variable-size string keys need the configured key checksummer for automatic dictionary layout selection; both opens use the same configuration. For transaction scopes that coordinate enlisted files, reuse FileTransactionScope and call BeginTransaction() on the scope itself; see custom transactional scopes. Scope disposal closes the owned transaction and does not imply automatic rollback by the common base. These are distinct transaction owners: a dictionary is not automatically enlisted in an unrelated scope.
π¦ Advanced Serialization Patterns
The serialization system supports reference-tracked graphs, polymorphic types, and custom decorators. See the Core Examples section above for BinarySerializer patterns. Refer to IItemSerializer<T> interface and SerializerFactory for custom implementations.
Merkle List with Integrity Proofs:
using Sphere10.Framework;
using System.Security.Cryptography;
// Create a merkle-aware list with SHA-256
var hasher = new HashAlgorithmAdapter(SHA256.Create());
var merkleList = new FlatMerkleList<string>(
ItemSerializer<string>.Default,
hasher
);
merkleList.Add("Block 1");
merkleList.Add("Block 2");
merkleList.Add("Block 3");
// Get root hash (commitment to entire list)
byte[] rootHash = merkleList.MerkleTree.Root;
// Generate proof that \"Block 2\" is at index 1
var proof = merkleList.MerkleTree.GenerateProof(1);
// Verify proof independently
var isValid = merkleList.MerkleTree.VerifyProof(
merkleList.GetItemHash(1),
1,
proof,
rootHash
);
Console.WriteLine($"Proof valid: {isValid}"); // true
Merkle Dictionary (Multiple Keys):
var merkleDictionary = new MerkleListAdapter<KeyValuePair<string, int>>(
new ExtendedList<KeyValuePair<string, int>>(),
hasher
);
merkleDictionary.Add(new KeyValuePair<string, int>("Alice", 100));
merkleDictionary.Add(new KeyValuePair<string, int>("Bob", 50));
// Prove integrity of multi-item state
var multiProof = merkleDictionary.MerkleTree.GenerateMultiProof(new[] { 0, 1 });
π¦ Serialization Examples
Built-in Serializers (Default):
using Sphere10.Framework;
public static class BuiltInSerializationExamples {
public static int RoundTripInt(int value) {
var serializer = SerializerFactory.Default.GetSerializer<int>();
var bytes = serializer.SerializeToBytes(value, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
public static ExtendedList<string> RoundTripList(ExtendedList<string> values) {
var serializer = SerializerFactory.Default.GetSerializer<ExtendedList<string>>();
var bytes = serializer.SerializeToBytes(values, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
}
Default registrations include the primitive and ExtendedList<T> serializers used here. For application types that need automatic assembly, use SerializerBuilder.FactoryAssemble<T>(factory) or retain their registrations with factory.RegisterAutoBuild<T>().
Custom Serializer Factory with Type Registration:
This deliberately starts with an empty factory to choose the string encoding and size descriptor. Register each required member serializer before registering the application's pure composite serializer:
using System.Text;
using Sphere10.Framework;
public sealed class FactoryMessage {
public string Text { get; set; }
}
public static class CustomFactoryExample {
public static FactoryMessage RoundTrip(FactoryMessage message) {
var factory = new SerializerFactory();
factory.Register<string>(new StringSerializer(Encoding.UTF8, SizeDescriptorStrategy.UseVarInt));
var pureSerializer = SerializerBuilder
.For<FactoryMessage>()
.Serialize(item => item.Text, factory.GetSerializer<string>())
.Build();
factory.Register<FactoryMessage>(pureSerializer);
var serializer = factory.GetSerializer<FactoryMessage>();
var bytes = serializer.SerializeToBytes(message, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
}
Usually, use new SerializerFactory(SerializerFactory.Default) to copy built-in registrations before adding new application types. Registrations cannot replace an existing type's mapping; do not re-register string in that copied factory. Register pure serializers, then obtain configured null/reference handling through GetSerializer<T>(). Applications exchanging these bytes must agree on registrations, layout and endianness.
Polymorphic Serialization (Inheritance Support):
using Sphere10.Framework;
[KnownSubType(typeof(Dog))]
[KnownSubType(typeof(Cat))]
public abstract class Animal {
public string Name { get; set; }
}
public sealed class Dog : Animal {
public bool IsWorkingDog { get; set; }
}
public sealed class Cat : Animal {
public int LivesRemaining { get; set; }
}
public static class PolymorphicSerializationExample {
public static Animal RoundTrip(Animal animal) {
var factory = new SerializerFactory(SerializerFactory.Default);
var serializer = SerializerBuilder.FactoryAssemble<Animal>(factory);
var bytes = serializer.SerializeToBytes(animal, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
}
The builder scans the [KnownSubType] declarations, assembles concrete serializers and uses a polymorphic serializer for the abstract Animal contract. Passing a Dog or Cat preserves its concrete type and public writable properties. Serialize collections with a collection serializer rather than passing a list to an IItemSerializer<Animal>.
Reference-Tracked Serialization (Graph Preservation):
Automatic assembly supplies composite instance activation and reference handling together, so members can refer back to an object that is still being populated:
using System;
using Sphere10.Framework;
public sealed class Node {
public string Value { get; set; }
public Node Next { get; set; }
}
public static class GraphSerializationExample {
public static Node RoundTripCycle() {
var factory = new SerializerFactory(SerializerFactory.Default);
factory.RegisterAutoBuild<Node>();
var serializer = factory.GetSerializer<Node>();
var first = new Node { Value = "A" };
var second = new Node { Value = "B", Next = first };
first.Next = second;
var bytes = serializer.SerializeToBytes(first, Endianness.LittleEndian);
var restored = serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
if (!ReferenceEquals(restored.Next.Next, restored))
throw new InvalidOperationException("The cycle was not preserved.");
return restored;
}
}
AsReferenceSerializer() is also a public extension for wrapping a pure serializer, but SerializerFactory rejects registration of a ReferenceSerializer<T> wrapper. Register the pure serializer and let factory lookup apply the wrapper. A custom cyclic graph serializer must implement the early activation contract; the reference wrapper alone cannot supply it.
Compact Integer Encoding (VarInt/CVarInt):
VarInt and CVarInt encode unsigned 64-bit values. VarInt uses a size prefix for larger values; 300 occupies three bytes. CVarInt uses its compact variable-length encoding, with 10000 occupying two bytes. The custom int serializer below accepts non-negative values and rejects encoded values beyond int.MaxValue when reading:
using System.IO;
using Sphere10.Framework;
public sealed class CompactSerializer : ItemSerializerBase<int> {
public override long CalculateSize(SerializationContext context, int item)
=> CVarInt.SizeOf(ToUnsigned(item));
public override void Serialize(int item, EndianBinaryWriter writer, SerializationContext context)
=> CVarInt.Write(ToUnsigned(item), writer.BaseStream);
public override int Deserialize(EndianBinaryReader reader, SerializationContext context)
=> checked((int)CVarInt.Read(reader.BaseStream));
private static ulong ToUnsigned(int item) {
Guard.Argument(item >= 0, nameof(item), "CompactSerializer requires a non-negative integer.");
return (ulong)item;
}
}
public static class CompactIntegerExamples {
public static ulong RoundTripVarInt(ulong value) {
using var stream = new MemoryStream();
VarInt.Write(value, stream);
stream.Position = 0;
return VarInt.Read(stream);
}
public static ulong RoundTripCVarInt(ulong value) {
var bytes = new CVarInt(value).ToBytes();
return CVarInt.Read(bytes);
}
public static int RoundTripNonNegativeInt(int value) {
var serializer = new CompactSerializer();
var bytes = serializer.SerializeToBytes(value, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
}
These compact encodings define their own byte layout; using them does not turn signed values into an unsigned encoding automatically. CVarIntSerializer.Instance and VarIntSerializer.Instance already serialize the corresponding framework value types.
Cryptographic Hashing:
using Sphere10.Framework;
var data = "Hello, World!";
// Standard hash functions
byte[] sha256 = Tools.Hashing.SHA256(data);
byte[] sha512 = Tools.Hashing.SHA512(data);
byte[] blake2b = Tools.Hashing.BLAKE2b(data);
byte[] murmurhash = Tools.Hashing.MurmurHash3(data);
// Hash files
byte[] fileHash = Tools.Hashing.SHA256File("path/to/file.bin");
// Compute multiple simultaneously
var hashes = Tools.Hashing.ComputeMultipleHashes(data, CHF.SHA2_256, CHF.SHA3_256);
// Hash files
byte[] fileHash = Tools.Hashing.SHA256File("path/to/file.bin");
// Compute multiple simultaneously
var hashes = Tools.Hashing.ComputeMultipleHashes(data, CHF.SHA2_256, CHF.SHA3_256);
π String Extensions (50+ helpers)
using Sphere10.Framework;
var text = "Hello World";
// Formatting & validation
var padded = text.PadToLength(20); // Pad or truncate to exact length
var truncated = text.Truncate(5); // Truncate with ellipsis
bool isEmpty = text.IsNullOrEmpty();
bool isWhitespace = " ".IsNullOrWhiteSpace();
// Type checking
bool isNumeric = "12345".IsNumeric();
bool isAlpha = "abc".IsAlpha();
bool isAlphaNumeric = "abc123".IsAlphaNumeric();
bool isHex = "DEADBEEF".IsHex();
// Case conversion
var camelCase = "hello_world".ToCamelCase(); // helloWorld
var pascalCase = "hello_world".ToPascalCase(); // HelloWorld
var snakeCase = "HelloWorld".ToSnakeCase(); // hello_world
// Parsing & extraction
var (success, number) = "42".TryParseInt();
var guid = "550e8400-e29b-41d4-a716-446655440000".TryParseGuid();
var words = "The quick brown fox".SplitOnWhitespace();
// Splitting & joining
var lines = "line1\nline2\nline3".ToLines();
var csv = new[] { "a", "b", "c" }.JoinWith(", ");
LevelDB Integration (High-Performance Key-Value Store):
using Sphere10.Framework.Windows.LevelDB;
// Open database
using var db = new DB("./mydata");
// Basic operations
var key = Encoding.UTF8.GetBytes("user:42");
var value = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(user));
db.Put(key, value);
var retrieved = db.Get(key);
if (retrieved != null) {
var restored = JsonSerializer.Deserialize<User>(Encoding.UTF8.GetString(retrieved));
}
// Batch operations (atomic)
using (var batch = db.CreateBatch()) {
for (int i = 0; i < 1000; i++) {
batch.Put(Encoding.UTF8.GetBytes($"key:{i}"), Encoding.UTF8.GetBytes($"value:{i}"));
}
db.Write(batch);
}
// Iteration & range queries
using (var iterator = db.CreateIterator()) {
iterator.SeekToFirst();
while (iterator.IsValid()) {
var k = Encoding.UTF8.GetString(iterator.Key());
var v = Encoding.UTF8.GetString(iterator.Value());
Console.WriteLine($"{k} = {v}");
iterator.Next();
}
}
π§ Extensibility & Customization
The library's design encourages extending core abstractions rather than modifying built-in types. Here are the main extension points:
Custom Serializers
Derive from ItemSerializerBase<T> to implement the IItemSerializer<T> contract. Implement sizing alongside serialization, and pass the supplied context and reader/writer to member serializers:
using Sphere10.Framework;
public class User {
public string Name { get; set; }
public int Age { get; set; }
}
public class UserSerializer : ItemSerializerBase<User> {
private readonly IItemSerializer<string> _stringSerializer;
private readonly IItemSerializer<int> _intSerializer;
public UserSerializer(SerializerFactory factory) {
Guard.ArgumentNotNull(factory, nameof(factory));
_stringSerializer = factory.GetSerializer<string>();
_intSerializer = factory.GetSerializer<int>();
}
public override long CalculateSize(SerializationContext context, User item)
=> _stringSerializer.CalculateSize(context, item.Name) + _intSerializer.CalculateSize(context, item.Age);
public override void Serialize(User item, EndianBinaryWriter writer, SerializationContext context) {
_stringSerializer.Serialize(item.Name, writer, context);
_intSerializer.Serialize(item.Age, writer, context);
}
public override User Deserialize(EndianBinaryReader reader, SerializationContext context)
=> new User {
Name = _stringSerializer.Deserialize(reader, context),
Age = _intSerializer.Deserialize(reader, context)
};
}
public static class UserSerializationExample {
public static User RoundTrip(User user) {
var factory = new SerializerFactory(SerializerFactory.Default);
factory.Register<User>(new UserSerializer(factory));
var serializer = factory.GetSerializer<User>();
var bytes = serializer.SerializeToBytes(user, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
}
The copied default factory supplies the string and integer serializers while keeping the custom registration local. This pure serializer expects a non-null User; factory lookup supplies the configured null/reference wrapper. Endianness belongs to the reader/writer, and the byte-array helpers accept it explicitly. See serialization guidance for factory registration, reference handling and stable wire formats.
Serializer Decorators
Use the public wrappers for nullable values and reference handling. ItemSerializerDecorator<T> is the reusable base for custom serializer decorators:
using Sphere10.Framework;
public static class SerializerDecoratorExamples {
public static int? RoundTripNullable(int? value) {
IItemSerializer<int?> serializer = new NullableSerializer<int>(PrimitiveSerializer<int>.Instance);
var bytes = serializer.SerializeToBytes(value, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
public static string RoundTripString(string value) {
IItemSerializer<string> serializer = new ReferenceSerializer<string>(
StringSerializer.UTF8,
ReferenceSerializerMode.SupportNull | ReferenceSerializerMode.SupportContextReferences
);
var bytes = serializer.SerializeToBytes(value, Endianness.LittleEndian);
return serializer.DeserializeBytes(bytes, Endianness.LittleEndian);
}
}
SerializerFactory.GetSerializer<T>() applies its configured reference/null handling; do not wrap an already reference-wrapped serializer in another ReferenceSerializer<T>. A graph serializer must support instance activation before reading members if cyclic references need to point back to the instance being constructed; wrapping a serializer alone does not add that activation contract.
Compression and encryption can be composed at the stream layer: supply an EndianBinaryWriter over the chosen transforming stream to Serialize, and use the matching inverse stream composition with an EndianBinaryReader for Deserialize. There are no public EncryptedSerializer<T> or CompressedSerializer<T> wrappers in this library. For EncryptedStream, follow its key, counter, authentication and ownership requirements.
Custom Indexes on Object Streams
Implement IProjectionIndex<TItem, TKey> to add custom indexing strategies:
public class LastNameIndex : ProjectionIndexBase<Person, string> {
public LastNameIndex(ObjectStream<Person> objectStream)
: base(objectStream) { }
public override string ProjectKey(Person item) => item.LastName;
protected override void OnIndexAdded(Person item, long index) {
// Store index mapping
}
public override long? TryGetIndex(string lastName) {
// Lookup by last name
return _indexStore.TryGetValue(lastName, out var idx) ? idx : null;
}
}
// Attach to ObjectStream
var objectStream = new ObjectStream<Person>(clusteredStreams, serializer);
var index = new LastNameIndex(objectStream);
objectStream.RegisterIndex(index);
// Query via index
var personIndex = index.TryGetIndex("Smith");
var person = objectStream[personIndex.Value];
Custom Transactional Scopes
TransactionalScopeBase<TTransaction> coordinates transaction ownership and nesting over ContextScope. Reuse the existing ActionTransactionalScope<TTransaction> class for synchronous backend delegates or TaskTransactionalScope<TTransaction> for asynchronous delegates. These are the actual domain owners, with direct finalization and no generic lifecycle-state layer or struct facade.
This complete example uses ActionTransactionalScope<DbTransaction> to wrap a provider's transaction. The caller supplies an already-open DbConnection and a context name; this scope requires that it be the root for that name:
using System;
using System.Data.Common;
using Sphere10.Framework;
public static class DatabaseTransactionExample {
public static ActionTransactionalScope<DbTransaction> CreateScope(DbConnection connection, string contextID) {
Guard.ArgumentNotNull(connection, nameof(connection));
return new ActionTransactionalScope<DbTransaction>(
ContextScopePolicy.MustBeRoot,
contextID,
connection.BeginTransaction,
static transaction => transaction.Commit(),
static transaction => transaction.Rollback(),
static transaction => transaction.Dispose()
);
}
public static void Execute(DbConnection connection, string contextID, Action<DbTransaction> operation) {
Guard.ArgumentNotNull(operation, nameof(operation));
using var scope = CreateScope(connection, contextID);
scope.BeginTransaction();
try {
operation(scope.Transaction);
scope.Commit();
} catch (Exception operationError) {
if (scope.ParticipatesWithinTransaction) {
try {
scope.Rollback();
} catch (Exception rollbackError) {
throw new AggregateException(operationError, rollbackError);
}
}
throw;
}
}
}
The operation must attach its database commands to the supplied transaction. The scope disposes that transaction; the caller retains ownership of the connection. Reuse existing backend scopes such as FileTransactionScope before introducing a custom scope. See directional sync/async hierarchies and transaction ownership.
Extending Collections
Decorate existing collections to add custom behavior:
// Add logging to list operations
public class LoggingList<T> : ExtendedListDecorator<T> {
private readonly ILogger _logger;
public LoggingList(IExtendedList<T> inner, ILogger logger) : base(inner) {
_logger = logger;
}
public override void Add(T item) {
_logger.Info($"Adding {item}");
base.Add(item);
}
public override void InsertRange(long index, T[] items) {
_logger.Info($"Inserting {items.Length} items at {index}");
base.InsertRange(index, items);
}
}
// Use transparently
var baseList = new ExtendedList<int>();
IExtendedList<int> logged = new LoggingList<int>(baseList, logger);
logged.Add(42); // "Adding 42" logged
β οΈ Threading / Performance / Safety Notes
Thread Safety
- Most collections are NOT thread-safe by default. Use
SynchronizedList<T>,SynchronizedDictionary<TKey, TValue>,SynchronizedExtendedList<T>, or wrap withConcurrentStreamwhere concurrent access is required. - Transactional scopes require serialized use. Nested scopes can share transaction ownership through the logical call context; creating another scope instance does not by itself guarantee an independent transaction. Follow the concrete backend's isolation and concurrency contract.
- Caches:
CacheBase<TKey, TValue>synchronizes access and returns a membership snapshot. Multi-step pinning and borrowed-value lifetime still require the caller's scope/lifetime discipline; see the cache guide.SynchronizedRepository<T>andSynchronizedLoggerprovide their respective synchronized wrappers. - ProducerConsumerQueue<T>: Fully thread-safe for concurrent producers and consumers.
Performance Considerations
- Range Operations: Prefer
ReadRange,UpdateRange, andInsertRangeover element-by-element operations for large datasets. - Removed References:
ExtendedList<T>releases references in vacated slots after removal or clearing, including references inside structs. It retains its backing capacity for reuse; clearing is not a shrink operation. - Stream Materialization: The
Stream.ToArray()extension uses the standard bounded transfer buffer. The returned array still needs space for the complete stream, but scratch capacity does not scale with its length. Seekable source position is restored. - Extended Lists:
ExtendedList<T>provides span append, update, insertion and destination-read overloads. Scalar operations, enumeration andCopyTofollow the range-first base and its virtual range methods. Array/List bulk inputs and overlapping spans remain supported. - Buffer Reads:
IBuffer.ReadRange(index, destinationSpan)writes into caller-owned storage. Memory, paged, file and stream buffers provide direct-copy paths; paged reads preserve notifications and keep each page open until its bytes are copied. The default interface and generic adapter paths useReadSpanand may allocate a snapshot. Paged and stream-mapped subclasses can override the virtual destination overload to customize those reads. - Buffer Streams:
ExtendedMemoryStreamandFragmentedStreamdelegate array and byte reads/writes to their virtual span overloads.BoundedStream,ConcurrentStreamandNonClosingStreamalso delegate array operations to span overloads.ToArray()follows the source buffer's normal materialization/copying contract. Length growth initializes new bytes to zero without allocating a temporary array proportional to the added length. - Fragment and Item Reads:
IStreamFragmentProvider.ReadFragment(fragmentID, fragmentPosition, destinationSpan)andStreamPagedList<T>.ReadItemBytes(itemIndex, byteOffset, destinationSpan)copy into caller-owned storage and return the number of bytes read. Fragment providers can implementGetFragmentLengthto avoid reading content just to determine its size; existing providers retain default implementations. Clustered streams use these paths without allocating fragment payload arrays, and item reads retain page notifications and scopes. - Dynamic Page Raw Bytes: Raw item reads and writes translate global item indexes to the selected page's local offsets, including items beyond the first page.
See span and buffer allocation measurements, the subsequent inheritance review, the current complexity review, and stream-mapped dictionary hot-path profiling for workloads, extension points and validation details.
- Paging Configuration: Tune page sizes and in-memory page counts for memory-paged and file-paged collections based on access patterns.
- Serialization: Constant-size serializers enable efficient random access. Variable-size serializers require sequential scans.
- Merkle Trees: Flat merkle trees optimize for proof generation but consume O(n log n) memory. Long merkle trees trade memory for computation.
- ClusteredStreams: Default cluster size is 4KB; adjust based on typical object sizes and access patterns.
Safety Constraints
- Stream Position Management: Many components assume exclusive control over stream position. Concurrent stream access without synchronization is unsafe.
- Serialization Context: Contexts are NOT thread-safe. Use separate contexts per thread or synchronize access.
- Disposal: Disposable resources (streams, transactions, scopes) must be disposed to release locks and persist changes. Use
usingstatements.
β Status & Maturity
Sphere10 Framework is a mature library that has evolved over multiple years. Core subsystems (collections, serialization, transactions, merkle trees) are stable and production-tested. Some components (post-quantum cryptography, protocol orchestration) may be less battle-tested and should be evaluated carefully for production use.
Compatibility
- Target Frameworks:
net8.0,net9.0andnet10.0, plusnet11.0when a .NET 11 SDK builds the library. Only thenet11.0build compiles with runtime async. - Backward Compatibility: The library does not guarantee API stability across major versions. Serialization formats may evolve, requiring migration strategies for persistent data.
- Platform Support: Windows, Linux, macOS, iOS (via Xamarin/MAUI), Android (via Xamarin/MAUI)
π§ͺ Experimental Components
- Post-quantum signature schemes (W-OTS, AMS) are reference implementations. Audit and validate before use in production cryptographic systems.
- Some advanced merkle-tree variants and indexing strategies are optimized for specific use cases and may have edge-case limitations.
π¦ Platform-Specific Packages
Sphere10.Framework.Windows- Windows-specific utilitiesSphere10.Framework.Windows.Forms- WinForms integrationSphere10.Framework.Windows.LevelDB- Native LevelDB wrapperSphere10.Framework.Application- Cross-platform application frameworkSphere10.Framework.Communications- Networking and protocol layersSphere10.Framework.Web.AspNetCore- ASP.NET Core integrationSphere10.Framework.CryptoEx- Extended cryptography (ECDSA, ECIES, etc.)
Dependencies
- .NET 8.0 or higher
- No package dependencies, and only the allowlisted .NET assemblies described in Allowed .NET assemblies
- Separate packages: BouncyCastle-based cryptography is in
Sphere10.Framework.CryptoEx, Newtonsoft.Json support inSphere10.Framework.DataandSphere10.Framework.Communications, and Microsoft.Extensions.DependencyInjection integration inSphere10.Framework.Application
βοΈ License
Distributed under the MIT License.
Sphere10 Framework is distributed under the MIT License.
More information: MIT License
π Resources
- GitHub: Herman Schoenfeld
- Website: sphere10.com
π€ Author
Herman Schoenfeld - Software Engineer
Device hook cleanup
BaseDeviceHook.Dispose() retains its public virtual signature and now delegates to Dispose(true) before suppressing finalization. The finalizer calls the protected virtual Dispose(false) cleanup hook directly, so public disposal overrides and their managed event callbacks are not invoked by finalization. Derived hooks that require cleanup during finalization should override Dispose(bool disposing), restrict managed-resource work to disposing == true, and call the base implementation. Base hook cleanup is idempotent.
Default encryption compatibility
Default text/file compression and the non-generic Tools.Streams.Encrypt / Decrypt overloads use Aes.Create(). The generic algorithm overloads remain available. AES key/block sizes, CBC/PKCS7 defaults, existing password derivation and the IV-prefixed encrypted format are retained; historical compressed data remains readable. SystemCRNG uses the platform cryptographic random-number factory.
SMTP TLS behaviour of Tools.Mail and the status of the UrlShortner providers are described with those tools in Sphere10.Framework.Communications.
Length-preserving encrypted streams
EncryptedStream (and EncryptedStream<TStream>) uses AES-CTR. It takes the backing stream, key, initial counter and optional leaveOpen flag (default false). Writes encrypt immediately and reads decrypt; 10 plaintext bytes produce exactly 10 ciphertext bytes. The mode is fixed to preserve arbitrary byte lengths and independent random access, including overwrites that touch only the requested bytes. There is no separate cipher interface, factory or inheritance hierarchy.
var key = Tools.Crypto.GenerateCryptographicallyRandomBytes(32);
var initialCounter = Tools.Crypto.GenerateCryptographicallyRandomBytes(16);
using var storage = new MemoryStream();
using var encryptedStream = new EncryptedStream(storage, key, initialCounter, leaveOpen: true);
encryptedStream.Write(new byte[10]);
// storage.Length == 10
encryptedStream.Position = 3;
var plaintext = new byte[7];
encryptedStream.ReadExactly(plaintext);
Use a 32-byte key for AES-256; AES-128 and AES-192 keys (16 and 24 bytes) are also accepted. The initial counter is always 16 bytes. Both arrays are copied. The stream owns its internal AES instance; leaveOpen: true keeps the backing stream open after disposal; the default closes it. Counter blocks increment as big-endian integers, following NIST SP 800-38A section 6.5; AES vectors from appendix F.5 are covered by the tests.
.NET's CipherMode enum has no CTR member. The small counter-mode loop therefore lives directly inside EncryptedStream and uses .NET AES to encrypt counter blocks without padding. It does not expose ECB as though it were the stream mode.
Keep the key secret and store the initial counter separately. Never reuse the same key/counter blocks for different plaintext, including revisions of overwritten data. CTR supplies confidentiality; authenticate ciphertext separately before decrypting untrusted input. Encrypted<T> below supplies that authentication for stored objects.
The stream supports array/span, async array/memory, byte-at-a-time, copy and legacy Begin/End operations. Seekable streams use absolute positions from the underlying stream's origin; reads and writes can start within a cipher block. Non-seekable streams process bytes sequentially from their position at wrapping. Resize and writes that create gaps are rejected, since underlying zero-filled gaps are not encrypted zeroes. Callers must serialize access to an instance and discard it after an underlying I/O failure. Closing/disposal adds no bytes.
Encrypted objects
Encrypted.For(item, secret) and new Encrypted<T>(item, secret) use the framework's BinarySerializer directly through EncryptedStream, including its type information, reference handling and null support. Callers no longer supply an item serializer.
var secret = Encoding.UTF8.GetBytes("application secret");
var encrypted = Encrypted.For("example", secret);
if (encrypted.TryDecrypt(secret, out var value)) {
// value == "example"
}
EncryptedBytes.Length equals the BinarySerializer output length, including serialization metadata. Salt, initial counter and a SHA-256 HMAC tag are held separately on the object, keeping ciphertext length unchanged. The object retains these values for TryDecrypt; EncryptedBytes alone is not a self-contained persistence format. The metadata accessors return defensive copies. Each SetItem generates fresh salt and counter values. PBKDF2-HMAC-SHA256 derives independent AES-256 and authentication keys; the configurable iteration count defaults to 600,000. HMAC covers the version domain, iteration count, salt, counter and ciphertext and is checked in constant time before deserialization. Wrong secrets or modified ciphertext return false; string secrets use UTF-8.
The new binary-secret PBKDF2.DeriveKey overload requires an explicit hash algorithm. The existing string overload keeps its legacy SHA-1 behavior for compatibility.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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. net11.0 is compatible. |
-
net10.0
- No dependencies.
-
net11.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (21)
Showing the top 5 NuGet packages that depend on Sphere10.Framework:
| Package | Downloads |
|---|---|
|
Sphere10.Framework.Data
Universal data access abstraction layer providing ADO.NET enhancements, schema management, connection/transaction scoping, and database-agnostic persistence. Includes DAC helpers, SQL execution and query building, CSV support, and common extensions used by provider packages (SQLite, SQL Server, Firebird, MySQL, PostgreSQL, Oracle, NHibernate). |
|
|
Sphere10.Framework.Application
Application framework and lifecycle management for Sphere10 Framework-based apps. Provides dependency injection integration, settings persistence, command-line argument parsing, product/version metadata, and builder-based startup/shutdown hooks. |
|
|
Sphere10.Framework.Drawing
Drawing utilities with cross-platform color and geometry helpers, plus Windows image processing and GDI+ rendering. Includes gradients, geometric utilities, and common visual effects. |
|
|
Sphere10.Framework.Windows
Windows platform integration layer providing secure, type-safe access to Windows-specific APIs and system integration features. Includes abstractions for NT security objects (users/groups/SIDs), services, event logging, registry access, privileges, and related Windows utilities. |
|
|
Sphere10.Framework.Windows.Forms
Windows Forms UI framework and component library for building desktop applications with Sphere10 Framework. Provides reusable WinForms controls, dialogs, layout/helpers, and common UI utilities intended to integrate cleanly with the framework's application and data layers. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.2.0 | 0 | 11/24/2026 |
| 3.2.0-ci.173.45375449609.1 | 0 | 11/24/2026 |
| 3.2.0-ci.171.45374063975.1 | 0 | 11/24/2026 |
| 3.2.0-ci.169.45350717665.1 | 0 | 11/24/2026 |
| 3.2.0-ci.168.45166918016.1 | 81 | 11/23/2026 |
| 3.2.0-ci.163.43664782937.1 | 221 | 11/15/2026 |
| 3.2.0-ci.160.43660265392.1 | 221 | 11/15/2026 |
| 3.2.0-ci.159.43537748063.1 | 211 | 11/14/2026 |
| 3.2.0-ci.158.43536665157.1 | 199 | 11/14/2026 |
| 3.2.0-ci.157.43350632870.1 | 206 | 11/13/2026 |
| 3.2.0-ci.156.43233095581.1 | 210 | 11/12/2026 |
| 3.1.2 | 442 | 9/9/2026 |
| 3.1.1 | 317 | 9/8/2026 |
| 3.1.0 | 290 | 9/7/2026 |
| 3.0.3 | 496 | 1/6/2026 |
| 3.0.2 | 367 | 1/2/2026 |
| 3.0.1 | 366 | 1/2/2026 |
| 3.0.0 | 373 | 1/2/2026 |
| 2.0.2 | 1,985 | 4/23/2019 |
| 2.0.1 | 856 | 3/1/2019 |
Initial public release