DotNetDupe 5.0.4
dotnet add package DotNetDupe --version 5.0.4
NuGet\Install-Package DotNetDupe -Version 5.0.4
<PackageReference Include="DotNetDupe" Version="5.0.4" />
<PackageVersion Include="DotNetDupe" Version="5.0.4" />
<PackageReference Include="DotNetDupe" />
paket add DotNetDupe --version 5.0.4
#r "nuget: DotNetDupe, 5.0.4"
#:package DotNetDupe@5.0.4
#addin nuget:?package=DotNetDupe&version=5.0.4
#tool nuget:?package=DotNetDupe&version=5.0.4
DotNetDupe ๐
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 (): 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 viaDriveInfo::GetDrives(),GetTotalSize(),GetTotalFreeSpace(), andGetAvailableFreeSpace(). - ๐ Recursive Directory Searching (
System::IO::Directory&SearchOption): AddedSearchOption::TopDirectoryOnlyandSearchOption::AllDirectoriesoverloads toDirectory::GetFiles,GetDirectories, andGetFileSystemEntrieswith permission-resilient traversal. - ๐ 64-bit Multi-Terabyte Stream Precision (
System::IO::Stream&FileStream): Seamless support for multi-gigabyte/terabyte files viaGetLength64(),GetPosition64(),SetPosition64(), andSeek64(). - ๐ 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), andJsonElementproperty helpers (HasProperty,GetProperty,GetPropertyString,GetPropertyInt32,GetPropertyDouble,GetPropertyAs<T>,Deserialize<T>). - ๐ง Linux Native NuGet Runtime Support (
libDotNetDupe.so): Native Linux x64 shared library bundled underruntimes/linux-x64/native/libDotNetDupe.sowith automated MSBuild.targetsand CMake integration. - โก Concurrent Collections & Producer-Consumer Hierarchy (
System::Collections::Concurrent): Full interface hierarchy retrofit acrossConcurrentQueue<T>,ConcurrentStack<T>,ConcurrentBag<T>,BlockingCollection<T>, andConcurrentDictionary<TKey, TValue>inheriting generic collection base interfaces (IReadOnlyCollection<T>,IEnumerable<T>,IDictionary<TKey, TValue>) and introducingIProducerConsumerCollection<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>&EventArgsModel: 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 multicastEventHandler<DownloadProgressChangedEventArgs>andEventHandler<DownloadCompletedEventArgs>with reliableFileModecreation and resumption. - ๐ Observable
ProcessStreamerModernization: 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 viaProcess::GetProcesses(),Process::GetProcessById(), andProcess::GetProcessesByName()matching .NET BCL, with on-demand per-process deep enrichment viaSystemMetrics::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, andData. - ๐ฆ 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>, andLinkedList<T>. - โก Thread-Safe Concurrent Collections (
System::Collections::Concurrent): Lock-free/fine-grained thread-safe data structures includingConcurrentDictionary,ConcurrentQueue,ConcurrentStack,ConcurrentBag, andBlockingCollection. - ๐ 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, andConsole::SetInusingSmartPointer. - ๐๏ธ LoggerTextWriter Log Redirector: Bridge standard
TextWriterstream calls directly intoLogManagerlogging providers without per-call lookup overhead. - ๐ท๏ธ Global LogManager: Thread-safe category logger caching and static factory via
LogManager::GetLogger("Category")andLogManager::GetLogger<T>(). - ๐ฒ Recursive Directory Creation: Overloaded
Directory::CreateDirectory(path, recursive)to automatically construct missing parent directory structures. - ๐ Resilient File Logging: Enhanced
FileLoggerProviderto 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 ๐
- DotNetDupe ๐
- Table of Contents ๐
- Project Overview ๐ก
- Features โจ
- Getting Started ๐
- Cross-Platform Support ๐
- WSL Setup Guide (Windows) ๐ง
- Developing Cross-Platform Applications ๐๐ป
- Usage ๐ป
- Smart Pointers & Memory Management ๐ง
- Collections & Data Structures ๐ฆ
- Language Integrated Query (LINQ) โก
- Web API & Database Integration Guide ๐๐๏ธ
- STL vs DotNetDupe Comparison โ๏ธ
- API Reference ๐
- Project Status ๐ง
- Contributions ๐
- CI/CD Pipeline ๐
- License ๐
- Generated Content ๐ค
- Contact ๐ง
- Release Notes ๐
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 withNewShared()andNewUnique()factory helpers.- Base
Objecttype system withToString(),GetType(),Equals(), andGetHashCode().
โก Delegates & Event Model (
System):EventHandler<TEventArgs>: Multicast event delegate supporting lambda, free function, and member method binding withoperator+=, token unsubscription withoperator-=, and FIFO invocation.EventArgs: Base class for event data payloads withEventArgs::Empty()singleton.
๐ค String Manipulation & Utilities (
System::String):- Full-featured
String&WStringwith UTF-8 / UTF-16 cross-transcoding. - Methods:
Format(),Split(),Join(),Replace(),Contains(),StartsWith(),EndsWith(),Trim(),PadLeft(),PadRight().
- Full-featured
๐ฆ Generic Collections (
System::Collections::Generic):- Type-safe container wrappers:
List<T>,Dictionary<K, V>,Queue<T>,Stack<T>,HashSet<T>, andKeyValuePair<K, V>.
- Type-safe container wrappers:
โก 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(), andToHashSet().
- Declarative fluent query pipeline:
๐ File I/O & System Services (
System::IO):- High-level static primitives:
File(ReadAllText,WriteAllText,AppendAllText,Exists,Delete) andDirectory(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.
- High-level static primitives:
๐ Console & Stream Redirection (
System::Console):- Rich console text & background color controls (
SetForegroundColor,SetBackgroundColor,ResetColor). - Full stream redirection via
SetOut(),SetError(), andSetIn()acceptingSmartPointer<TextWriter>andSmartPointer<TextReader>.
- Rich console text & background color controls (
๐ฒ 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:
ConsoleLoggerProviderandFileLoggerProviderwith automatic relative path resolution & recursive parent directory creation. LogManager: Category logger caching factory (GetLogger("Category"),GetLogger<T>(),GetConsoleLogger,GetFileLogger).LoggerTextWriter: High-performance stream redirector bridgingTextWriteroutput intoLogManager.
- Structured & Plaintext logging (
๐งต Multi-Threading & Process Management (
System::Threading/System::Diagnostics):- Thread lifecycle (
Thread), high-throughputThreadPool, and task parallelism (Task,Task<T>). - Synchronization primitives:
Mutex,AutoResetEvent,ManualResetEvent,EventWaitHandle,CriticalSection,ReaderWriterLockSlim. - Process orchestration & telemetry:
Process,ProcessStartInfo, and progressive streaming viaProcessStreamer/ProcessStreamOptions.
- Thread lifecycle (
๐ 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:
SslStreambacked by OpenSSL. - Embedded Web Server & Hosting:
WebAppServerandHostBuilderfor serving static Web UI files and REST API controllers.
- Low-level socket abstractions (
๐ Dependency Injection (
Extensions::DependencyInjection):- Full-featured DI container (
ServiceCollection,ServiceProvider,ServiceDescriptor). - Lifetimes:
Transient,Scoped,Singleton.
- Full-featured DI container (
๐ Security & Principal (
System::Security::Principal):UserPrincipalandWindowsIdentityfor cross-platform OS user enumeration and privilege inspection.
โก Database Data Access (
System::Data):- Abstract ADO.NET-style data provider interfaces (
IDbConnection,IDbCommand,IDataReader,IDataParameterCollection).
- Abstract ADO.NET-style data provider interfaces (
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.dllfor x64, andlibssl-4.dll,libcrypto-4.dllfor 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 symlinkslibssl.so,libcrypto.so) underruntimes/linux-x64/native/which are automatically copied to output directories via MSBuild.targets. Pre-compiled libraries and headers are also provided inexternal/openssl-4.0.1/linux-x64/.
- Windows: The NuGet package bundles pre-built OpenSSL runtime binaries (
Installation โฌ๏ธ
Clone the repository:
git clone https://github.com/sudheeshps/DotNetDupe.git cd DotNetDupeBuild the solution and generate NuGet package: Run the automated build script from PowerShell:
.\BuildAndPack.ps1This 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 thenuget_packagesdirectory.Add local NuGet package source: To use the locally generated NuGet package, add the
nuget_packagesdirectory as a local NuGet source:nuget sources Add -Name "DotNetDupeLocal" -Source "D:\Personal\Projects\C++\DotNetDupe\nuget_packages"(Replace
D:\Personal\Projects\C++\DotNetDupewith your actual solution root path.)Install the NuGet package in your project: In your C++ project, you can now install the
DotNetDupepackage 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.)Integrate into your project: Once installed, ensure your project's
.vcxprojfile is configured to link against theDotNetDupe.liband include its headers. The NuGet package's.targetsfile 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 toDotNetDupe.dllat build time. - Linux: Dynamic OpenSSL 4.0.1 dependencies (
libssl.so.4&libcrypto.so.4) are packaged directly inside the NuGet package and deployed alongsidelibDotNetDupe.soat 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, andSystem::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)
- Add the local
nuget_packagesfolder as a NuGet Package Source:nuget sources Add -Name "DotNetDupeLocal" -Source "D:\Personal\Projects\C++\DotNetDupe\nuget_packages" - In Visual Studio, right-click your project โ Manage NuGet Packages โ Select
DotNetDupeLocalโ InstallDotNetDupe.
C. Consuming NuGet Package on Linux / CMake (WSL)
- 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 - Configure CMake pointing
NUGET_PATHto 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:
- Unique Mode (Default): Zero-overhead, move-only RAII ownership equivalent to
std::unique_ptr. - Shared Mode: Thread-safe atomic reference-counted ownership equivalent to
std::shared_ptr. - Hungarian Naming Standard: Per Quality Gate 11, all
SmartPointervariables and parameters strictly adhere to thep/sp/m_p/s_pHungarian 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 atomicTryAdd(),GetOrAdd(), andAddOrUpdate().BlockingCollection<T>: Provides bounded capacity and blockingTake()/Add()across worker threads.ConcurrentQueue<T>,ConcurrentStack<T>,ConcurrentBag<T>: Thread-safe producer/consumer collections implementingIProducerConsumerCollection<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
- Declare your data structure.
- Specialize the
JsonConverter<T>for the structure to enable automatic serialization and deserialization. - Inherit from
ControllerBaseand define your action methods. - Bind routes using
ControllerRouteBuilderand 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);
}
}
Option B: Strongly-Typed Client (RestClient<T>) - Recommended
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.
Recommended Usage Patterns
- 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 theDOTNETDUPE_USE_SQLITEflag defined.
- In-Memory Emulation (Default): Use
- Always Parameterize Queries: Use
AddWithValueparameters to protect queries against parsing issues and SQL syntax injections. - 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
mainand 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 ๐
- Online Reports:
- Live Documentation Portal: https://sudheeshps.github.io/dotnetdupe/
- Local Generation: Run
powershell .\scripts\Generate-CoverageReport.ps1to execute tests under OpenCppCoverage and refresh theCodeCoverage/folder.
How to Release
- Update the version in
DotNetDupe.nuspec. - Commit and push the changes.
- Create and push a new tag:
Note: Requiresgit tag v1.0.0 git push origin v1.0.0NUGET_API_KEYto 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(), andGetAvailableFreeSpace().
- Added full support for querying drive metrics, volume labels, drive formats (NTFS, FAT32, ext4), total drive capacity, and available/total free space via
- Recursive Directory Traversal (
System::IO::Directory&SearchOption):- Introduced
SearchOptionenumeration (SearchOption::TopDirectoryOnlyandSearchOption::AllDirectories). - Added recursive directory searching overloads to
Directory::GetFiles,Directory::GetDirectories, andDirectory::GetFileSystemEntrieswith permission-resilient folder iteration.
- Introduced
- 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(), andSeek64().
- Upgraded core stream architecture with 64-bit positioning (
- 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
Taskinstances concurrently.
- Added barrier synchronization to wait on collections or arrays of asynchronous
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.targetsto automatically link and stage native OpenSSL libraries (-lssl -lcrypto).
- Bundled pre-built Linux native shared library (
- 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).
- Bundled native OpenSSL 4.0.1 binaries for Linux (
- 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, andTan. - Added statistical operations and financial time-series moving window indicators:
Mean,Variance,StandardDeviation(StdDev),MovingAverage,MovingAverageSeries,ExponentialMovingAverage, andExponentialMovingAverageSeries.
- Implemented IEEE 754 arithmetic and transcendental methods:
- 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, andDateTime. - Added
JsonElementproperty helpers:HasProperty,GetProperty,GetPropertyString,GetPropertyInt32,GetPropertyDouble,GetPropertyAs<T>, andDeserialize<T>.
- Added strongly-typed generic serialization and deserialization via compile-time SFINAE DTO mapping (
v5.0.2 - 2026-09-29
- Concurrent Collections Interface Hierarchy Retrofit:
- Retrofitted
ConcurrentQueue<T>,ConcurrentStack<T>,ConcurrentBag<T>,BlockingCollection<T>, andConcurrentDictionary<TKey, TValue>to inherit generic base collection interfaces (IReadOnlyCollection<T>,IEnumerable<T>,IDictionary<TKey, TValue>). - Introduced
IProducerConsumerCollection<T>base interface.
- Retrofitted
- 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.natvisvisualizers for concurrent containers. - Added dedicated Smart Pointers and Collections documentation sections with compile-ready code snippets to
README.md.
- Updated
v5.0.1 - 2026-09-29
- LINQ Documentation & Guide:
- Added dedicated Language Integrated Query (LINQ) section to
README.mdwith practical code examples. - Updated repository Table of Contents and navigation anchors.
- Added dedicated Language Integrated Query (LINQ) section to
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, andReverse. - Added numeric aggregations and quantifiers:
Any,All,Contains,First,Single,ElementAt,Count,Sum,Min,Max,Average, andAggregate. - Added sequence generators:
RangeandRepeat. - Added collection materialization:
ToList,ToArray,ToDictionary, andToHashSet. - Supported standard C++ range-based
forloops across all queryable sequences.
- Major milestone release introducing zero-STL-allocation LINQ query operators:
- 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
BinaryReaderandBinaryWriterwith configurable endianness and stream seeking support.
- Added
- String Enhancements:
- Added
GetChars()method toDotNetDupe::System::String.
- Added
- Smart Pointer Safety:
- Added safe handling for
thissmart pointer patterns.
- Added safe handling for
- 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.
- Introduced idiomatic multicast delegate event model (
- Native Process Discovery (
System::Diagnostics::Process):- Added ultra-fast process discovery matching .NET BCL:
Process::GetProcesses(),Process::GetProcessById(), andProcess::GetProcessesByName().
- Added ultra-fast process discovery matching .NET BCL:
- On-Demand Process Enrichment:
- Added
SystemMetrics::EnrichProcessInfo()for detailed per-process CPU, memory, and handle telemetry.
- Added
- Version String Parsing:
- Added strict, .NET-compliant
Version::ParseandVersion::TryParsesupporting 2, 3, and 4-component versions with full error validation.
- Added strict, .NET-compliant
- Event Modernization:
- Modernized
FileDownloaderandProcessStreamerto typed multicastEventHandlercallbacks.
- Modernized
v4.0.2 - 2026-08-19
- Observable Process Streaming (
ProcessStreamer):- Added progressive two-tier process discovery and telemetry streaming events.
- Network & WebSocket Hardening:
- Improved
WebSocketExceptionerror handling and connection teardown.
- Improved
- 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.
- Resolved event tracking issue in
- 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.
- Major architectural refactoring eliminating STL types (
- 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>, andLinkedList<T>.
- Added pure library implementations for
- Thread-Safe Concurrent Collections:
- Added lock-free and fine-grained concurrent collections:
ConcurrentDictionary,ConcurrentQueue,ConcurrentStack,ConcurrentBag, andBlockingCollection.
- Added lock-free and fine-grained concurrent collections:
- Console Stream Redirection:
- Added standard stream redirection via
Console::SetOut,Console::SetError, andConsole::SetInusingSmartPointer.
- Added standard stream redirection via
- Logging Subsystem:
- Added
LoggerTextWriterstream redirector and globalLogManagercategory caching.
- Added
- Resilient File I/O:
- Added
FileDownloaderutility with prompt file handle cleanup. - Added recursive
Directory::CreateDirectoryoverload.
- Added
- Dependency Injection:
- Improved
ServiceCollectionDI container with refined lifetime management.
- Improved
- Debugger Natvis Visualizer:
- Introduced
DotNetDupe.natvisvisualizer for inspecting Pimpl internal types in Visual Studio.
- Introduced
- 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.ps1static analysis validation in CI/CD pipeline. - Enforced zero compiler warnings (
/WXon MSVC,-Werroron GCC).
- Added automated
- 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.
- Eliminated raw pointer usage in favor of
- 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.
- Added embedded web server hosting static files (
- Hardware Telemetry (
SystemMetrics):- Added real-time CPU, memory, disk I/O, and network bandwidth telemetry.
- Session Enumeration:
- Added
TerminalSessionandActiveUserSessionto enumerate active, disconnected, and remote desktop user sessions.
- Added
- Named Synchronization:
- Added cross-process named support for mutexes and synchronization events.
v3.0.3 - 2026-08-05
- Documentation Refinements:
- Minor updates to
README.mdand WSL setup guidelines.
- Minor updates to
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
WebApplicationhost andRestClientsupporting 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.
- Introduced
- 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
Interlockedatomic operations.
- Threading enhancements and corrected documentation for
v2.0.0 - 2026-05-20
- Threading & Synchronization (
System::Threading):- Introduced
Thread,ThreadPool,Mutex,AutoResetEvent,ManualResetEvent,Monitor,Interlocked, andSemaphore.
- Introduced
- Text I/O Streams (
System::IO):- Added
TextWriter,TextReader,StringWriter, andStringReader.
- Added
- Time Zone Support (
System):- Added
TimeZoneandTimeZoneInfoclasses.
- Added
- Unit Testing:
- Added unit test suites and sample code in
DotNetDupeDemofor threading and synchronization.
- Added unit test suites and sample code in
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, andMath. - Stream and file I/O:
Stream,FileStream,MemoryStream,File, andPath.
- Foundational types:
- Build Integration:
- Shipped MSBuild
.targetsand platform toolset v143 support for seamless Visual Studio integration.
- Shipped MSBuild
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| native | native is compatible. |
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 |
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.