PowerCSharp


Enhanced C# extension methods and utilities for .NET developers
🌐 Official website: https://powercsharp.net/

PowerCSharp is a comprehensive library of extension methods, utilities, and helper classes designed to enhance your C# development experience. Built by a senior C# architect with 20+ years of experience, this library provides practical, well-tested solutions for common programming challenges.
PowerCSharp v2.0.0 — Features Framework Release
What’s New in v2.0.0:
- Features Framework: Brand-new
PowerCSharp.Features engine — hybrid auto-scan + explicit module discovery, composite flag resolution (config → env vars → overrides), DI orchestration, opt-in diagnostics endpoint
- Built-in Features:
PowerCSharp.BuiltInFeatures bundle — runtime-flag-toggled ASP.NET Core capabilities (CORS), toggled via PowerFeatures:<Key>:Enabled
- Cache Feature Family:
PowerCSharp.Feature.Cache (module + options), PowerCSharp.Feature.Cache.Abstractions (contracts + NoOp, netstandard2.0 + net8.0), PowerCSharp.Feature.Cache.BitFaster (BitFaster-backed LRU), PowerCSharp.Feature.Cache.Disk (disk-backed LRU with cross-process locking)
- Sanitization Feature Family:
PowerCSharp.Feature.Sanitization.Abstractions (engine + contracts + NoOp, netstandard2.0 + net8.0) and PowerCSharp.Feature.Sanitization (module + options) — log injection (CWE-117), file-path traversal (CWE-22), sensitive-data masking (CWE-200), and regex-injection/ReDoS validation (CWE-400/CWE-730)
- Operational Package Family:
PowerCSharp.Operational.Abstractions (contracts + NoOp, netstandard2.0 + net8.0) and PowerCSharp.Operational (net8.0) — cross-cutting issue capture, in-app diagnostics, structured logging, disk event-log writing, and HTTP retry/circuit-breaker resilience. Optional PowerCSharp.Features integration; usable standalone.
- EditorConfig: Comprehensive coding standards applied across the entire codebase
- Directory Extensions:
TrySafeDelete and related safe I/O helpers
- Code Quality: Nullable annotations, member ordering, and namespace cleanup throughout
📦 Packages
PowerCSharp is organized into focused, independently versioned packages.
Core Libraries (v2.0.0)
- PowerCSharp.Core - Core foundation and base classes, including centralized interfaces and models
- PowerCSharp.Extensions - Cross-platform extension methods for collections, HTTP, LINQ, JSON, XML, objects, types, streams, and strings
- PowerCSharp.Extensions.AspNetCore - ASP.NET Core specific extensions for configuration and web utilities
- PowerCSharp.Utilities - Utility classes for validation, file operations, and mathematics
- PowerCSharp.Helpers - Specialized helpers for JSON, cryptography, and environment operations
- PowerCSharp.Compatibility - .NET Framework compatibility layer (
net462/net472/net48)
Features Framework (v1.0.0)
- PowerCSharp.Features.Abstractions - Contracts only:
IFeatureModule, IFeatureFlagProvider, FeatureOptionsBase, FeatureDescriptor. Zero third-party dependencies.
- PowerCSharp.Features - The engine: assembly discovery, composite flag resolution, DI orchestration, feature registry, and diagnostics. Entry points:
AddPowerFeatures() / UsePowerFeatures().
- PowerCSharp.BuiltInFeatures - Bundle of lightweight, runtime-toggled ASP.NET Core capabilities (CORS). Toggle via
PowerFeatures:<Key>:Enabled.
Cache Feature Family (v1.3.5)
Sanitization Feature Family (v1.0.0)
- PowerCSharp.Feature.Sanitization.Abstractions - Sanitization engine, contracts, and NoOp safe-off implementation covering log injection, file-path traversal, sensitive-data masking, and regex-injection/ReDoS. Targets
netstandard2.0 + net8.0.
- PowerCSharp.Feature.Sanitization - Sanitization feature module, options, and
AddSanitizationFeature() wiring. No separate provider package — registers the real service directly.
Operational Package Family (v1.0.1)
- PowerCSharp.Operational.Abstractions - Contracts (
IDiagnosticsService, IIssueManager, IEventViewerService), models, enums, and NoOp safe-off implementations. Zero third-party dependencies. Targets netstandard2.0 + net8.0.
- PowerCSharp.Operational - In-app diagnostics, centralized issue/error capture, a custom
ILogger provider, disk event-log writing (NDJSON), and HTTP retry/circuit-breaker resilience (via Polly). Works standalone via AddOperational()/UseOperational(), or through PowerCSharp.Features via the optional OperationalFeatureModule. Targets net8.0 (ASP.NET Core).
🏗️ Architecture
PowerCSharp follows a clean architectural pattern with centralized interfaces in PowerCSharp.Core:
- All interfaces are located in
PowerCSharp.Core.Interfaces namespace
- All models are located in
PowerCSharp.Core.Models namespace
- Clear separation of concerns with proper dependency management
- Consistent namespace organization across the entire ecosystem
- Modular design allowing selective package installation
- Dependency-free core for maximum compatibility
🚀 Installation
Core libraries
dotnet add package PowerCSharp.Core
dotnet add package PowerCSharp.Extensions
dotnet add package PowerCSharp.Extensions.AspNetCore
dotnet add package PowerCSharp.Utilities
dotnet add package PowerCSharp.Helpers
dotnet add package PowerCSharp.Compatibility
Features framework
dotnet add package PowerCSharp.Features.Abstractions
dotnet add package PowerCSharp.Features
dotnet add package PowerCSharp.BuiltInFeatures
Cache feature (pick a provider)
dotnet add package PowerCSharp.Feature.Cache
dotnet add package PowerCSharp.Feature.Cache.BitFaster # in-memory LRU (BitFaster)
dotnet add package PowerCSharp.Feature.Cache.Disk # disk-backed LRU
Sanitization feature
dotnet add package PowerCSharp.Feature.Sanitization.Abstractions # engine — usable standalone, no DI required
dotnet add package PowerCSharp.Feature.Sanitization # module — Features Framework + DI wiring
Operational package family
dotnet add package PowerCSharp.Operational.Abstractions # contracts + NoOp — usable standalone, no DI required
dotnet add package PowerCSharp.Operational # diagnostics, issue capture, logging, event-log writer, retry/circuit-breaker
💡 Usage Examples
String Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
string text = "hello world";
bool isEmpty = text.IsNullOrWhiteSpace(); // false
string title = text.ToTitleCase(); // "Hello World"
string safe = text.SafeSubstring(0, 5); // "hello"
// Additional string utilities
string camel = "HelloWorld".ToCamelCase(); // "helloWorld"
string firstLower = text.FirstCharToLowerCase(); // "hello world"
string mid = text.Mid(6); // "world"
string normalized = "User Name".NormalizeKey(); // "userName"
string ascii = "café".AsAscii(); // "caf"
bool isValid = "https://example.com".IsValidUrl(); // true
Collection Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
var numbers = new List<int> { 1, 2, 3, 4, 5 };
bool isEmpty = numbers.IsNullOrEmpty(); // false
var first = numbers.FirstOrDefaultSafe(-1); // 1
var page = numbers.Page(1, 2); // [1, 2]
// New collection utilities
var list = new List<string> { "keep", "remove", "keep", "remove" };
int removed = list.RemoveAll(x => x == "remove"); // 2
DateTime Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
var date = DateTime.Now;
int age = date.GetAge();
bool isWeekend = date.IsWeekend();
var firstDay = date.FirstDayOfMonth();
var lastDay = date.LastDayOfMonth();
HTTP & Network Extensions (PowerCSharp.Extensions.AspNetCore)
using PowerCSharp.Extensions.AspNetCore;
using System.Net;
// HTTP Status Code utilities
HttpStatusCode status = HttpStatusCode.OK;
bool success = status.IsSuccessful(); // true
bool clientError = status.IsClientError(); // false
bool serverError = status.IsServerError(); // false
bool isRedirect = status.IsRedirect(); // false
// URI manipulation
Uri uri = new Uri("https://example.com");
Uri withParam = uri.AddParameter("search", "test"); // https://example.com?search=test
// HTTP Request cloning
using var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com");
var clonedRequest = request.Clone();
var clonedAsync = await request.CloneAsync();
Configuration Extensions (PowerCSharp.Extensions.AspNetCore)
using PowerCSharp.Extensions.AspNetCore;
using Microsoft.Extensions.Configuration;
var configuration = new ConfigurationBuilder().Build();
var options = configuration.GetOptions<MyAppOptions>("MyApp"); // Reads from "MyApp" section
Features Framework (PowerCSharp.Features + PowerCSharp.BuiltInFeatures)
// Program.cs
builder.Services.AddPowerFeatures(builder.Configuration, options =>
{
options.AddBuiltInFeatures(); // opt-in the built-in bundle (CORS, etc.)
options.ScanAssemblies( // opt-in pluggable feature assemblies
typeof(CacheFeatureModule).Assembly);
options.Override("Cache", true); // optional code-level override
options.EnableDiagnosticsEndpoint(); // GET /power-features — off by default
});
var app = builder.Build();
app.UsePowerFeatures();
// appsettings.json
{
"PowerFeatures": {
"Cors": { "Enabled": true, "AllowedOrigins": [ "https://example.com" ] },
"Cache": { "Enabled": true, "Provider": "BitFaster", "Capacity": 1000 }
}
}
Flag resolution order (highest precedence first): explicit code override → custom IFeatureFlagProvider → environment variables (POWERFEATURES__<KEY>__ENABLED) → appsettings → feature default.
Cache Feature (PowerCSharp.Feature.Cache + provider)
// Resolves to the active provider (BitFaster or Disk) or NoOp if disabled.
var cache = app.Services.GetRequiredService<ICacheService>();
await cache.SetAsync("key", myObject, TimeSpan.FromMinutes(5));
var result = await cache.GetAsync<MyObject>("key");
if (result.Hit)
Console.WriteLine(result.Value);
Sanitization Feature (PowerCSharp.Feature.Sanitization.Abstractions)
using PowerCSharp.Feature.Sanitization.Abstractions;
// Usable standalone — no DI or feature registration required.
string safeForLog = untrustedInput.SanitizeForLog(); // CWE-117 log injection
string safeForPath = untrustedSegment.SanitizeForFilePath(); // CWE-22 path traversal (throws if rejected)
string masked = payload.SanitizeForSensitiveData(); // CWE-200 sensitive-data masking
string safePattern = untrustedPattern.SanitizeForRegexInjection(); // CWE-400/CWE-730 ReDoS validation
// Or resolve the DI-facing service once PowerCSharp.Feature.Sanitization is registered:
var sanitizer = app.Services.GetRequiredService<ISanitizationService>();
var result = sanitizer.SanitizeForLogInjection(untrustedInput);
Operational (PowerCSharp.Operational)
// Program.cs
builder.Services.AddOperational(builder.Configuration);
// ...
app.UseOperational();
using PowerCSharp.Operational.Abstractions;
public class OrderController(IDiagnosticsService diagnostics, IIssueManager issues)
{
public IActionResult Get(int id)
{
diagnostics.AddTrace($"Looking up order {id}");
try
{
return Ok(GetOrder(id));
}
catch (Exception ex)
{
issues.CaptureException(ex, new { orderId = id });
throw;
}
}
}
Enable per-request diagnostics with the debug: true header (add debugVerbose: true to disable auto-obfuscation, traceLevel: <0-6> to filter, eventLog: true to also write to disk). Disabled or unconfigured, PowerCSharp.Operational.Abstractions NoOp floors keep every call site safe.
LINQ & Dynamic Query Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
// Dynamic expression parsing
string expression = "Age > 18 && Name.Contains('John')";
var predicate = expression.GetExpressionDelegate<Person>();
// Dynamic ordering
string orderExpression = "Name DESC, Age ASC";
var orderDelegates = orderExpression.GetOrderDelegates<Person>();
// Dynamic filtering and ordering
var filterProvider = new DynamicFilterProvider<Person>();
var orderProvider = new DynamicOrderProvider<Person>();
var filtered = people.Filter(filterProvider);
var ordered = people.Order(orderProvider);
JSON & XML Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
using System.Text.Json;
// JSON element access
JsonElement element = JsonDocument.Parse("{\"name\":\"John\"}").RootElement;
var name = element.Get("name"); // JsonElement with value "John"
var firstItem = element.Get(0); // For arrays
// Case-insensitive JSON access
bool found = element.TryGetPropertyCaseInsensitive("NAME", out var value);
// XML flattening
using System.Xml.Linq;
XElement xml = XElement.Parse("<root><child>value</child></root>");
var dict = xml.Flatten(); // Dictionary with XML structure
Object & Type Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
// Object utilities
string text = "test";
text.ThrowOnNull(); // Throws if null
bool isTrue = "true".TryGetBool(out bool result); // result = true, isTrue = true
bool isFalse = "0".TryGetBool(out result); // result = false, isFalse = true
// Generic operations
var person = new Person { Name = "John", Age = 30 };
var copy = new Person();
person.CopyPropertiesTo(copy); // Copies matching properties
// Type operations
bool isDefault = default(int).IsDefault(); // true
string typeName = typeof(List<string>).GetGenericTypeName(); // "List<String>"
// Concrete type resolution
Type concreteType = typeof(IMyInterface).GetConcreteType();
Stream Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
using var originalStream = new MemoryStream(Encoding.UTF8.GetBytes("test data"));
using var destinationStream = new MemoryStream();
await originalStream.CloneAsync(destinationStream);
// destinationStream now contains the same data as originalStream
Object Hash Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
var person = new { Name = "John", Age = 30, Email = "[email protected]" };
string hash = person.ComputeHash(); // "A1B2C3D4E5F67890" (16-char hex string)
// Handles complex objects with nested properties
var complexObj = new Order
{
Id = 123,
Customer = new Customer { Name = "Alice" },
Items = new List<Item> { new Item { Name = "Product1" } }
};
string orderHash = complexObj.ComputeHash(); // Consistent hash for caching/identification
Secure Path Extensions (PowerCSharp.Extensions)
using PowerCSharp.Extensions;
string basePath = "/var/www/uploads";
string userFile = "../../etc/passwd"; // Malicious attempt
// This will throw SecurityException due to directory traversal attempt
string safePath = PathExtensions.CombineAndValidate(basePath, userFile);
// Safe usage with valid relative paths
string validPath = PathExtensions.CombineAndValidate(basePath, "images/photo.jpg");
// Returns: "/var/www/uploads/images/photo.jpg"
// Multiple path segments
string multiPath = PathExtensions.CombineAndValidate(basePath, "documents", "2023", "report.pdf");
// Returns: "/var/www/uploads/documents/2023/report.pdf"
Validation Utilities (PowerCSharp.Utilities)
using PowerCSharp.Utilities;
bool isValidEmail = ValidationHelper.IsValidEmail("[email protected]");
bool isNumeric = ValidationHelper.IsNumeric("12345");
bool isValidUrl = ValidationHelper.IsValidUrl("https://example.com");
File Utilities (PowerCSharp.Utilities)
using PowerCSharp.Utilities;
string content = FileHelper.SafeReadAllText("file.txt");
bool success = FileHelper.SafeWriteAllText("output.txt", "Hello World");
string size = FileHelper.GetFileSize(1024 * 1024); // "1 MB"
JSON Helpers (PowerCSharp.Helpers)
using PowerCSharp.Helpers;
var obj = new { Name = "John", Age = 30 };
string json = JsonHelper.SafeSerialize(obj);
var deserialized = JsonHelper.SafeDeserialize<MyClass>(json);
string pretty = JsonHelper.PrettyPrint(json);
Crypto Helpers (PowerCSharp.Helpers)
using PowerCSharp.Helpers;
string sha256 = CryptoHelper.ComputeSHA256("password");
string md5 = CryptoHelper.ComputeMD5("data");
string random = CryptoHelper.GenerateRandomString(10);
🎯 Target Frameworks
- Modern .NET: .NET 8.0 — core libraries, Features engine, BuiltInFeatures, Cache, Sanitization, and Operational feature modules
- .NET Standard 2.0 + .NET 8.0:
PowerCSharp.Features.Abstractions, PowerCSharp.Feature.Cache.Abstractions, PowerCSharp.Feature.Cache.BitFaster, PowerCSharp.Feature.Sanitization.Abstractions, PowerCSharp.Operational.Abstractions — usable from .NET Framework and .NET Core
- .NET Framework: 4.6.2, 4.7.2, 4.8 — via
PowerCSharp.Compatibility
- ASP.NET Core: .NET 8.0 —
PowerCSharp.Extensions.AspNetCore, Features engine, BuiltInFeatures, PowerCSharp.Operational
🧪 Testing
All PowerCSharp packages include comprehensive unit tests. Run tests with:
dotnet test
📚 Documentation
Package-Specific Documentation
Core libraries
Features framework
Cache feature family
Sanitization feature family
Operational package family
Detailed API Documentation
Development Documentation
🤝 Contributing
Contributions are welcome! Please read our Contributing Guidelines for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Built with passion by Mario Arce
- Inspired by 20+ years of C# development experience
- Community feedback and contributions
📞 Support
PowerCSharp - Making C# development more powerful, one extension at a time! 🚀
评论