PowerCSharp.Extensions 1.0.0

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

PowerCSharp.Extensions

PowerCSharp Banner

PowerCSharp.Extensions License: MIT NuGet NuGet Downloads

Cross-platform extension methods for .NET developers that enhance productivity and simplify common programming tasks. This package contains over 100 extension methods organized into logical categories, compatible with both modern .NET and .NET Standard 2.0.

Recent Improvements (v0.3.0):

  • Package Separation: ASP.NET Core extensions moved to dedicated package for cleaner dependencies
  • Performance Optimization: Reduced memory allocations and improved execution speed
  • Enhanced Documentation: Better API documentation and practical examples
  • Improved Testing: Expanded unit test coverage for all extension methods

๐Ÿ“ฆ Package Information

  • Package ID: PowerCSharp.Extensions
  • Version: 0.3.0
  • Target Frameworks: .NET 8.0, .NET Standard 2.0
  • Dependencies:
    • PowerCSharp.Core (for shared interfaces)
    • System.Linq.Dynamic.Core v1.7.2 (for dynamic LINQ)
    • Ben.Demystifier v0.4.1 (for enhanced exception demystification)
    • System.Text.Json v10.0.8 (for JSON processing)

Note: ASP.NET Core specific extensions (Configuration, URI manipulation) are now available in the separate PowerCSharp.Extensions.AspNetCore package.

๐Ÿš€ Installation

dotnet add package PowerCSharp.Extensions

๐Ÿ“š Extension Categories

๐Ÿ•’ DateTime Extensions

Enhanced date and time operations for common scenarios.

using PowerCSharp.Extensions;

var date = DateTime.Now;
int age = date.GetAge();                    // Calculate age
bool isWeekend = date.IsWeekend();           // Check if weekend
var firstDay = date.FirstDayOfMonth();       // First day of month
var lastDay = date.LastDayOfMonth();         // Last day of month

๐Ÿ”ค String Extensions

Powerful string manipulation and validation methods.

using PowerCSharp.Extensions;

string text = "hello world";
bool isEmpty = text.IsNullOrWhiteSpace();    // false
string title = text.ToTitleCase();            // "Hello World"
string camel = "HelloWorld".ToCamelCase();    // "helloWorld"
string safe = text.SafeSubstring(0, 5);       // "hello"
bool isValid = "https://example.com".IsValidUrl(); // true

๐Ÿ“ฆ Collection Extensions

Enhanced collection operations for better data manipulation.

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]

// Remove all matching items
var list = new List<string> { "keep", "remove", "keep" };
int removed = list.RemoveAll(x => x == "remove"); // 1

๐Ÿ” LINQ & Dynamic Query Extensions

Advanced LINQ operations with dynamic expression parsing.

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

Simplified JSON and XML document manipulation.

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"
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

Enhanced object manipulation and type operations.

using PowerCSharp.Extensions;

// Object utilities
string text = "test";
text.ThrowOnNull();                           // Throws if null

bool isTrue = "true".TryGetBool(out bool result); // result = 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>"

๐ŸŒŠ Stream Extensions

Asynchronous stream operations and cloning.

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

Generate consistent hash values from objects for caching and identification.

using PowerCSharp.Extensions;

var person = new { Name = "John", Age = 30, Email = "john@example.com" };
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

// Graceful error handling for non-serializable objects
string fallbackHash = problematicObj.ComputeHash(); // Returns fallback hash based on type and error

๐Ÿ›ก๏ธ Secure Path Extensions

CWE-73 compliant path operations with directory traversal protection.

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"

// Security events are automatically logged for monitoring

๐ŸŽฏ Key Features

โœ… Thread Safety

All extension methods are designed to be thread-safe when used with immutable data structures.

โœ… Null Safety

Comprehensive null checking and graceful error handling throughout.

โœ… Performance Optimized

Methods are optimized for performance with minimal allocations and efficient algorithms.

โœ… .NET Standard Compatible

Works with .NET Framework 4.6.1+, .NET Core 2.0+, .NET 5+, and .NET 8.0.

๐Ÿ”— Dependencies

PowerCSharp.Extensions depends on:

  • PowerCSharp.Core - Shared interfaces and base functionality
  • System.Linq.Dynamic.Core - Dynamic LINQ expression parsing
  • Ben.Demystifier - Enhanced exception demystification and stack trace formatting
  • System.Text.Json - JSON processing

For ASP.NET Core specific functionality: Install PowerCSharp.Extensions.AspNetCore for configuration extensions, URI manipulation, and HTTP utilities.

๐Ÿงช Testing

PowerCSharp.Extensions includes comprehensive unit tests. Run tests with:

dotnet test src/PowerCSharp.Extensions.Tests

๐Ÿ“– Documentation

๐Ÿ’ก Usage Examples

Dynamic LINQ Scenario

using PowerCSharp.Extensions;

public class AdvancedDataProcessor
{
    public IEnumerable<User> FilterAndSortUsers(IEnumerable<User> users, string filterExpression, string sortExpression)
    {
        // Dynamic filtering
        if (!string.IsNullOrEmpty(filterExpression))
        {
            var predicate = filterExpression.GetExpressionDelegate<User>();
            users = users.Where(predicate);
        }
        
        // Dynamic sorting
        if (!string.IsNullOrEmpty(sortExpression))
        {
            var orderDelegates = sortExpression.GetOrderDelegates<User>();
            users = users.OrderByMultiple(orderDelegates);
        }
        
        return users;
    }
    
    public void ProcessDynamicQuery(string query)
    {
        // Example: "Age > 25 AND Name.Contains('John') ORDER BY Name DESC, Age ASC"
        var parts = query.Split("ORDER BY", StringSplitOptions.RemoveEmptyEntries);
        var filterPart = parts[0].Trim();
        var sortPart = parts.Length > 1 ? parts[1].Trim() : "Name ASC";
        
        var users = GetUsers();
        var results = FilterAndSortUsers(users, filterPart, sortPart);
        
        foreach (var user in results)
        {
            Console.WriteLine($"{user.Name} ({user.Age})");
        }
    }
    
    private IEnumerable<User> GetUsers() => new List<User>();
}

## ๐Ÿค Contributing

Contributions are welcome! Please read our [Contributing Guidelines](../../CONTRIBUTING.md) for details.

### Development Setup

1. Clone the repository
2. Navigate to PowerCSharp.Extensions project
3. Restore dependencies: `dotnet restore`
4. Run tests: `dotnet test`
5. Make your changes
6. Add tests for new functionality
7. Submit a Pull Request

### Adding New Extensions

When adding new extension methods:

1. **Choose the right category** - Place extensions in the appropriate folder
2. **Follow naming conventions** - Use descriptive, PascalCase method names
3. **Add XML documentation** - Include comprehensive XML docs
4. **Write unit tests** - Cover all scenarios and edge cases
5. **Update documentation** - Add to API documentation

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.

## ๐Ÿ”— Related Packages

- [PowerCSharp.Core](../PowerCSharp.Core/README.md) - Core interfaces and architecture
- [PowerCSharp.Utilities](../PowerCSharp.Utilities/README.md) - Utility classes and helpers
- [PowerCSharp.Helpers](../PowerCSharp.Helpers/README.md) - Specialized helper classes

## ๐Ÿ“ž Support

- ๐Ÿ› [Report Issues](https://github.com/marioarce/PowerCSharp/issues)
- ๐Ÿ’ก [Feature Requests](https://github.com/marioarce/PowerCSharp/discussions)
- ๐Ÿ“ง [Email Support](mailto:support@example.com)

---

**PowerCSharp.Extensions** - Making C# development more productive, one extension at a time! ๐Ÿš€

[โ† Back to Main Documentation](../../README.md)
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 64 6/8/2026
0.3.0 89 6/2/2026
0.2.0 92 6/1/2026
0.1.0 99 5/30/2026