DotNetDupe 5.0.4

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

DotNetDupe ๐Ÿš€

Build Status CodeQL Security Coverage API Docs NuGet Version Language Platforms License

Ever admired the elegance and developer-friendliness of .NET APIs? ๐Ÿค” While the C++ Standard Template Library (STL) is powerful, its learning curve can be steep. This project, DotNetDupe, bridges that gap! ๐ŸŒ‰

Inspired by the clear and concise API design of C# .NET, DotNetDupe is a C++ library that brings a familiar, streamlined development experience to your C++ projects. โœจ

Latest Published Version (NuGet Version): Comprehensive documentation, API reference updates, Pimpl ABI stability, and refined packaging! ๐ŸŒ Key highlights include:

  • ๐Ÿ’พ Drive Metrics & Free Space Telemetry (System::IO::DriveInfo): Full drive metrics, file system format, volume label, total size, and available/free space queries via DriveInfo::GetDrives(), GetTotalSize(), GetTotalFreeSpace(), and GetAvailableFreeSpace().
  • ๐Ÿ“‚ Recursive Directory Searching (System::IO::Directory & SearchOption): Added SearchOption::TopDirectoryOnly and SearchOption::AllDirectories overloads to Directory::GetFiles, GetDirectories, and GetFileSystemEntries with permission-resilient traversal.
  • ๐Ÿ“Š 64-bit Multi-Terabyte Stream Precision (System::IO::Stream & FileStream): Seamless support for multi-gigabyte/terabyte files via GetLength64(), GetPosition64(), SetPosition64(), and Seek64().
  • ๐Ÿ” Streaming Cryptographic SHA-256 (System::Security::Cryptography::SHA256): FIPS 180-2 compliant streaming SHA-256 hash algorithm supporting byte buffers, streams (ComputeHash(SmartPointer<Stream>)), static one-shot hashing (HashData), and hex string formatting (ToHexString).
  • ๐Ÿงฉ Batch Task Synchronization (System::Threading::Tasks::Task::WaitAll): Parallel task completion barrier enabling multi-threaded worker pools to synchronize cleanly.
  • ๐Ÿงฎ Mathematical Primitives & Time-Series Statistics (System::Math & System::Numerics::Statistics): Full suite of IEEE 754 arithmetic and transcendental methods (Abs, Min, Max, Clamp, Round, Sqrt, Pow, Log, Sin, Cos, Tan) and time-series statistics (Mean, Variance, StandardDeviation, MovingAverage, MovingAverageSeries, ExponentialMovingAverage, ExponentialMovingAverageSeries).
  • ๐Ÿ”ฃ Generic JSON Serialization & DOM Accessors (System::Text::Json): Strongly-typed generic serialization and deserialization via compile-time SFINAE DTO mapping (ToJson/FromJson), expanded primitive/container converters (Array<T>, DateTime, Guid), and JsonElement property helpers (HasProperty, GetProperty, GetPropertyString, GetPropertyInt32, GetPropertyDouble, GetPropertyAs<T>, Deserialize<T>).
  • ๐Ÿง Linux Native NuGet Runtime Support (libDotNetDupe.so): Native Linux x64 shared library bundled under runtimes/linux-x64/native/libDotNetDupe.so with automated MSBuild .targets and CMake integration.
  • โšก Concurrent Collections & Producer-Consumer Hierarchy (System::Collections::Concurrent): Full interface hierarchy retrofit across ConcurrentQueue<T>, ConcurrentStack<T>, ConcurrentBag<T>, BlockingCollection<T>, and ConcurrentDictionary<TKey, TValue> inheriting generic collection base interfaces (IReadOnlyCollection<T>, IEnumerable<T>, IDictionary<TKey, TValue>) and introducing IProducerConsumerCollection<T> with lock-free snapshot enumeration and direct LINQ method chaining.
  • ๐Ÿง  Dedicated Smart Pointers & Collections Documentation: Comprehensive architectural guides, comparison tables, and compile-ready code snippets showcasing unique/shared ownership, polymorphic abstractions, fast dictionaries/hash sets, bounded blocking pipelines, and snapshot iteration.
  • โšก First-Class C# EventHandler<TEventArgs> & EventArgs Model: Idiomatic C# .NET event-driven delegate system with multicast subscription (+=, -=), member method binding (Add(pInstance, &Class::Method)), token-based unsubscription, and thread-safe dispatch.
  • ๐Ÿ“ฅ Modernized FileDownloader: Upgraded download callbacks to typed multicast EventHandler<DownloadProgressChangedEventArgs> and EventHandler<DownloadCompletedEventArgs> with reliable FileMode creation and resumption.
  • ๐Ÿ”„ Observable ProcessStreamer Modernization: Multicast event streams (ProcessDiscovered, BatchReady, ProcessUpdated, Completed, Error) with two-tier progressive telemetry streaming and thread-safe cancellation.
  • โฑ๏ธ First-Class Process Discovery (Process::GetProcesses): Native ultra-fast (< 5ms) discovery snapshots via Process::GetProcesses(), Process::GetProcessById(), and Process::GetProcessesByName() matching .NET BCL, with on-demand per-process deep enrichment via SystemMetrics::EnrichProcessInfo().
  • ๐Ÿ”ข Version String Parsing (Version::Parse & Version::TryParse): Strict, .NET-compliant string parsing supporting 2, 3, and 4-component version formats with full error validation.
  • ๐Ÿ›ก๏ธ Zero Header STL Dependencies: Completely refactored public headers to eliminate STL dependencies from public interfaces, ensuring clean ABI boundaries and library-centric types across String, Collections, IO, Net, Logging, and Data.
  • ๐Ÿ“ฆ Core Data Structures & Collections Overhaul: Pure library implementations for List<T>, Dictionary<K, V>, HashSet<T>, Queue<T>, Stack<T>, PriorityQueue<T>, SortedDictionary<K, V>, SortedSet<T>, and LinkedList<T>.
  • โšก Thread-Safe Concurrent Collections (System::Collections::Concurrent): Lock-free/fine-grained thread-safe data structures including ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, ConcurrentBag, and BlockingCollection.
  • ๐Ÿ” Language Integrated Query (System::Linq): Expressive, declarative query pipeline (Where, Select, SelectMany, OrderBy, OrderByDescending, ThenBy, GroupBy, Distinct, Take, Skip, Zip, Reverse) with numeric aggregations (Sum, Average, Min, Max, Aggregate), quantifiers (Any, All, Contains), sequence generators (Range, Repeat), and seamless materialization (ToList, ToArray, ToDictionary, ToHashSet) with direct collection interface support.
  • ๐Ÿ“Š Real-Time Telemetry & System Metrics (System::Diagnostics::SystemMetrics): Real-time monitoring of system hardware metrics (CPU load %, memory usage, disk throughput, network bandwidth, and active processes).
  • ๐Ÿ“œ ETW & Enterprise Event Logging (System::Diagnostics::EtwLogReader & EventLog): High-performance Event Tracing for Windows (ETW) and Linux Syslog channel enumeration, querying, and live subscription listening.
  • ๐Ÿ–ฅ๏ธ Terminal & User Sessions (System::Diagnostics::TerminalSession & ActiveUserSession): Enumerate local, disconnected, and remote desktop (RDP) Terminal Services user sessions.
  • ๐Ÿ“„ Console I/O Redirection: Standard stream redirection via Console::SetOut, Console::SetError, and Console::SetIn using SmartPointer.
  • ๐Ÿ–Š๏ธ LoggerTextWriter Log Redirector: Bridge standard TextWriter stream calls directly into LogManager logging providers without per-call lookup overhead.
  • ๐Ÿท๏ธ Global LogManager: Thread-safe category logger caching and static factory via LogManager::GetLogger("Category") and LogManager::GetLogger<T>().
  • ๐ŸŒฒ Recursive Directory Creation: Overloaded Directory::CreateDirectory(path, recursive) to automatically construct missing parent directory structures.
  • ๐Ÿ“‚ Resilient File Logging: Enhanced FileLoggerProvider to resolve relative log paths to full paths and auto-create missing log directories.
  • ๐Ÿงฉ ServiceCollection DI Enhancements: Improved lifetime management and container registration.

This project is a living example of how persistent human effort during weekends and late evenings can build a system from scratch using AI. DotNetDupe has grown far beyond a foundational set of classes into a comprehensive, multi-platform C++ Base Class Library offering extensive modern capabilities across System, IO, Collections, Net, Threading, Logging, Data, and Hosting. If anyone wants to join hands, you are most welcome in the form of PRs, issues or comments ๐Ÿ™

A fun fact: While I personally crafted core components like Char, String, and Path (along with their tests), the rest of the system was collaboratively designed, built, and expanded by myself and my peer Antigravity. ๐Ÿค– This project serves as a unique playground for exploring how generative AI can accelerate development from scratch. ๐Ÿš€

DotNetDupe aims to simplify C++ development by providing C#-like interfaces for common tasks, making your code more concise, intuitive, and a joy to write. ๐Ÿ’–

Table of Contents ๐Ÿ“š

Project Overview ๐Ÿ’ก

The core objective of DotNetDupe is to bridge the gap between the power and performance of C++ and the ease of use and productivity offered by C# APIs. By providing C#-like interfaces for common programming tasks, DotNetDupe aims to:

  • Simplify C++ Development: Reduce the boilerplate and complexity often associated with STL, making C++ more approachable for developers accustomed to higher-level languages.
  • Enhance Readability: Promote cleaner and more readable code by adopting well-known C# API patterns.
  • Boost Productivity: Accelerate development cycles by offering intuitive and efficient tools for common operations.

Features & Library Capabilities โœจ

DotNetDupe has evolved into a feature-rich, multi-platform C++20 Base Class Library (BCL) offering an extensive suite of modern capabilities:

  • ๐Ÿง  Memory & Object Management (System):

    • SmartPointer<T>: Exception-safe RAII reference-counted smart pointer with NewShared() and NewUnique() factory helpers.
    • Base Object type system with ToString(), GetType(), Equals(), and GetHashCode().
  • โšก Delegates & Event Model (System):

    • EventHandler<TEventArgs>: Multicast event delegate supporting lambda, free function, and member method binding with operator+=, token unsubscription with operator-=, and FIFO invocation.
    • EventArgs: Base class for event data payloads with EventArgs::Empty() singleton.
  • ๐Ÿ”ค String Manipulation & Utilities (System::String):

    • Full-featured String & WString with UTF-8 / UTF-16 cross-transcoding.
    • Methods: Format(), Split(), Join(), Replace(), Contains(), StartsWith(), EndsWith(), Trim(), PadLeft(), PadRight().
  • ๐Ÿ“ฆ Generic Collections (System::Collections::Generic):

    • Type-safe container wrappers: List<T>, Dictionary<K, V>, Queue<T>, Stack<T>, HashSet<T>, and KeyValuePair<K, V>.
  • โšก Language Integrated Query (System::Linq):

    • Declarative fluent query pipeline: Where, Select, SelectMany, OrderBy, OrderByDescending, ThenBy, ThenByDescending, GroupBy, Distinct, Take, Skip, Zip, Reverse.
    • Numeric aggregations & quantifiers: Count, Sum, Min, Max, Average, Aggregate, Any, All, Contains.
    • Sequence generators & materialization: Range(), Repeat(), Empty(), ToList(), ToArray(), ToDictionary(), and ToHashSet().
  • ๐Ÿ“ File I/O & System Services (System::IO):

    • High-level static primitives: File (ReadAllText, WriteAllText, AppendAllText, Exists, Delete) and Directory (CreateDirectory(path, recursive), Exists, EnumerateFiles).
    • Cross-platform path calculations: Path (Combine, GetFullPath, GetDirectoryName, GetFileName, GetExtension).
    • Stream & Reader/Writer hierarchy: FileStream, MemoryStream, BufferedStream, StreamReader, StreamWriter, BinaryReader, BinaryWriter, StringReader, StringWriter.
  • ๐Ÿ“Ÿ Console & Stream Redirection (System::Console):

    • Rich console text & background color controls (SetForegroundColor, SetBackgroundColor, ResetColor).
    • Full stream redirection via SetOut(), SetError(), and SetIn() accepting SmartPointer<TextWriter> and SmartPointer<TextReader>.
  • ๐ŸŒฒ Enterprise Logging & Diagnostics (Extensions::Logging):

    • Structured & Plaintext logging (ILogger, ILoggerProvider, LoggerFactory).
    • Formats: Custom plaintext layout templates & JSON structured payloads with key-value metadata properties.
    • Providers: ConsoleLoggerProvider and FileLoggerProvider with automatic relative path resolution & recursive parent directory creation.
    • LogManager: Category logger caching factory (GetLogger("Category"), GetLogger<T>(), GetConsoleLogger, GetFileLogger).
    • LoggerTextWriter: High-performance stream redirector bridging TextWriter output into LogManager.
  • ๐Ÿงต Multi-Threading & Process Management (System::Threading / System::Diagnostics):

    • Thread lifecycle (Thread), high-throughput ThreadPool, and task parallelism (Task, Task<T>).
    • Synchronization primitives: Mutex, AutoResetEvent, ManualResetEvent, EventWaitHandle, CriticalSection, ReaderWriterLockSlim.
    • Process orchestration & telemetry: Process, ProcessStartInfo, and progressive streaming via ProcessStreamer / ProcessStreamOptions.
  • ๐ŸŒ Networking, HTTP & Web App Hosting (System::Net / Extensions::Hosting):

    • Low-level socket abstractions (TcpClient, TcpListener, UdpClient, Socket).
    • Full-duplex WebSockets: WebSocket, WebSocketState, WebSocketException, WebSocketError (RFC 6455).
    • High-level HTTP client: HttpClient, HttpRequestMessage, HttpResponseMessage, HttpContent, StringContent, ByteArrayContent.
    • SSL/TLS security: SslStream backed by OpenSSL.
    • Embedded Web Server & Hosting: WebAppServer and HostBuilder for serving static Web UI files and REST API controllers.
  • ๐Ÿ’‰ Dependency Injection (Extensions::DependencyInjection):

    • Full-featured DI container (ServiceCollection, ServiceProvider, ServiceDescriptor).
    • Lifetimes: Transient, Scoped, Singleton.
  • ๐Ÿ” Security & Principal (System::Security::Principal):

    • UserPrincipal and WindowsIdentity for cross-platform OS user enumeration and privilege inspection.
  • โšก Database Data Access (System::Data):

    • Abstract ADO.NET-style data provider interfaces (IDbConnection, IDbCommand, IDataReader, IDataParameterCollection).

Getting Started ๐Ÿš€

Prerequisites ๐Ÿ“‹

  • C++17 / C++20 compatible compiler (e.g., MSVC v143, GCC 11+, Clang 13+)
  • CMake 3.15+ (for building on Linux / WSL)
  • OpenSSL / SSL Runtime Dependencies:
    • Windows: The NuGet package bundles pre-built OpenSSL runtime binaries (libssl-4-x64.dll, libcrypto-4-x64.dll for x64, and libssl-4.dll, libcrypto-4.dll for x86) which are automatically copied into the target build output directory via MSBuild .targets.
    • Linux: The NuGet package bundles pre-built OpenSSL 4.0.1 runtime libraries (libssl.so.4, libcrypto.so.4, and symlinks libssl.so, libcrypto.so) under runtimes/linux-x64/native/ which are automatically copied to output directories via MSBuild .targets. Pre-compiled libraries and headers are also provided in external/openssl-4.0.1/linux-x64/.

Installation โฌ‡๏ธ

  1. Clone the repository:

    git clone https://github.com/sudheeshps/DotNetDupe.git
    cd DotNetDupe
    
  2. Build the solution and generate NuGet package: Run the automated build script from PowerShell:

    .\BuildAndPack.ps1
    

    This script will update the resource build timestamp, compile the x64 and x86 Release binaries, and output the NuGet package (DotNetDupe.5.0.4.nupkg) into the nuget_packages directory.

  3. Add local NuGet package source: To use the locally generated NuGet package, add the nuget_packages directory as a local NuGet source:

    nuget sources Add -Name "DotNetDupeLocal" -Source "D:\Personal\Projects\C++\DotNetDupe\nuget_packages"
    

    (Replace D:\Personal\Projects\C++\DotNetDupe with your actual solution root path.)

  4. Install the NuGet package in your project: In your C++ project, you can now install the DotNetDupe package using the NuGet Package Manager or the command line:

    nuget install DotNetDupe -OutputDirectory <YourProjectDirectory> -Source DotNetDupeLocal
    

    (Replace <YourProjectDirectory> with the path to your project where you want to install the package.)

  5. Integrate into your project: Once installed, ensure your project's .vcxproj file is configured to link against the DotNetDupe.lib and include its headers. The NuGet package's .targets file should handle most of this automatically.

Cross-Platform Support ๐ŸŒ

DotNetDupe is designed for high portability and officially supports Windows (via MSVC/MSBuild) and Linux (via GCC/Clang/CMake).

Building and Testing

Platform Build System Build Command Test Command
Windows MSBuild msbuild DotNetDupe.sln /p:Configuration=Release .\bin\x64\Release\DotNetDupeTests.exe
Linux / WSL CMake cmake -S . -B build && cmake --build build cd build && ctest

Integration via NuGet

DotNetDupe is distributed as a multi-platform NuGet package. It contains native binaries for:

  • win-x64 (DotNetDupe.dll, libssl-4-x64.dll, libcrypto-4-x64.dll)
  • win-x86 (DotNetDupe.dll, libssl-4.dll, libcrypto-4.dll)
  • linux-x64 (libDotNetDupe.so, libssl.so.4, libcrypto.so.4)

When you add the NuGet package to your project, the appropriate binary and dependencies are automatically selected based on your target platform.

SSL Runtime Dependencies
  • Windows: Dynamic OpenSSL dependencies (libssl-4-x64.dll & libcrypto-4-x64.dll) are packaged directly inside the NuGet package and deployed next to DotNetDupe.dll at build time.
  • Linux: Dynamic OpenSSL 4.0.1 dependencies (libssl.so.4 & libcrypto.so.4) are packaged directly inside the NuGet package and deployed alongside libDotNetDupe.so at build time via MSBuild .targets.
Note for Linux Users

On Linux, NuGet packages are typically managed via dotnet CLI or integrated into CMake projects using tools like vcpkg or by manually extracting the shared library (.so) and headers from the .nupkg (which is a ZIP file).

Example manual extraction:

unzip DotNetDupe.nupkg -d dotnetdupe_lib
# Use dotnetdupe_lib/include for headers
# Use dotnetdupe_lib/runtimes/linux-x64/native/libDotNetDupe.so for linking

WSL Setup Guide (Windows) ๐Ÿง

For Windows developers who want to build and test for Linux locally, we recommend using the Windows Subsystem for Linux (WSL).

1. Install WSL

If you haven't already, install Ubuntu via PowerShell:

wsl --install -d Ubuntu

2. Environment Provisioning

Inside your WSL terminal, install the C++ build chain and OpenSSL development headers:

sudo apt-get update
sudo apt-get install -y build-essential cmake libssl-dev pkg-config

3. Build & Test in WSL

Navigate to your project root (e.g., /mnt/d/Projects/DotNetDupe) and run:

# Create build directory
mkdir -p build-wsl && cd build-wsl

# Configure and Build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build .

# Run Tests
ctest --output-on-failure

4. Running WSL Commands from PowerShell

You can also build and test for Linux directly from a Windows PowerShell terminal without manually entering the WSL shell:

# Create build directory
wsl -d Ubuntu -- bash -c "mkdir -p build-wsl"

# Configure
wsl -d Ubuntu -- bash -c "cd build-wsl && cmake .. -DCMAKE_BUILD_TYPE=Release"

# Build
wsl -d Ubuntu -- bash -c "cd build-wsl && cmake --build ."

# Run Tests (via CTest)
wsl -d Ubuntu -- bash -c "cd build-wsl && ctest"

# Run Tests (direct execution)
wsl -d Ubuntu -- bash -c "cd build-wsl && ./DotNetDupeTests"

# Run Demo Application
wsl -d Ubuntu -- bash -c "cd build-wsl && ./DotNetDupeDemo"

Developing Cross-Platform Applications ๐ŸŒ๐Ÿ’ป

DotNetDupe enables unified, cross-platform C++20 development across Windows (MSVC / MSBuild) and Linux (GCC/Clang via CMake or WSL).


1. Cross-Platform Project Architecture

When building a cross-platform application with DotNetDupe:

  • Use UTF-8 character encoding for cross-platform portability.
  • Rely on DotNetDupe::System::SmartPointer<T> for memory and resource cleanup.
  • Avoid platform-specific raw syscalls; use DotNetDupe abstractions like System::IO::Path, System::IO::File, System::Threading::Thread, and System::Net::Sockets::TcpClient.

2. Integrating via NuGet Package

You can package and consume DotNetDupe via NuGet across Windows and Linux (WSL / CMake) projects.

A. Generating the NuGet Package

Run the automated build script from PowerShell:

.\BuildAndPack.ps1

This updates the build timestamp, compiles both x64 and x86 Release binaries, and outputs DotNetDupe.5.0.2.nupkg inside the nuget_packages/ directory.

B. Consuming NuGet Package in Visual Studio (Windows)
  1. Add the local nuget_packages folder as a NuGet Package Source:
    nuget sources Add -Name "DotNetDupeLocal" -Source "D:\Personal\Projects\C++\DotNetDupe\nuget_packages"
    
  2. In Visual Studio, right-click your project โ†’ Manage NuGet Packages โ†’ Select DotNetDupeLocal โ†’ Install DotNetDupe.
C. Consuming NuGet Package on Linux / CMake (WSL)
  1. Extract DotNetDupe.5.0.2.nupkg (ZIP format) to a local directory:
    Expand-Archive -Path "nuget_packages\DotNetDupe.5.0.2.nupkg" -DestinationPath "DotNetDupe_NuGet" -Force
    
  2. Configure CMake pointing NUGET_PATH to the extracted package folder:
    cmake -S . -B build -DUSE_NUGET=ON -DNUGET_PATH="./DotNetDupe_NuGet"
    cmake --build build
    

3. Building a Web Application with Static Files & REST APIs

The WebAppServer class serves static website assets (index.html, CSS, JavaScript, images) alongside mapped REST endpoints.

Project Directory Layout
MyWebApp/
โ”œโ”€โ”€ wwwroot/
โ”‚   โ”œโ”€โ”€ index.html
โ”‚   โ””โ”€โ”€ site.css
โ””โ”€โ”€ main.cpp
Step 1: Create wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DotNetDupe Web App</title>
    <link rel="stylesheet" href="site.css">
</head>
<body>
    <h1>DotNetDupe Web Application Server</h1>
    <p>Serving static assets and REST API endpoints simultaneously!</p>
    <button onclick="fetchWelcomeMessage()">Hit Welcome Endpoint</button>
    <p id="welcome-output"></p>

    <script>
        async function fetchWelcomeMessage() {
            const response = await fetch('/api/welcome?name=Developer');
            const data = await response.json();
            document.getElementById('welcome-output').innerText = data.message;
        }
    </script>
</body>
</html>
Step 2: C++ Application (main.cpp)

Here is a complete, compile-ready web application hosting index.html and responding with a welcome message on hitting /api/welcome:

#include "System/Console.h"
#include "System/SmartPointer.h"
#include "System/IO/File.h"
#include "System/IO/Path.h"
#include "System/IO/Directory.h"
#include "WebAppCore/Builder/WebApplication.h"
#include "WebAppCore/Builder/WebApplicationBuilder.h"
#include "WebAppCore/Server/WebAppServer.h"
#include "WebAppCore/Http/HttpContext.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::WebAppCore::Builder;
using namespace DotNetDupe::WebAppCore::Server;
using namespace DotNetDupe::WebAppCore::Http;

int main() {
    Console::WriteLine("=============================================");
    Console::WriteLine(" Starting DotNetDupe Cross-Platform Web Server");
    Console::WriteLine("=============================================");

    String webRoot = "wwwroot";
    if (!IO::Directory::Exists(webRoot)) {
        IO::Directory::CreateDirectory(webRoot, true);
    }

    // 1. Initialize WebApplication Host Builder
    auto builder = WebApplication::CreateBuilder();
    auto app = builder->Build();

    // 2. Map REST Endpoint (/api/welcome?name=...)
    app->MapGet("/api/welcome", [](SmartPointer<HttpContext> ctx) -> String {
        String name = "Guest";
        if (ctx->GetRequest()->GetQuery().ContainsKey("name")) {
            name = ctx->GetRequest()->GetQuery()["name"];
        }

        ctx->GetResponse()->SetContentType("application/json");
        return String("{\"status\":\"Success\",\"message\":\"Welcome to DotNetDupe Web Server, ") + name + "!\"}";
    });

    // 3. Initialize WebAppServer to serve website content (index.html & assets)
    WebAppServer server(app, webRoot);
    server.EnableStaticFiles("index.html");

    Console::WriteLine("Server running at: http://localhost:8080/index.html");
    Console::WriteLine("Welcome Endpoint at: http://localhost:8080/api/welcome?name=Developer");

    // 4. Start Server
    server.Run("http://localhost:8080/index.html");

    return 0;
}

Usage ๐Ÿ’ป

Here are some quick examples of how to use DotNetDupe:

1. Strings, Dates & Console

#include "System/Console.h"
#include "System/String.h"
#include "System/DateTime.h"
#include "System/TimeSpan.h"
#include "System/IO/Path.h"

using namespace DotNetDupe::System;

void DemonstrateBasics() {
    // String interpolation / formatting & manipulation
    String sGreeting = "Hello";
    String sName = "Developer";
    String sMessage = String::Format("{0}, {1}! Welcome to DotNetDupe.", sGreeting, sName);
    Console::WriteLine(sMessage);

    // Cross-platform Path manipulation
    String sDocPath = IO::Path::Combine("C:\\Projects", "DotNetDupe", "README.md");
    Console::WriteLine("Combined Path: {0}", sDocPath);
    Console::WriteLine("Extension: {0}", IO::Path::GetExtension(sDocPath));

    // DateTime and TimeSpan operations
    DateTime dtNow = DateTime::Now();
    DateTime dtTomorrow = dtNow.AddDays(1);
    TimeSpan tsDiff = dtTomorrow - dtNow;
    Console::WriteLine("Current Time: {0}", dtNow.ToString());
    Console::WriteLine("Hours until tomorrow: {0}", tsDiff.GetTotalHours());
}

2. Multi-Threading & Asynchronous Tasks

#include "System/Console.h"
#include "System/Threading/Thread.h"
#include "System/Threading/ThreadPool.h"
#include "System/Threading/Tasks/Task.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Threading;
using namespace DotNetDupe::System::Threading::Tasks;

void DemonstrateConcurrency() {
    // Thread lifecycle
    Thread workerThread([]() {
        Console::WriteLine("Worker thread running...");
        Thread::Sleep(100);
    });
    workerThread.Start();
    workerThread.Join();

    // High-throughput ThreadPool queue
    ThreadPool::QueueUserWorkItem([]() {
        Console::WriteLine("ThreadPool work item executed.");
    });

    // Async Task Parallelism
    auto spTask = Task<int>::Run([]() -> int {
        Thread::Sleep(50);
        return 42 * 2;
    });

    spTask->Wait();
    Console::WriteLine("Task result: {0}", spTask->GetResult());
}

3. Thread-Safe Concurrent Collections

#include "System/Console.h"
#include "System/Collections/Concurrent/ConcurrentDictionary.h"
#include "System/Collections/Concurrent/ConcurrentQueue.h"
#include "System/Collections/Concurrent/BlockingCollection.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Concurrent;

void DemonstrateConcurrentCollections() {
    // Thread-safe ConcurrentDictionary
    ConcurrentDictionary<String, int> dict;
    dict.TryAdd("CPU", 95);
    dict.TryAdd("Memory", 60);
    dict.GetOrAdd("Disk", 40);

    int iUsage = 0;
    if (dict.TryGetValue("CPU", iUsage)) {
        Console::WriteLine("CPU Usage: {0}%", iUsage);
    }

    // Thread-safe Producer-Consumer BlockingCollection
    BlockingCollection<String> pipeline(100);
    pipeline.Add("Packet #1");
    pipeline.Add("Packet #2");

    String sItem;
    if (pipeline.TryTake(sItem)) {
        Console::WriteLine("Processed item from pipeline: {0}", sItem);
    }
}

Smart Pointers & Memory Management ๐Ÿง 

DotNetDupe eliminates manual memory leaks and raw pointer ownership bugs through its unified SmartPointer<T> abstraction (System::SmartPointer, Quality Gate 8 & 11). Modeled after modern RAII and C# object references, SmartPointer<T> provides high performance, zero raw ownership, and dual-mode ownership semantics:

  1. Unique Mode (Default): Zero-overhead, move-only RAII ownership equivalent to std::unique_ptr.
  2. Shared Mode: Thread-safe atomic reference-counted ownership equivalent to std::shared_ptr.
  3. Hungarian Naming Standard: Per Quality Gate 11, all SmartPointer variables and parameters strictly adhere to the p / sp / m_p / s_p Hungarian prefix.

Key Capabilities

Feature Description
Zero-Overhead Unique Mode Move-only semantics with zero heap metadata overhead. Prevents accidental copying via compiler enforcement.
Atomic Shared Mode Lock-free, thread-safe reference counting via atomic interlocked increments and decrements.
Factory Methods SmartPointer<T>::NewUnique(args...) and SmartPointer<T>::NewShared(args...) for concise, type-safe allocation.
Polymorphic Upcasting Implicit, type-safe conversion from SmartPointer<Derived> to SmartPointer<Base> or abstract interface types.
Safe Boolean Checks Explicit operator bool() allowing safe null checks (if (spResource) { ... }).
Intrusive EnableSharedFromThis Allows classes inheriting EnableSharedFromThis<T> to generate shared handles to themselves.

1. Unique vs. Shared Ownership

Use NewUnique() when an object is exclusively owned by a single component or function scope. Use NewShared() when an object must be referenced across multiple components or worker threads.

#include "System/Console.h"
#include "System/String.h"
#include "System/SmartPointer.h"
#include <utility>

using namespace DotNetDupe::System;

class DatabaseConnection {
private:
    String m_sHost;

public:
    DatabaseConnection(const String& sHost) : m_sHost(sHost) {
        Console::WriteLine("Connected to database: {0}", m_sHost);
    }

    ~DatabaseConnection() {
        Console::WriteLine("Closed connection: {0}", m_sHost);
    }

    void ExecuteQuery(const String& sSql) const {
        Console::WriteLine("[{0}] Executing: {1}", m_sHost, sSql);
    }
};

void DemonstrateOwnership() {
    // 1. Unique Ownership (Move-only RAII, zero overhead)
    auto pPrimary = SmartPointer<DatabaseConnection>::NewUnique("cluster-primary.local");
    pPrimary->ExecuteQuery("SELECT * FROM users");

    // Move ownership to another pointer (copying a unique pointer throws SystemException)
    auto pTransferred = std::move(pPrimary);
    if (!pPrimary) {
        Console::WriteLine("pPrimary is now null after ownership transfer.");
    }
    pTransferred->ExecuteQuery("UPDATE users SET active = 1");

    // 2. Shared Ownership (Thread-safe atomic reference counting)
    auto spReplica1 = SmartPointer<DatabaseConnection>::NewShared("cluster-replica.local");
    Console::WriteLine("Initial ref count: {0}", spReplica1.GetRefCount()); // 1

    {
        // Copying is permitted in Shared mode and atomically increments the reference count
        auto spReplica2 = spReplica1;
        Console::WriteLine("Ref count in inner scope: {0}", spReplica1.GetRefCount()); // 2
        spReplica2->ExecuteQuery("SELECT COUNT(*) FROM telemetry");
    }

    // Inner scope exited: spReplica2 destructed, reference count decremented back to 1
    Console::WriteLine("Ref count after inner scope: {0}", spReplica1.GetRefCount()); // 1
}

2. Polymorphic Abstractions & Interfaces

SmartPointer seamlessly supports polymorphic base classes and interface contracts. Destructors are called virtually and cleanly without memory leaks.

#include "System/Console.h"
#include "System/String.h"
#include "System/SmartPointer.h"

using namespace DotNetDupe::System;

// Abstract interface contract
class IDataProcessor {
public:
    virtual ~IDataProcessor() = default;
    virtual void ProcessData(const String& sPayload) = 0;
};

// Concrete implementation
class JsonDataProcessor : public IDataProcessor {
public:
    void ProcessData(const String& sPayload) override {
        Console::WriteLine("Processing JSON payload: {0}", sPayload);
    }
};

void DemonstratePolymorphism() {
    // Upcast from concrete implementation to abstract interface
    SmartPointer<IDataProcessor> spProcessor = 
        SmartPointer<JsonDataProcessor>::NewShared();

    spProcessor->ProcessData("{\"status\":\"ok\",\"code\":200}");
}

3. Lifetime Controls & Safety Guarantees

DotNetDupe provides fine-grained methods to inspect, reset, and reassign managed objects safely.

#include "System/Console.h"
#include "System/String.h"
#include "System/SmartPointer.h"

using namespace DotNetDupe::System;

void DemonstrateLifetimeControls() {
    auto spBuffer = SmartPointer<String>::NewShared("Initial Data");

    // Inspection
    Console::WriteLine("Buffer content: {0}", *spBuffer);
    Console::WriteLine("Is Shared: {0}", spBuffer.IsShared() ? "True" : "False");

    // Reset with a new value
    spBuffer.Reset(new String("Updated Content"), true);
    Console::WriteLine("After Reset: {0}", *spBuffer);

    // Explicit disposal
    spBuffer.Reset();
    if (!spBuffer) {
        Console::WriteLine("Buffer safely disposed.");
    }
}

Collections & Data Structures ๐Ÿ“ฆ

DotNetDupe provides an extensive suite of type-safe, developer-friendly collections in DotNetDupe::System::Collections::Generic and DotNetDupe::System::Collections::Concurrent. All collections conform to ECMA-335 standards, implement the standard interface hierarchy (IEnumerable<T>, ICollection<T>, IList<T>, IDictionary<K,V>, ISet<T>), provide native C++ range-based for iteration (begin() / end()), and integrate directly with LINQ without intermediate adapters.

Collection Hierarchy Overview

Collection Namespace Key Interfaces Description
List<T> Generic IList<T>, IReadOnlyList<T>, IEnumerable<T> Fast, dynamically-resizable sequential array list.
Dictionary<K, V> Generic IDictionary<K, V>, IReadOnlyDictionary<K, V> High-performance O(1) hash map indexed by unique keys.
HashSet<T> Generic ISet<T>, IReadOnlyCollection<T>, IEnumerable<T> High-performance O(1) hash set of unique elements.
Queue<T> Generic IReadOnlyCollection<T>, IEnumerable<T> First-in, first-out (FIFO) sequential queue.
Stack<T> Generic IReadOnlyCollection<T>, IEnumerable<T> Last-in, first-out (LIFO) sequential stack.
SortedDictionary<K, V> Generic IDictionary<K, V>, IReadOnlyDictionary<K, V> Key/value collection sorted by key (Red-Black tree).
SortedSet<T> Generic ISet<T>, IReadOnlyCollection<T>, IEnumerable<T> Self-balancing binary search tree maintaining unique elements in sorted order.
LinkedList<T> Generic ICollection<T>, IReadOnlyCollection<T>, IEnumerable<T> Doubly-linked list providing O(1) insertion/removal at both ends.
Array<T> System IList<T>, IReadOnlyList<T>, IEnumerable<T> Fixed-size contiguous array buffer matching .NET System.Array.
ConcurrentDictionary<K, V> Concurrent IDictionary<K, V>, IReadOnlyDictionary<K, V> Thread-safe key/value hash map with fine-grained synchronization.
ConcurrentQueue<T> Concurrent IProducerConsumerCollection<T>, IEnumerable<T> Thread-safe FIFO queue for multi-threaded worker pipelines.
ConcurrentStack<T> Concurrent IProducerConsumerCollection<T>, IEnumerable<T> Thread-safe LIFO stack for lock-free push/pop operations.
ConcurrentBag<T> Concurrent IProducerConsumerCollection<T>, IEnumerable<T> Thread-safe unordered container optimized for producer-consumer workflows.
BlockingCollection<T> Concurrent IReadOnlyCollection<T>, IEnumerable<T> Bounded, blocking coordination collection implementing the Producer-Consumer pattern.

1. Generic Collections & Interface Hierarchy

Every DotNetDupe generic collection implements standard interfaces such as IEnumerable<T>, IReadOnlyCollection<T>, and IList<T>. This allows writing generic routines that operate polymorphically across any collection type.

#include "System/Console.h"
#include "System/String.h"
#include "System/Collections/Generic/List.h"
#include "System/Collections/Generic/Queue.h"
#include "System/Collections/Generic/Stack.h"
#include "System/Collections/Generic/IReadOnlyCollection.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Generic;

// Polymorphic helper accepting any read-only collection interface
template <typename T>
void PrintCollectionSummary(const IReadOnlyCollection<T>& collection, const String& sTitle) {
    Console::WriteLine("--- {0} (Count: {1}) ---", sTitle, collection.GetCount());
    for (const auto& item : collection) {
        Console::WriteLine(" - {0}", item);
    }
}

void DemonstrateGenericCollections() {
    // 1. Dynamic List<T>
    List<String> fruits;
    fruits.Add("Apple");
    fruits.Add("Banana");
    fruits.Add("Cherry");
    fruits.Insert(1, "Blueberry");
    PrintCollectionSummary(fruits, "Fruit Basket");

    // 2. FIFO Queue<T>
    Queue<String> printQueue;
    printQueue.Enqueue("Invoice_101.pdf");
    printQueue.Enqueue("Contract_202.pdf");
    Console::WriteLine("Next print job: {0}", printQueue.Peek());
    Console::WriteLine("Processed job: {0}", printQueue.Dequeue());

    // 3. LIFO Stack<T>
    Stack<String> browserHistory;
    browserHistory.Push("https://github.com");
    browserHistory.Push("https://dotnetdupe.org");
    Console::WriteLine("Current page: {0}", browserHistory.Peek());
    Console::WriteLine("Navigated back from: {0}", browserHistory.Pop());
}

2. Key/Value Dictionaries & Hash Sets

Dictionary<TKey, TValue> and HashSet<T> provide average O(1) amortized lookup, insertion, and deletion using internal hash tables and collision chaining.

#include "System/Console.h"
#include "System/String.h"
#include "System/Collections/Generic/Dictionary.h"
#include "System/Collections/Generic/HashSet.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Generic;

void DemonstrateDictionariesAndSets() {
    // 1. Dictionary<TKey, TValue>
    Dictionary<String, int> inventory;
    inventory.Add("Widget", 150);
    inventory.Add("Gadget", 75);
    inventory["Doohickey"] = 42; // Indexer assignment

    // Safe retrieval with TryGetValue
    int iStock = 0;
    if (inventory.TryGetValue("Widget", iStock)) {
        Console::WriteLine("Widget stock: {0} units", iStock);
    }

    // Iterate key-value pairs with range-for
    Console::WriteLine("Full Inventory:");
    for (const auto& kvp : inventory) {
        Console::WriteLine(" - {0}: {1}", kvp.Key, kvp.Value);
    }

    // 2. HashSet<T> (Uniqueness Guarantee)
    HashSet<String> allowedRoles;
    allowedRoles.Add("Administrator");
    allowedRoles.Add("Editor");
    allowedRoles.Add("Administrator"); // Duplicate silently ignored

    Console::WriteLine("Allowed roles count: {0}", allowedRoles.GetCount()); // 2
    Console::WriteLine("Is Viewer allowed: {0}", 
        allowedRoles.Contains("Viewer") ? "Yes" : "No");
}

3. Thread-Safe Concurrent Collections

The DotNetDupe::System::Collections::Concurrent namespace provides thread-safe data structures designed for highly concurrent multi-threaded applications:

  • ConcurrentDictionary<TKey, TValue>: Supports atomic TryAdd(), GetOrAdd(), and AddOrUpdate().
  • BlockingCollection<T>: Provides bounded capacity and blocking Take() / Add() across worker threads.
  • ConcurrentQueue<T>, ConcurrentStack<T>, ConcurrentBag<T>: Thread-safe producer/consumer collections implementing IProducerConsumerCollection<T>.
#include "System/Console.h"
#include "System/String.h"
#include "System/Collections/Concurrent/ConcurrentDictionary.h"
#include "System/Collections/Concurrent/BlockingCollection.h"
#include "System/Threading/Thread.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Concurrent;
using namespace DotNetDupe::System::Threading;

void DemonstrateConcurrentCollections() {
    // 1. ConcurrentDictionary with atomic operations
    ConcurrentDictionary<String, int> sessionHits;
    sessionHits.TryAdd("user_101", 1);
    
    // Atomically increment or initialize hits
    sessionHits.AddOrUpdate("user_101", 1, sessionHits["user_101"] + 1);
    sessionHits.GetOrAdd("user_202", 1);

    Console::WriteLine("User 101 hits: {0}", sessionHits["user_101"]); // 2

    // 2. Bounded BlockingCollection (Producer-Consumer pipeline)
    BlockingCollection<int> workQueue(5); // Upper bound of 5 items

    // Producer Thread
    Thread producerThread([&workQueue]() {
        for (int i = 1; i <= 5; ++i) {
            workQueue.Add(i * 100);
            Thread::Sleep(10);
        }
        workQueue.CompleteAdding(); // Signal no more items will be added
    });

    producerThread.Start();

    // Consumer (main thread)
    int iWorkItem = 0;
    while (workQueue.TryTake(iWorkItem, -1)) { // -1 waits until item is available
        Console::WriteLine("Processed work item: {0}", iWorkItem);
    }

    producerThread.Join();
    Console::WriteLine("Pipeline complete: {0}", workQueue.IsCompleted() ? "True" : "False");
}

4. Snapshot Iteration & Direct LINQ Integration

Unlike traditional C++ containers where concurrent iteration during modification causes data corruption, DotNetDupe's concurrent collections provide lock-free snapshot iteration. Calling GetEnumerator(), using range-based for, or invoking LINQ queries captures a thread-safe snapshot under mutual exclusion and iterates lock-free.

All collections can be queried with LINQ directly without any wrapper calls:

#include "System/Console.h"
#include "System/String.h"
#include "System/Linq.h"
#include "System/Collections/Concurrent/ConcurrentQueue.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Concurrent;

void DemonstrateSnapshotAndLinq() {
    ConcurrentQueue<int> scoreQueue;
    scoreQueue.Enqueue(45);
    scoreQueue.Enqueue(92);
    scoreQueue.Enqueue(78);
    scoreQueue.Enqueue(88);
    scoreQueue.Enqueue(63);

    // Direct LINQ method chaining directly on ConcurrentQueue:
    // Filter passing scores (>= 70), sort descending, and materialize to List<int>
    auto topScores = scoreQueue
        .Where([](int score) { return score >= 70; })
        .OrderByDescending([](int score) { return score; })
        .ToList();

    Console::WriteLine("Passing Scores (Descending):");
    for (int score : topScores) {
        Console::WriteLine(" - {0}", score);
    }
}

Language Integrated Query (LINQ) โšก

DotNetDupe brings the expressive, declarative power of C# .NET's Language Integrated Query (System.Linq, ECMA-335) directly to modern C++. Through fluent operator chaining and type-safe lambdas, you can filter, sort, transform, group, and aggregate collections without verbose imperative loops, temporary vectors, or STL algorithm boilerplate.

All LINQ operators work natively and directly on any DotNetDupe collection (List<T>, Array<T>, LinkedList<T>, HashSet<T>, Dictionary<K, V>, Queue<T>, Stack<T>, SortedSet<T>, SortedDictionary<K, V>) through the standard IEnumerable<T> interface hierarchy, offering pure library types, value semantics, and exception-safe RAII memory management.

Key Capabilities

Category Operators & Methods
Filtering & Partitioning Where, Take, TakeWhile, Skip, SkipWhile, Distinct
Transformations & Projections Select, SelectMany, Zip
Ordering & Sorting OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping & Bucketing GroupBy (IGrouping<TKey, TElement>), Key, Count, Elements
Aggregations & Reductions Sum, Min, Max, Average, Aggregate, Count
Quantifiers & Search Any, All, Contains, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault
Set Operations Union, Intersect, Except, Concat
Generators & Materialization Enumerable<T>::Range(), Repeat(), Empty(), ToList(), ToArray(), ToDictionary(), ToHashSet()

1. Filtering, Sorting & Projections

Chain Where, OrderByDescending, ThenBy, and Select into a clean query pipeline. Results can be materialized into a List<T> using ToList() or an Array<T> using ToArray().

#include "System/Console.h"
#include "System/String.h"
#include "System/Linq.h"
#include "System/Collections/Generic/List.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Generic;
using namespace DotNetDupe::System::Linq;

struct ProductItem {
    String Name;
    String Category;
    int Price;
    int InStock;
};

void DemonstrateFilteringAndSorting() {
    List<ProductItem> inventory;
    inventory.Add({"Espresso Machine", "Appliances", 299, 12});
    inventory.Add({"Coffee Grinder",   "Appliances",  89,  0});
    inventory.Add({"Dark Roast Beans", "Coffee",      15, 50});
    inventory.Add({"French Press",     "Appliances",  35,  8});
    inventory.Add({"Colombian Roast",  "Coffee",      18, 25});

    // Fluent LINQ Pipeline: Filter in-stock appliances, sort by price descending, project formatted summary
    auto popularItems = inventory
        .Where([](const ProductItem& p) { return p.InStock > 0 && p.Category == "Appliances"; })
        .OrderByDescending([](const ProductItem& p) { return p.Price; })
        .Select([](const ProductItem& p) {
            return String::Format("{0} - ${1} ({2} available)", p.Name, p.Price, p.InStock);
        })
        .ToList();

    Console::WriteLine("Available Appliances (Sorted by Price):");
    for (int i = 0; i < popularItems.GetCount(); ++i) {
        Console::WriteLine("  โ€ข {0}", popularItems[i]);
    }
}

2. Grouping & Bucket Aggregations

Use GroupBy to partition collections by key into groups implementing IGrouping<TKey, TElement>. Each group exposes Key(), Count(), and indexer access (group[i]) or Elements().

#include "System/Console.h"
#include "System/String.h"
#include "System/Linq.h"
#include "System/Collections/Generic/List.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Generic;
using namespace DotNetDupe::System::Linq;

struct Employee {
    String Name;
    String Department;
    int Salary;
};

void DemonstrateGrouping() {
    List<Employee> staff;
    staff.Add({"Alice",   "Engineering", 125000});
    staff.Add({"Bob",     "Marketing",    85000});
    staff.Add({"Charlie", "Engineering", 140000});
    staff.Add({"Diana",   "Finance",     110000});
    staff.Add({"Evan",    "Engineering",  95000});
    staff.Add({"Fiona",   "Marketing",    92000});

    // Group employees by Department and sort buckets by member count descending
    auto deptGroups = staff
        .GroupBy([](const Employee& e) { return e.Department; })
        .OrderByDescending([](const auto& g) { return g.Count(); })
        .ToList();

    for (int i = 0; i < deptGroups.GetCount(); ++i) {
        const auto& group = deptGroups[i];
        Console::WriteLine("\nDepartment: {0} ({1} members)", group.Key(), group.Count());

        for (int j = 0; j < group.Count(); ++j) {
            Console::WriteLine("  - {0} (${1})", group[j].Name, group[j].Salary);
        }
    }
}

3. Aggregations & Quantifiers

Perform reductions, scalar metrics, and boolean sequence assertions across strongly typed datasets with ease.

#include "System/Console.h"
#include "System/String.h"
#include "System/Linq.h"
#include "System/Collections/Generic/List.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Generic;
using namespace DotNetDupe::System::Linq;

void DemonstrateAggregations() {
    List<int> readings = { 42, 18, 95, 73, 60, 84, 51 };

    // Numeric Aggregations
    int sum = readings.Sum();
    int min = readings.Min();
    int max = readings.Max();
    double avg = readings.Average();
    int highCount = readings.Count([](int n) { return n >= 70; });

    Console::WriteLine("Readings Stats -> Sum: {0}, Min: {1}, Max: {2}, Avg: {3}, High (>=70): {4}",
                       sum, min, max, avg, highCount);

    // Quantifiers & Predicate Matching
    bool hasOver90   = readings.Any([](int n) { return n > 90; });
    bool allPositive = readings.All([](int n) { return n > 0; });
    bool contains51  = readings.Contains(51);

    Console::WriteLine("Any > 90? {0} | All > 0? {1} | Contains 51? {2}",
                       hasOver90 ? "Yes" : "No",
                       allPositive ? "Yes" : "No",
                       contains51 ? "Yes" : "No");
}

4. Set Operations, Generators & Materialization

Combine sequences with set theory operators (Union, Intersect, Except), generate data streams on the fly with Range() and Repeat(), and materialize query pipelines directly into targeted collection structures.

#include "System/Console.h"
#include "System/String.h"
#include "System/Linq.h"
#include "System/Collections/Generic/List.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::System::Collections::Generic;
using namespace DotNetDupe::System::Linq;

void DemonstrateGeneratorsAndSetOps() {
    // 1. Sequence Generation via Range
    auto squares = Enumerable<int>::Range(1, 5)
        .Select([](int n) { return n * n; })
        .ToList(); // [1, 4, 9, 16, 25]

    Console::WriteLine("Generated Squares: [{0}, {1}, {2}, {3}, {4}]",
                       squares[0], squares[1], squares[2], squares[3], squares[4]);

    // 2. Set Operations
    List<int> setA = { 1, 2, 3, 4, 5 };
    List<int> setB = { 4, 5, 6, 7, 8 };

    auto common = setA.Intersect(setB).ToList(); // [4, 5]
    auto uniqueToA = setA.Except(setB).ToList();  // [1, 2, 3]
    auto combined = setA.Union(setB).ToList();   // [1, 2, 3, 4, 5, 6, 7, 8]

    Console::WriteLine("Common (Intersect): Count = {0}", common.GetCount());
    Console::WriteLine("Unique to A (Except): Count = {0}", uniqueToA.GetCount());
    Console::WriteLine("Combined (Union): Count = {0}", combined.GetCount());

    // 3. Fast Lookup Dictionary Materialization
    List<String> words = { "Apple", "Banana", "Cherry" };
    auto wordMap = words
        .ToDictionary([](const String& s) { return s; },
                      [](const String& s) { return s.GetLength(); });

    int len = 0;
    if (wordMap.TryGetValue("Banana", len)) {
        Console::WriteLine("Lookup 'Banana' length in Dictionary: {0}", len);
    }
}

Web API & Database Integration Guide ๐ŸŒ๐Ÿ—„๏ธ

This section provides comprehensive examples and recommended practices for hosting web services, consuming them, and using the database storage layer.

1. Hosting REST API Controllers

DotNetDupe provides an ASP.NET-like hosting model with dependency injection and controller-based routing in the WebAppCore namespaces.

Defining and Hosting a Controller
  1. Declare your data structure.
  2. Specialize the JsonConverter<T> for the structure to enable automatic serialization and deserialization.
  3. Inherit from ControllerBase and define your action methods.
  4. Bind routes using ControllerRouteBuilder and map them in the application host.
#include "WebAppCore/Builder/WebApplicationBuilder.h"
#include "WebAppCore/Builder/WebApplication.h"
#include "WebAppCore/Controllers/ControllerBase.h"
#include "System/Collections/Generic/List.h"

using namespace DotNetDupe::System;
using namespace DotNetDupe::WebAppCore::Builder;
using namespace DotNetDupe::WebAppCore::Controllers;

// 1. Declare the data model
struct ProductItem {
    String Name;
    int Price = 0;
};

// 2. Specialize JsonConverter for serialization/deserialization
namespace DotNetDupe {
    namespace System {
        namespace Text {
            namespace Json {
                template <>
                struct JsonConverter<ProductItem> {
                    static JsonElement Write(const ProductItem& value) {
                        JsonElement obj(JsonValueKind::Object);
                        obj.SetProperty("name", JsonElement(value.Name));
                        obj.SetProperty("price", JsonElement(static_cast<double>(value.Price)));
                        return obj;
                    }
                    static ProductItem Read(const JsonElement& element) {
                        ProductItem p;
                        JsonElement prop;
                        if (element.TryGetProperty("name", prop)) p.Name = prop.GetString();
                        if (element.TryGetProperty("price", prop)) p.Price = prop.GetInt32();
                        return p;
                    }
                };
            }
        }
    }
}

// 3. Define the controller
class ProductsController : public ControllerBase {
public:
    // GET /api/products
    Collections::Generic::List<ProductItem> GetProducts() {
        Collections::Generic::List<ProductItem> list;
        list.Add(ProductItem{"Espresso Machine", 299});
        list.Add(ProductItem{"Coffee Grinder", 89});
        return list;
    }

    // POST /api/products
    String CreateProduct(const ProductItem& product) {
        return Created(String("Added ") + product.Name);
    }
};

int main() {
    auto builder = WebApplication::CreateBuilder();

    // 4. Register and configure routes on the controller
    builder->AddController<ProductsController>("/api/products")
        .MapGet("", &ProductsController::GetProducts)
        .MapPost("", &ProductsController::CreateProduct);

    auto app = builder->Build();
    app->MapControllers(); // Applies the registered mappings

    app->Run("http://127.0.0.1:5000");
}

2. Consuming REST APIs

DotNetDupe makes client-side web requests simple. You can query endpoints using a low-level HTTP client or a strongly-typed REST resource client.

Option A: Low-level HTTP Client (HttpClient)

Best for general, raw request handling, sending custom headers, or performing authentication (like setting Bearer tokens).

#include "System/Net/Http/HttpClient.h"
#include "System/Console.h"

void GetRawData() {
    using namespace DotNetDupe::System::Net::Http;
    
    HttpClient client;
    
    // Add default headers (e.g. JWT Auth token)
    client.GetDefaultRequestHeaders().Add("Authorization", "Bearer your_token_here");
    
    auto response = client.Get("http://127.0.0.1:5000/api/products");
    if (response->GetStatusCode() == 200) {
        DotNetDupe::System::String json = response->GetContent()->ReadAsString();
        DotNetDupe::System::Console::WriteLine(json);
    }
}

Best for standard RESTful resources. It handles payload serialization/deserialization to your model structures automatically.

#include "System/Net/Http/RestClient.h"
#include "System/Console.h"

void SyncProducts() {
    using namespace DotNetDupe::System::Net::Http;
    
    // Point the RestClient to your resource endpoint
    RestClient<ProductItem> client("http://127.0.0.1:5000/api/products");
    
    // GET all resources automatically parsed into List<T>
    auto products = client.GetAll();
    
    // POST new resource automatically serialized to JSON
    ProductItem newProduct{"Milk Frother", 35};
    DotNetDupe::System::String reply = client.Post(newProduct);
}

3. Using the Database Layer

DotNetDupe emulates C# ADO.NET (SqlConnection, SqlCommand, SqlDataReader) for SQL execution.

  1. Routing and Engine Fallback via Connection String:
    • In-Memory Emulation (Default): Use Engine=InMemory; for unit testing or when you don't want server/file dependencies. This runs an in-memory SQL parsing engine.
    • Persistent SQLite: Use Engine=SQLite; Data Source=my_db.db; when you need actual SQLite file persistence. Note: Requires compilation with the DOTNETDUPE_USE_SQLITE flag defined.
  2. Always Parameterize Queries: Use AddWithValue parameters to protect queries against parsing issues and SQL syntax injections.
  3. Use RAII and Smart Pointers: Wrap database commands and readers in smart pointers to guarantee resource cleanup.
#include "System/Data/SqlClient/SqlConnection.h"
#include "System/Data/SqlClient/SqlCommand.h"
#include "System/Console.h"

void AccessDatabase() {
    using namespace DotNetDupe::System;
    using namespace DotNetDupe::System::Data::SqlClient;

    try {
        // Connect. Uses default In-Memory emulation engine if SQLite is not compiled.
        SqlConnection conn("Data Source=InventoryDb;Engine=InMemory;");
        conn.Open();

        // 1. Create table schema
        auto cmdCreate = conn.CreateCommand();
        cmdCreate->SetCommandText("CREATE TABLE Items (Id INT, Name VARCHAR, Price INT)");
        cmdCreate->ExecuteNonQuery();

        // 2. Parameterized Insert (Recommended)
        auto cmdInsert = conn.CreateCommand();
        cmdInsert->SetCommandText("INSERT INTO Items (Id, Name, Price) VALUES (@id, @name, @price)");
        cmdInsert->GetParameters()->AddWithValue("@id", 101);
        cmdInsert->GetParameters()->AddWithValue("@name", "Bean Grinder");
        cmdInsert->GetParameters()->AddWithValue("@price", 75);
        cmdInsert->ExecuteNonQuery();

        // 3. Querying rows
        auto cmdSelect = conn.CreateCommand();
        cmdSelect->SetCommandText("SELECT Id, Name, Price FROM Items WHERE Price < @maxPrice");
        cmdSelect->GetParameters()->AddWithValue("@maxPrice", 100);

        auto reader = cmdSelect->ExecuteReader();
        while (reader->Read()) {
            int id = reader->GetInt32(0);
            String name = reader->GetString(1);
            int price = reader->GetInt32(2);

            Console::Write("Item: ");
            Console::Write(name);
            Console::Write(" costs $");
            Console::WriteLine(price);
        }

        conn.Close();
    } catch (const Exception& ex) {
        Console::Write("Database Error: ");
        Console::WriteLine(ex.What());
    }
}

STL vs DotNetDupe Comparison โš–๏ธ

DotNetDupe is designed to be more intuitive and less verbose than the standard C++ STL. Architectural comparisons, usage patterns, and class-by-class overviews are available in the Interactive Documentation Portal.

Sample Client and Test Code ๐Ÿงช

The repository includes DotNetDupeDemo (a sample console application) and DotNetDupeTests (unit tests) projects. These projects demonstrate how to integrate and use the DotNetDupe library. You can refer to their .vcxproj files for examples of how to configure your own projects to consume the DotNetDupe NuGet package.

API Reference ๐Ÿ“–

DotNetDupe provides comprehensive documentation through an interactive portal:

  • ๐ŸŒ Interactive Documentation Portal: Modern web interface with real-time class search, namespace categorization, section-wise API browsing, and C# vs C++ code comparisons.

Generating API Documentation Locally: You can rebuild the entire documentation suite locally at any time using PowerShell:

powershell -ExecutionPolicy Bypass -File .\scripts\Generate-Docs.ps1 -OpenBrowser

For detailed information on the available classes, methods, and their usage, please refer to the comprehensive API documentation for each class:

Navigation: Click any Class Name to inspect its C++ header interface, or click ๐Ÿ“– to open its generated Doxygen API reference.

Namespace: DotNetDupe::System   ๐Ÿ“–

Core Primitives & Base Classes

Class Description
Object   ๐Ÿ“– Supports all classes in the .NET class hierarchy and provides low-level services to derived classes.
SmartPointer<T>   ๐Ÿ“– Unified smart pointer supporting RAII unique and shared reference-counted ownership.
EventArgs   ๐Ÿ“– Base class for event data payloads with Empty singleton representation.
EventHandler<TEventArgs>   ๐Ÿ“– Multicast delegate supporting publisher-subscriber event model with token unsubscription.
Char   ๐Ÿ“– Represents character code points and provides Unicode classification and transformation methods.
String   ๐Ÿ“– Represents immutable sequences of UTF-8 and UTF-16 characters (String and WString).
Array<T>   ๐Ÿ“– Provides methods for creating, manipulating, searching, and sorting arrays.
BitConverter   ๐Ÿ“– Converts base data types to arrays of bytes, and arrays of bytes to base data types.
Buffer   ๐Ÿ“– Manipulates arrays of primitive types efficiently.
Console   ๐Ÿ“– Reads and writes to standard I/O streams with full color control and stream redirection.
Convert   ๐Ÿ“– Converts base data types and hexadecimal strings.
DateTime   ๐Ÿ“– Represents an instant in time, typically expressed as a date and time of day.
DateTimeOffset   ๐Ÿ“– Represents a point in time relative to UTC with time zone offset.
TimeSpan   ๐Ÿ“– Represents a time interval.
TimeZone   ๐Ÿ“– Represents a time zone.
TimeZoneInfo   ๐Ÿ“– Represents any time zone in the world with Daylight Saving adjustments.
DaylightTime   ๐Ÿ“– Defines the period of daylight saving time.
TimeProvider   ๐Ÿ“– Provides a testable abstraction for date and time.
Guid   ๐Ÿ“– Represents a globally unique identifier (GUID).
Environment   ๐Ÿ“– Provides environment variables, machine info, and platform properties.
OperatingSystem   ๐Ÿ“– Represents operating system platform identifiers and version metadata.
Random   ๐Ÿ“– Represents a pseudo-random number generator.
Uri   ๐Ÿ“– Provides an object representation of Uniform Resource Identifiers (URI).
UriBuilder   ๐Ÿ“– Provides convenient mutation of URI components.
UriComponents   ๐Ÿ“– Specifies parts of a URI.
UriFormat   ๐Ÿ“– Controls how URI information is escaped.
UriParser   ๐Ÿ“– Parses and validates URI schemes.
GenericUriParser   ๐Ÿ“– Customizable parser for hierarchical URI schemes.
Math   ๐Ÿ“– Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions, as well as time-series statistics.
Version   ๐Ÿ“– Represents version numbers (major.minor.build.revision).

Core Interfaces

Interface Description
IDisposable   ๐Ÿ“– Defines a mechanism for deterministic release of unmanaged resources.
IClonable   ๐Ÿ“– Defines mechanisms for deep or shallow object cloning.
IComparable   ๐Ÿ“– Defines comparison method for sorting and ordering.
IComparable<T>   ๐Ÿ“– Defines strongly-typed comparison method for sorting and ordering.
IFormatProvider<T>   ๐Ÿ“– Provides custom type-formatting services.
IServiceProvider   ๐Ÿ“– Defines service object resolution mechanism for dependency injection.

Exceptions

Exception Description
Exception   ๐Ÿ“– Root exception class for all DotNetDupe library errors.
SystemException   ๐Ÿ“– Base class for system-level runtime exceptions.
ArgumentException   ๐Ÿ“– Thrown when an argument passed to a method is invalid.
ArgumentNullException   ๐Ÿ“– Thrown when a null argument is passed to a non-null parameter.
ArgumentOutOfRangeException   ๐Ÿ“– Thrown when an argument falls outside allowable boundary limits.
ArithmeticException   ๐Ÿ“– Thrown for errors in mathematical or arithmetic operations.
FormatException   ๐Ÿ“– Thrown when string or argument formatting is invalid.
NotImplementedException   ๐Ÿ“– Thrown when a requested method or feature is not implemented.
OverflowException   ๐Ÿ“– Thrown on arithmetic or conversion overflow.

Namespace: DotNetDupe::System::Collections::Generic   ๐Ÿ“–

Classes

Class Description
IEnumerable<T>   ๐Ÿ“– Base interface exposing an enumerator and native LINQ operators over generic collections.
IEnumerator<T>   ๐Ÿ“– Supports simple iteration over a generic collection.
ICollection<T>   ๐Ÿ“– Defines size, enumerators, and mutation methods for generic collections.
IReadOnlyCollection<T>   ๐Ÿ“– Represents a strongly-typed, read-only collection of elements.
IList<T>   ๐Ÿ“– Represents a collection of objects that can be individually accessed by index.
IReadOnlyList<T>   ๐Ÿ“– Represents a read-only collection of elements accessible by index.
ISet<T>   ๐Ÿ“– Base interface for the abstraction of sets and mathematical set operations.
IDictionary<TKey, TValue>   ๐Ÿ“– Generic collection of key/value pairs accessible by key.
IReadOnlyDictionary<TKey, TValue>   ๐Ÿ“– Represents a read-only collection of key/value pairs.
KeyValuePair<TKey, TValue>   ๐Ÿ“– Defines a key/value pair that can be set or retrieved.
List<T>   ๐Ÿ“– Strongly-typed dynamic array list implementing IList<T>.
Dictionary<TKey, TValue>   ๐Ÿ“– Key/value hash map collection implementing IDictionary<TKey, TValue>.
HashSet<T>   ๐Ÿ“– Set of unique elements backed by a hash table implementing ISet<T>.
Queue<T>   ๐Ÿ“– First-In-First-Out (FIFO) queue collection implementing IReadOnlyCollection<T>.
Stack<T>   ๐Ÿ“– Last-In-First-Out (LIFO) stack collection implementing IReadOnlyCollection<T>.
PriorityQueue<TElement, TPriority>   ๐Ÿ“– Min-heap collection of prioritized items.
SortedDictionary<TKey, TValue>   ๐Ÿ“– Key/value collection sorted by key implementing IDictionary<TKey, TValue>.
SortedSet<T>   ๐Ÿ“– Ordered unique collection maintained in sorted order implementing ISet<T>.
LinkedList<T>   ๐Ÿ“– Doubly-linked list collection implementing ICollection<T>.
Generic Collections Overview   ๐Ÿ“– Comprehensive guide and comparison of generic collection types.

Namespace: DotNetDupe::System::Collections::Concurrent   ๐Ÿ“–

Classes

Class Description
IProducerConsumerCollection<T>   ๐Ÿ“– Defines methods to manipulate thread-safe collections intended for producer/consumer usage.
ConcurrentDictionary<TKey, TValue>   ๐Ÿ“– Thread-safe key/value collection for concurrent multi-threaded access.
ConcurrentQueue<T>   ๐Ÿ“– Lock-free thread-safe First-In-First-Out (FIFO) queue.
ConcurrentStack<T>   ๐Ÿ“– Lock-free thread-safe Last-In-First-Out (LIFO) stack.
ConcurrentBag<T>   ๐Ÿ“– Thread-safe unordered object container with thread-local storage.
BlockingCollection<T>   ๐Ÿ“– Thread-safe collection providing blocking producer-consumer capabilities.
Concurrent Collections Overview   ๐Ÿ“– Comprehensive guide and architecture of lock-free and thread-safe collections.

Namespace: DotNetDupe::System::Linq   ๐Ÿ“–

Classes

Class Description
Enumerable<T>   ๐Ÿ“– Fluent query operators providing declarative transformations, filtering, projections, partitioning, aggregations, and generators.
OrderedEnumerable<T>   ๐Ÿ“– Sorted sequence supporting custom stable multi-key ordering (OrderBy, OrderByDescending, ThenBy, ThenByDescending) with zero STL algorithm dependencies.
IGrouping<TKey, TElement>   ๐Ÿ“– Represents a collection of objects that share a common key produced by GroupBy.
Linq   ๐Ÿ“– Master umbrella include file for DotNetDupe LINQ queries and operators.

Namespace: DotNetDupe::System::IO   ๐Ÿ“–

Classes

Class Description
File   ๐Ÿ“– Static helper methods for file creation, reading, writing, moving, and deletion.
Directory   ๐Ÿ“– Static helper methods for creating (including recursive creation), moving, deleting, and enumerating directories.
Path   ๐Ÿ“– Performs cross-platform directory and file path string operations.
Stream   ๐Ÿ“– Abstract base class for byte sequence streams.
FileStream   ๐Ÿ“– Provides a byte stream for files supporting synchronous read/write.
MemoryStream   ๐Ÿ“– Creates a stream whose backing store is memory.
TextReader   ๐Ÿ“– Abstract reader for sequential character input.
TextWriter   ๐Ÿ“– Abstract writer for sequential character output.
StringReader   ๐Ÿ“– Implements TextReader reading from a String.
StringWriter   ๐Ÿ“– Implements TextWriter writing characters into a string buffer.
BinaryReader   ๐Ÿ“– Reads primitive data types as binary values in Little-Endian or Big-Endian encoding from a stream.
BinaryWriter   ๐Ÿ“– Writes primitive data types in binary format with configurable endianness to a stream.

Exceptions

Exception Description
IOException   ๐Ÿ“– Thrown when an I/O or file system error occurs.
FileNotFoundException   ๐Ÿ“– Thrown when an attempt to access a file that does not exist on disk fails.
DirectoryNotFoundException   ๐Ÿ“– Thrown when part of a file or directory path cannot be found.
EndOfStreamException   ๐Ÿ“– Thrown when reading is attempted past the end of a stream.

Namespace: DotNetDupe::System::Threading & System::Threading::Tasks   ๐Ÿ“–

Classes

Class Description
Thread   ๐Ÿ“– Creates, configures, and controls OS threads.
ThreadPool   ๐Ÿ“– High-throughput worker thread pool managing parallel task execution.
Task   ๐Ÿ“– Represents asynchronous operations with continuation support.
Task<T>   ๐Ÿ“– Represents asynchronous operations returning a result value.
WaitHandle   ๐Ÿ“– Abstract base class for thread synchronization handles.
EventWaitHandle   ๐Ÿ“– Manages cross-thread and system synchronization event signals.
AutoResetEvent   ๐Ÿ“– Notifies waiting threads and automatically resets to non-signaled state.
ManualResetEvent   ๐Ÿ“– Notifies waiting threads and remains signaled until manually reset.
Mutex   ๐Ÿ“– Mutual exclusion synchronization primitive (supports named inter-process mutexes).
Semaphore   ๐Ÿ“– Limits concurrent thread access to a bounded resource pool.
SemaphoreSlim   ๐Ÿ“– Lightweight alternative to Semaphore avoiding kernel transitions for fast locking.
CriticalSection   ๐Ÿ“– Low-overhead recursive mutex primitive for intra-process synchronization.
Interlocked   ๐Ÿ“– Provides atomic hardware operations (Increment, Decrement, Exchange, CompareExchange).
Lock<T>   ๐Ÿ“– Exception-safe RAII lock wrapper for synchronization primitives.

Exceptions

Exception Description
ThreadStateException   ๐Ÿ“– Thrown when a thread is in an invalid state for the requested operation.
ThreadInterruptedException   ๐Ÿ“– Thrown when a thread is interrupted while waiting.
SynchronizationLockException   ๐Ÿ“– Thrown when unlocking a synchronization object not owned by the caller.
AbandonedMutexException   ๐Ÿ“– Thrown when a thread acquires a mutex abandoned by another terminating thread.
WaitHandleCannotBeOpenedException   ๐Ÿ“– Thrown when attempting to open a non-existent named system sync handle.
SemaphoreFullException   ๐Ÿ“– Thrown when releasing a semaphore whose count is already at maximum capacity.
TaskCanceledException   ๐Ÿ“– Thrown when a task execution is canceled.

Namespace: DotNetDupe::System::Diagnostics   ๐Ÿ“–

Classes

Class Description
Process   ๐Ÿ“– Starts, manages, monitors, and redirects stdin/stdout/stderr for child processes.
Stopwatch   ๐Ÿ“– High-resolution performance timer for measuring elapsed time.
EventLog   ๐Ÿ“– Interacts with OS diagnostic event logs and writes operational entries.
EtwLogReader   ๐Ÿ“– Queries Event Tracing for Windows (ETW) channels and Linux syslog files with live event subscription listening.
SystemMetrics   ๐Ÿ“– Queries system hardware telemetry metrics including CPU %, Memory load, Disk %, Network Mbps, and top processes.
RealtimeTelemetry   ๐Ÿ“– High-frequency telemetry metrics streaming and real-time dashboard endpoint.
ActiveUserSession   ๐Ÿ“– Enumerates active and terminal user sessions across the system.
TerminalSession   ๐Ÿ“– Enumerates active, disconnected, and remote desktop (RDP) Terminal Services sessions.
ProcessStreamer   ๐Ÿ“– Progressive, non-blocking two-tier telemetry streaming and event-driven observable process enumerator.

Namespace: DotNetDupe::System::Net, Sockets & Security   ๐Ÿ“–

Classes

Class Description
Dns   ๐Ÿ“– Provides domain name resolution and IP address lookup.
Socket   ๐Ÿ“– Low-level cross-platform BSD/WinSock socket abstraction.
NetworkStream   ๐Ÿ“– Implements Stream backed by a network socket.
TcpClient   ๐Ÿ“– Client connection wrapper for TCP network services.
TcpListener   ๐Ÿ“– TCP listener for accepting incoming network connections.
UdpClient   ๐Ÿ“– User Datagram Protocol (UDP) client for datagram transmission.
SslStream   ๐Ÿ“– TLS/SSL secure stream wrapper built on OpenSSL.

Namespace: DotNetDupe::System::Net::Http   ๐Ÿ“–

Classes

Class Description
HttpClient   ๐Ÿ“– Sends HTTP/HTTPS requests and receives responses from URI endpoints.
RestClient<T>   ๐Ÿ“– Strongly-typed REST client with automated C++ structure JSON serialization/deserialization.
FileDownloader   ๐Ÿ“– High-level HTTP/HTTPS file downloader with pause/resume, speed metrics, and prompt resource disposal.
HttpRequestMessage   ๐Ÿ“– Represents an outgoing HTTP request with headers, method, and payload.
HttpResponseMessage   ๐Ÿ“– Represents an HTTP response with status code, response headers, and content stream.
HttpContent   ๐Ÿ“– Base class for HTTP entity bodies and content headers.
StringContent   ๐Ÿ“– HTTP content wrapper for text and JSON payloads.
ByteArrayContent   ๐Ÿ“– HTTP content wrapper for raw byte arrays and binary payloads.
HttpMethod   ๐Ÿ“– Represents standard HTTP request methods (GET, POST, PUT, DELETE, etc.).

Namespace: DotNetDupe::System::Text & System::Text::Json   ๐Ÿ“–

Classes

Class Description
StringBuilder   ๐Ÿ“– Mutable string buffer for high-performance string concatenation.
TextEncoding   ๐Ÿ“– Represents character encodings (UTF-8, ASCII, UTF-16).
JsonElement   ๐Ÿ“– Represents a specific JSON value within a JSON document or object hierarchy, supporting property querying, type conversion, and deserialization.
JsonSerializer   ๐Ÿ“– Serializes objects to JSON strings and deserializes JSON to C++ types with compile-time DTO mapping and container converters.

Namespace: DotNetDupe::System::Numerics   ๐Ÿ“–

Classes

Class Description
Statistics   ๐Ÿ“– Provides statistical calculation functions and time-series moving averages (Mean, Variance, StdDev, MovingAverage, ExponentialMovingAverage).

Namespace: DotNetDupe::System::Utils   ๐Ÿ“–

Classes

Class Description
StringConvert   ๐Ÿ“– Static helper methods for UTF-8 / UTF-16 conversions and type transformations.

Namespace: DotNetDupe::System::Security   ๐Ÿ“–

Classes

Class Description
UserPrincipal   ๐Ÿ“– Cross-platform user account enumeration, group memberships, and administrative privilege inspection.
HMACSHA256   ๐Ÿ“– Computes SHA256 Hash-based Message Authentication Codes.
X509Certificate2   ๐Ÿ“– Loads and inspects X.509 SSL/TLS certificates and private keys.
JWTToken   ๐Ÿ“– Encodes, parses, and validates JSON Web Tokens with HMAC-SHA256 signature verification.

Namespace: DotNetDupe::System::Data::SqlClient   ๐Ÿ“–

Classes

Class Description
SqlConnection   ๐Ÿ“– Represents an open connection to a database (supports In-Memory emulation and SQLite persistence).
SqlCommand   ๐Ÿ“– Represents SQL statements and queries to execute against a database.
SqlDataReader   ๐Ÿ“– Forward-only cursor for reading result rows from SQL queries.
SqlParameter   ๐Ÿ“– Parameter for parameterized SQL commands protecting against SQL injection.

Namespace: DotNetDupe::Extensions::DependencyInjection   ๐Ÿ“–

Classes & Interfaces

Type Description
ServiceCollection   ๐Ÿ“– Accumulates service descriptors with Transient, Scoped, and Singleton lifetimes.
ServiceProvider   ๐Ÿ“– Dependency injection container resolving registered service dependencies.
ServiceScope   ๐Ÿ“– Represents a lifetime scope for resolving scoped service instances.
ServiceScopeFactory   ๐Ÿ“– Factory for creating scoped service containers.
IServiceCollection   ๐Ÿ“– Contract for service collection builders.
IServiceScope   ๐Ÿ“– Contract for lifetime scopes.
IServiceScopeFactory   ๐Ÿ“– Contract for service scope factories.

Namespace: DotNetDupe::Extensions::Logging   ๐Ÿ“–

Classes & Interfaces

Type Description
LogManager   ๐Ÿ“– Global thread-safe static factory and cache for category loggers and file/console providers.
LoggerTextWriter   ๐Ÿ“– High-performance stream redirector bridging TextWriter output into LogManager.
LoggerFactory   ๐Ÿ“– Configures providers and generates category loggers.
Logger<T>   ๐Ÿ“– Generic category logger for class-specific logging.
ConsoleLoggerProvider   ๐Ÿ“– Renders structured console log records (Plain text and JSON format).
FileLoggerProvider   ๐Ÿ“– Thread-safe file logging provider with auto directory creation and relative path resolution.
ILogger   ๐Ÿ“– Core interface for emitting structured diagnostic log events.
ILoggerOf<T>   ๐Ÿ“– Generic category logger interface.
ILoggerProvider   ๐Ÿ“– Provider factory interface for creating loggers.
ILoggerFactory   ๐Ÿ“– Logging factory interface.

Namespace: DotNetDupe::WebAppCore   ๐Ÿ“–

Builder, Controllers & Server

Class Description
WebApplicationBuilder   ๐Ÿ“– Configures services, dependency injection, and builds the WebApplication host.
WebApplication   ๐Ÿ“– Configures routing endpoints and executes the HTTP server listener.
WebAppServer   ๐Ÿ“– Web server hosting static website content (index.html, CSS, JS) and REST APIs simultaneously.
ControllerBase   ๐Ÿ“– Base class for ASP.NET MVC / Web API style controllers (Ok, Created, NotFound, BadRequest).
ControllerRouteBuilder<T>   ๐Ÿ“– Maps controller actions and automates JSON payload serialization and deserialization.
HttpContext   ๐Ÿ“– Encapsulates HTTP request and response context for individual HTTP transactions.
HttpRequest   ๐Ÿ“– Represents incoming HTTP request headers, query parameters, and body.
HttpResponse   ๐Ÿ“– Represents outgoing HTTP response status codes, headers, and body.
Push Notifications (SSE & WebSockets)   ๐Ÿ“– Real-time push notifications via Server-Sent Events (SSE) and full-duplex WebSockets.

Project Status ๐Ÿšง

DotNetDupe is currently under active development. I am continuously working on expanding the API coverage and improving stability.

Contributions ๐Ÿ‘‹

Contributions to the DotNetDupe project are highly welcome! Whether it's bug reports, feature requests, code contributions, or documentation improvements, your help is invaluable. Please refer to GitHub's general contributing guidelines for more information on how to get started.

CI/CD Pipeline ๐Ÿš€

This repository uses GitHub Actions to automate the build, test, and release process.

Workflow Details

  • Build & Test Matrix: Every push to main and all pull requests trigger a full build (Debug & Release) across Windows (MSBuild) and Linux (CMake/GCC), running all 660 Google Tests.
  • GitHub CodeQL Analysis: Continuous semantic security vulnerability scanning on every push, pull request, and weekly schedule via github/codeql-action.
  • Quality Gates & Static Analysis: Automated enforcement of 11 Quality Gate metrics (LLOC โ‰ค 15, CCN โ‰ค 10, Nesting depth โ‰ค 4, Hungarian SmartPointers, zero empty catch blocks, zero standard throw std::* exceptions, zero raw pointer ownership).
  • Code Coverage: Automated code coverage measurement via OpenCppCoverage (> 80% line coverage required) and static analysis HTML report generation.
  • NuGet Release: Pushing a tag (e.g., v1.0.0) triggers the creation and publishing of the NuGet package to nuget.org.

Code Coverage & Static Analysis ๐Ÿ“Š

How to Release

  1. Update the version in DotNetDupe.nuspec.
  2. Commit and push the changes.
  3. Create and push a new tag:
    git tag v1.0.0
    git push origin v1.0.0
    
    Note: Requires NUGET_API_KEY to be set in GitHub repository secrets.

License ๐Ÿ“„

This project is licensed under the MIT License. See the LICENSE file for details.

Generated Content ๐Ÿค–

This project is a unique blend of manual craftsmanship and AI-powered development, built collaboratively by myself and my peer Antigravity. While the initial core components were meticulously crafted by hand, the remaining code, including many classes, methods, and their corresponding unit tests, were developed and expanded with Antigravity. This project stands as a testimonial on how persistent human effortโ€”spanning weekends and late eveningsโ€”combined with generative AI can build an entire, robust system from scratch.

Contact ๐Ÿ“ง

For questions or support, please open an issue on the GitHub repository or contact sudheeshps@gmail.com.


Release Notes ๐Ÿ“

v5.0.4 (Current / Latest)

  • Drive Metrics & Telemetry (System::IO::DriveInfo):
    • Added full support for querying drive metrics, volume labels, drive formats (NTFS, FAT32, ext4), total drive capacity, and available/total free space via DriveInfo::GetDrives(), GetTotalSize(), GetTotalFreeSpace(), and GetAvailableFreeSpace().
  • Recursive Directory Traversal (System::IO::Directory & SearchOption):
    • Introduced SearchOption enumeration (SearchOption::TopDirectoryOnly and SearchOption::AllDirectories).
    • Added recursive directory searching overloads to Directory::GetFiles, Directory::GetDirectories, and Directory::GetFileSystemEntries with permission-resilient folder iteration.
  • 64-bit Stream Precision (System::IO::Stream & FileStream):
    • Upgraded core stream architecture with 64-bit positioning (int64_t) supporting multi-terabyte file streaming: GetLength64(), GetPosition64(), SetPosition64(), and Seek64().
  • Streaming Cryptographic SHA-256 (System::Security::Cryptography::SHA256):
    • Added FIPS 180-2 compliant streaming SHA-256 hash algorithm.
    • Supports continuous byte buffers, stream sources (ComputeHash(SmartPointer<Stream>)), static one-shot hashing (HashData), and hexadecimal output formatting (ToHexString).
  • Batch Task Synchronization (System::Threading::Tasks::Task::WaitAll):
    • Added barrier synchronization to wait on collections or arrays of asynchronous Task instances concurrently.

v5.0.3 - 2026-10-01

  • Linux Native NuGet Runtime Packaging:
    • Bundled pre-built Linux native shared library (runtimes/linux-x64/native/libDotNetDupe.so) alongside Windows x64 binaries.
    • Updated MSBuild DotNetDupe.targets to automatically link and stage native OpenSSL libraries (-lssl -lcrypto).
  • OpenSSL 4.0.1 Native Dependencies:
    • Bundled native OpenSSL 4.0.1 binaries for Linux (libssl.so.4, libcrypto.so.4) and Windows (libssl-4-x64.dll, libcrypto-4-x64.dll, libssl-4.dll, libcrypto-4.dll).
  • Mathematical Primitives & Time-Series Statistics (System::Math & System::Numerics::Statistics):
    • Implemented IEEE 754 arithmetic and transcendental methods: Abs, Min, Max, Clamp, Round, Sqrt, Pow, Log, Sin, Cos, and Tan.
    • Added statistical operations and financial time-series moving window indicators: Mean, Variance, StandardDeviation (StdDev), MovingAverage, MovingAverageSeries, ExponentialMovingAverage, and ExponentialMovingAverageSeries.
  • Generic JSON DTO Serialization & DOM Accessors (System::Text::Json):
    • Added strongly-typed generic serialization and deserialization via compile-time SFINAE DTO mapping (JsonSerializer::Serialize<T>, JsonSerializer::Deserialize<T>).
    • Added built-in type converters for Array<T>, short, uint, int64, Guid, and DateTime.
    • Added JsonElement property helpers: HasProperty, GetProperty, GetPropertyString, GetPropertyInt32, GetPropertyDouble, GetPropertyAs<T>, and Deserialize<T>.

v5.0.2 - 2026-09-29

  • Concurrent Collections Interface Hierarchy Retrofit:
    • Retrofitted ConcurrentQueue<T>, ConcurrentStack<T>, ConcurrentBag<T>, BlockingCollection<T>, and ConcurrentDictionary<TKey, TValue> to inherit generic base collection interfaces (IReadOnlyCollection<T>, IEnumerable<T>, IDictionary<TKey, TValue>).
    • Introduced IProducerConsumerCollection<T> base interface.
  • Lock-Free Snapshot Enumeration & Direct LINQ Integration:
    • Implemented thread-safe snapshot iteration across all concurrent collections.
    • Enabled direct LINQ method chaining directly on concurrent collections without intermediate conversions.
  • Debugger Visualizer & Documentation:
    • Updated DotNetDupe.natvis visualizers for concurrent containers.
    • Added dedicated Smart Pointers and Collections documentation sections with compile-ready code snippets to README.md.

v5.0.1 - 2026-09-29

  • LINQ Documentation & Guide:
    • Added dedicated Language Integrated Query (LINQ) section to README.md with practical code examples.
    • Updated repository Table of Contents and navigation anchors.

v5.0.0 - 2026-09-28

  • Language Integrated Query (System::Linq):
    • Major milestone release introducing zero-STL-allocation LINQ query operators: Where, Select, SelectMany, OrderBy, OrderByDescending, ThenBy, ThenByDescending, GroupBy, Distinct, Take, Skip, Concat, Union, Intersect, Except, Zip, and Reverse.
    • Added numeric aggregations and quantifiers: Any, All, Contains, First, Single, ElementAt, Count, Sum, Min, Max, Average, and Aggregate.
    • Added sequence generators: Range and Repeat.
    • Added collection materialization: ToList, ToArray, ToDictionary, and ToHashSet.
    • Supported standard C++ range-based for loops across all queryable sequences.
  • Cross-Platform Parity:
    • Full functional and test parity across Linux (WSL/GCC/CMake) and Windows (MSVC).
  • SmartX File Querying:
    • Integrated LINQ querying directly over file system entries.

v4.0.7 - 2026-09-10

  • Documentation & Report Links:
    • Fixed documentation and report links on NuGet.org and GitHub Pages.
    • Published OpenCppCoverage and Quality Gate static analysis reports under docs/CodeCoverage.

v4.0.6 - 2026-09-10

  • Standardized Documentation Header:
    • Standardized documentation navigation headers across all API reference pages with real-time NuGet versioning.
    • Resolved GitHub Pages 404 Not Found errors on header and source navigation links.

v4.0.5 - 2026-09-09

  • Package Documentation Links:
    • Fixed NuGet package documentation links to the Interactive Documentation Portal and Doxygen API reference URLs.

v4.0.4 - 2026-09-09

  • Binary I/O Streams (System::IO):
    • Added BinaryReader and BinaryWriter with configurable endianness and stream seeking support.
  • String Enhancements:
    • Added GetChars() method to DotNetDupe::System::String.
  • Smart Pointer Safety:
    • Added safe handling for this smart pointer patterns.
  • Documentation Revamp:
    • Executed complete 7-phase documentation audit and standardization across all public headers and classes.

v4.0.3 - 2026-08-20

  • C# .NET Event Model (System::EventHandler<TEventArgs>):
    • Introduced idiomatic multicast delegate event model (+=, -=) with member method binding (Add(pInstance, &Class::Method)) and thread-safe dispatch.
  • Native Process Discovery (System::Diagnostics::Process):
    • Added ultra-fast process discovery matching .NET BCL: Process::GetProcesses(), Process::GetProcessById(), and Process::GetProcessesByName().
  • On-Demand Process Enrichment:
    • Added SystemMetrics::EnrichProcessInfo() for detailed per-process CPU, memory, and handle telemetry.
  • Version String Parsing:
    • Added strict, .NET-compliant Version::Parse and Version::TryParse supporting 2, 3, and 4-component versions with full error validation.
  • Event Modernization:
    • Modernized FileDownloader and ProcessStreamer to typed multicast EventHandler callbacks.

v4.0.2 - 2026-08-19

  • Observable Process Streaming (ProcessStreamer):
    • Added progressive two-tier process discovery and telemetry streaming events.
  • Network & WebSocket Hardening:
    • Improved WebSocketException error handling and connection teardown.
  • Pimpl Move & ABI Stability:
    • Enhanced Pimpl idiom destruction and move semantics.
  • Code Coverage & Quality:
    • Updated demo application code and refreshed test coverage reports.

v4.0.1 - 2026-08-17

  • Full API Reference Transpilation:
    • Transpiled and validated complete API reference across all namespaces and classes.
  • Markdown & HTML Rendering:
    • Enhanced table rendering and cross-namespace link navigation in documentation.
  • Bug Fix:
    • Resolved event tracking issue in EtwLogReader.
  • NuGet Packaging Cleanup:
    • Cleaned up package assets for seamless local IDE and online web navigation.

v4.0.0 - 2026-08-15

  • Zero-STL Public Header Architecture:
    • Major architectural refactoring eliminating STL types (std::string, std::vector, std::map, etc.) from all public headers, guaranteeing ABI stability.
  • Pure Library Data Structures:
    • Added pure library implementations for List<T>, Dictionary<K, V>, HashSet<T>, Queue<T>, Stack<T>, PriorityQueue<T>, SortedDictionary<K, V>, SortedSet<T>, and LinkedList<T>.
  • Thread-Safe Concurrent Collections:
    • Added lock-free and fine-grained concurrent collections: ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, ConcurrentBag, and BlockingCollection.
  • Console Stream Redirection:
    • Added standard stream redirection via Console::SetOut, Console::SetError, and Console::SetIn using SmartPointer.
  • Logging Subsystem:
    • Added LoggerTextWriter stream redirector and global LogManager category caching.
  • Resilient File I/O:
    • Added FileDownloader utility with prompt file handle cleanup.
    • Added recursive Directory::CreateDirectory overload.
  • Dependency Injection:
    • Improved ServiceCollection DI container with refined lifetime management.
  • Debugger Natvis Visualizer:
    • Introduced DotNetDupe.natvis visualizer for inspecting Pimpl internal types in Visual Studio.
  • Quality Gate System:
    • Introduced 11 automated Quality Gate metrics and CI/CD validation.

v3.0.6 - 2026-08-06

  • CI/CD Quality Gate Automation:
    • Added automated Check-QualityGates.ps1 static analysis validation in CI/CD pipeline.
    • Enforced zero compiler warnings (/WX on MSVC, -Werror on GCC).
  • Live Reporting:
    • Configured live GitHub Pages badging for code coverage and static analysis compliance.

v3.0.5 - 2026-08-06

  • Smart Pointer Standardization:
    • Eliminated raw pointer usage in favor of SmartPointer<T> across all remaining classes.
  • Pipeline Optimization:
    • Refactored build scripts and CI workflow directory layouts.

v3.0.4 - 2026-08-05

  • C++20 Standard Upgrade:
    • Upgraded project compilation to ISO C++20.
  • Mini WebAppServer:
    • Added embedded web server hosting static files (index.html, CSS, JS) and REST APIs simultaneously.
  • Hardware Telemetry (SystemMetrics):
    • Added real-time CPU, memory, disk I/O, and network bandwidth telemetry.
  • Session Enumeration:
    • Added TerminalSession and ActiveUserSession to enumerate active, disconnected, and remote desktop user sessions.
  • Named Synchronization:
    • Added cross-process named support for mutexes and synchronization events.

v3.0.3 - 2026-08-05

  • Documentation Refinements:
    • Minor updates to README.md and WSL setup guidelines.

v3.0.2 - 2026-08-05

  • Web API & Database Subsystem:
    • Added database abstraction layer and SQLite connectivity.
    • Added authentication and authorization with secure HTTPS (SSL) and JWT token handling.
    • Added WebApplication host and RestClient supporting GET, POST, PUT, and DELETE.
    • Added structured logging framework (Logger).
    • Added code samples to class API reference documentation.

v3.0.1 - 2026-06-20

  • Web API & Database Support:
    • Initial introduction of WebApplication, REST endpoints, JWT authentication, and dependency injection container.
  • WSL Guide:
    • Added WSL environment provisioning and setup documentation.

v3.0.0 - 2026-05-31

  • Cross-Platform Support:
    • Added multi-platform build support for Linux (Ubuntu on WSL) via CMake/GCC alongside Windows (MSBuild).
  • Smart Pointer Ownership:
    • Introduced DotNetDupe::System::SmartPointer<T> with unique and shared ownership semantics.
  • C++ Core Guidelines:
    • Refactored core codebase to follow modern C++ Core Guidelines.

v2.1.0 - 2026-05-21

  • Threading Refinement:
    • Threading enhancements and corrected documentation for Interlocked atomic operations.

v2.0.0 - 2026-05-20

  • Threading & Synchronization (System::Threading):
    • Introduced Thread, ThreadPool, Mutex, AutoResetEvent, ManualResetEvent, Monitor, Interlocked, and Semaphore.
  • Text I/O Streams (System::IO):
    • Added TextWriter, TextReader, StringWriter, and StringReader.
  • Time Zone Support (System):
    • Added TimeZone and TimeZoneInfo classes.
  • Unit Testing:
    • Added unit test suites and sample code in DotNetDupeDemo for threading and synchronization.

v1.0.0 - 2026-05-09

  • Initial NuGet Release:
    • First official release of DotNetDupe on NuGet.
  • Core Base Class Library:
    • Foundational types: Object, String, Char, BitConverter, Convert, Console, Environment, and Math.
    • Stream and file I/O: Stream, FileStream, MemoryStream, File, and Path.
  • Build Integration:
    • Shipped MSBuild .targets and platform toolset v143 support for seamless Visual Studio integration.
Product Compatible and additional computed target framework versions.
native native is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.4 92 10/15/2026
5.0.3 110 10/2/2026
5.0.2 107 9/29/2026
5.0.1 97 9/29/2026
5.0.0 100 9/28/2026
4.0.7 119 9/10/2026
4.0.6 119 9/10/2026
4.0.5 108 9/9/2026
4.0.4 109 9/9/2026
4.0.3 169 8/20/2026
4.0.2 116 8/20/2026
4.0.1 129 8/17/2026
4.0.0 127 8/15/2026
3.0.6 124 8/6/2026
3.0.5 132 8/6/2026
3.0.4 121 8/5/2026
3.0.2 129 8/5/2026
3.0.1 140 6/20/2026
3.0.0 128 5/31/2026
2.1.0 137 5/21/2026
Loading failed

v5.0.4: Added System::IO::DriveInfo with drive metrics, volume labels, and free space telemetry; added SearchOption enumeration and recursive search overloads to System::IO::Directory; upgraded System::IO::Stream and FileStream with 64-bit positioning (int64_t); added System::Security::Cryptography::SHA256 streaming hash algorithm with FIPS 180-2 compliance; added Task::WaitAll batch synchronization in System::Threading::Tasks. Previous: v5.0.3: Bundled OpenSSL 4.0.1 native dependencies for Linux (libssl.so.4, libcrypto.so.4) and Windows (libssl-4-x64.dll, libcrypto-4-x64.dll); included pre-built Linux native shared library (runtimes/linux-x64/native/libDotNetDupe.so) with automatic -lssl -lcrypto linking and staging in DotNetDupe.targets; added System::Math and System::Numerics::Statistics with standard IEEE 754 arithmetic and financial time-series moving window indicators (MovingAverage, MovingAverageSeries, ExponentialMovingAverage, ExponentialMovingAverageSeries, Variance, StandardDeviation, StdDev); enhanced System::Text::Json::JsonSerializer and JsonElement with strongly-typed generic DTO serialization/deserialization, property accessors, and converters for Array, short, uint, int64, Guid, DateTime. Previous: v5.0.2: Interface hierarchy retrofit across concurrent collections (ConcurrentQueue, ConcurrentStack, ConcurrentBag, BlockingCollection, ConcurrentDictionary) inheriting generic base interfaces (IReadOnlyCollection, IEnumerable, IDictionary) and introducing IProducerConsumerCollection; lock-free snapshot enumeration and direct LINQ method chaining on concurrent collections; added dedicated Smart Pointers and Collections sections with code snippets to README; updated Natvis debugger visualizers. Previous: v5.0.1: Documentation updates, added dedicated LINQ section with practical examples and updated Table of Contents in README. Previous: v5.0.0: Major version release introducing System::Linq query operators with zero-STL allocation algorithms and range-for loop support; SmartX file querying integration; cross-platform Linux and Windows parity.