SGU.Tools_Extensions 2.8.1

dotnet add package SGU.Tools_Extensions --version 2.8.1
                    
NuGet\Install-Package SGU.Tools_Extensions -Version 2.8.1
                    
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="SGU.Tools_Extensions" Version="2.8.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SGU.Tools_Extensions" Version="2.8.1" />
                    
Directory.Packages.props
<PackageReference Include="SGU.Tools_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 SGU.Tools_Extensions --version 2.8.1
                    
#r "nuget: SGU.Tools_Extensions, 2.8.1"
                    
#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 SGU.Tools_Extensions@2.8.1
                    
#: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=SGU.Tools_Extensions&version=2.8.1
                    
Install as a Cake Addin
#tool nuget:?package=SGU.Tools_Extensions&version=2.8.1
                    
Install as a Cake Tool

SGU.Tools_Extensions

Buy Me a Coffee

A comprehensive collection of 90+ .NET extension methods providing utility functions for strings, data conversion, compression, JSON serialization, collections, dates, and much more.

NuGet Version

Features

  • String Extensions: Whitespace normalization, validation, numeric stripping, Base64 encoding
  • DateTime Extensions: Business day calculations, age computation, Unix timestamps, friendly time strings ✨ NEW
  • Collection Extensions: Null-safe operations, chunking, joining, LINQ enhancements ✨ NEW
  • Data Conversion: Safe parsing to int, decimal with default values
  • Compression: GZip string compression and decompression with Base64 encoding
  • JSON Serialization: Multiple serialization options (compact, indented, custom)
  • DataTable Extensions: Convert collections to DataTable, export to Excel/HTML
  • Hash & Cryptography: SHA-512 hashing for strings, files, and streams
  • Time Conversion: Convert between milliseconds, seconds, and minutes with formatting
  • Dictionary Extensions: GetOrDefault, Merge, AddOrUpdate, ToQueryString ✨ NEW
  • Stream Extensions: ToByteArray, SaveToFile, ReadToString conversions ✨ NEW
  • Enum Extensions: Description attributes, safe parsing, get all values ✨ NEW
  • Numeric Range Extensions: Range checks, clamping, tolerance, percentages ✨ NEW
  • Validation: Email validation, JSON validation, numeric type checking
  • And much more!

What's New in v2.8.1 ✨

Major Update: 46 new extension methods added across 8 new categories!

  • DateTime Extensions - Business days, age calculation, Unix timestamps, friendly strings
  • Collection Extensions - LINQ enhancements, chunking, null-safe operations
  • Dictionary Extensions - GetOrDefault, Merge, AddOrUpdate, ToQueryString
  • Stream & Byte Extensions - Stream conversions, file operations, Base64 encoding
  • Enum Extensions - Description attributes, safe parsing
  • Numeric Range Extensions - Range checks, clamping, percentages
  • Enhanced StringBuilder - Conditional append methods

See NEW_EXTENSIONS.md for detailed documentation and examples.

Installation

Install via NuGet Package Manager Console:

Install-Package SGU.Tools_Extensions

Or via .NET CLI:

dotnet add package SGU.Tools_Extensions

Usage

String Extensions

using SGU.Tools;

// Normalize whitespace
string messy = "  Hello    World\n\nTest  ";
string clean = messy.TrimAndReduce();
// clean = "Hello World Test"

// Strip to numeric value
string price = "$1,234.56";
string numeric = price.StripToNumber();
// numeric = "1234.56"

// Validate email
string email = "user@example.com";
bool isValid = email.IsValidEmail();
// isValid = true

// Count occurrences
string text = "hello world, hello universe";
int count = text.CountOccurrences("hello");
// count = 2

Data Conversion

// Safe string to int conversion
string quantity = "1,234";
int value = quantity.ToInt32();
// value = 1234

// Safe string to decimal conversion
string amount = "$99.99";
decimal price = amount.ToDecimal();
// price = 99.99

// Time conversions
int minutes = 5;
double milliseconds = minutes.MinToMs();
// milliseconds = 300000

int ms = 90000;
string timeStr = ms.ToTime();
// timeStr = "00:01:30"

Compression

// Compress string
string largeText = "This is a long string...";
string compressed = largeText.CompressString();

// Decompress
string original = compressed.DecompressString();

JSON Serialization

var person = new Person { Name = "John", Age = 30 };

// Compact JSON
string compact = person.ToJson();
// compact = "{\"Name\":\"John\",\"Age\":30}"

// Indented JSON
string readable = person.ToJsonIndented();
// readable = 
// {
//   "Name": "John",
//   "Age": 30
// }

// Deserialize
var obj = jsonString.To<Person>();

DataTable Extensions

// Convert list to DataTable
var employees = GetEmployees();
DataTable dt = employees.ToDataTable();

// Export to Excel
using (var stream = dt.ToExcel("Employees"))
{
    stream.Position = 0;
    File.WriteAllBytes("employees.xlsx", stream.ToArray());
}

// Export to HTML
string html = dt.ToHTMLTable(Page: true);

// Check if has rows
if (dt.HasRows())
{
    ProcessData(dt);
}

Hashing

// Hash string
string password = "MyPassword123";
string hash = password.GetHashString();

// Hash file
var fileInfo = new FileInfo(@"C:\temp\document.pdf");
string fileHash = fileInfo.GetHashString();

// Hash with salt
string saltedHash = password.GetHashString("MySalt");

Validation

// Validate JSON
string json = "{\"name\":\"test\"}";
bool isValid = json.IsValidJson<MyClass>();

// Check numeric type
object value = 42;
bool isNumeric = value.IsNumericType();
// isNumeric = true

// Check even/odd
int number = 7;
bool isOdd = number.IsOdd();
// isOdd = true

DateTime Extensions ✨ NEW

// Business day calculations
var friday = new DateTime(2025, 1, 10);
var monday = friday.AddBusinessDays(1);  // Skips weekend

// Check day type
bool isWeekend = someDate.IsWeekend();
bool isBusinessDay = someDate.IsBusinessDay();

// Day boundaries
var startOfDay = DateTime.Now.StartOfDay();  // 00:00:00
var endOfDay = DateTime.Now.EndOfDay();      // 23:59:59.999

// Age calculations
var birthDate = new DateTime(1990, 6, 15);
int age = birthDate.Age();

// Unix timestamps
long timestamp = DateTime.Now.ToUnixTimestamp();
DateTime date = timestamp.FromUnixTimestamp();

// Friendly time strings
string friendly = someDate.ToFriendlyString();
// "just now", "2 hours ago", "yesterday", "in 3 days"

Collection Extensions ✨ NEW

// Null-safe operations
bool isEmpty = list.IsNullOrEmpty();
var safeList = nullableList.OrEmpty();

// Join to string
var csv = items.JoinString(", ");

// Split into chunks
var chunks = largeList.Chunk(100);

// Safe first element
var first = list.SafeFirst(defaultValue);

// ForEach with action
items.ForEach(item => Console.WriteLine(item));

// Distinct by property
var uniquePeople = people.DistinctBy(p => p.Email);

Dictionary Extensions ✨ NEW

// Get with default
int value = dict.GetOrDefault("key", 0);

// Add or update
dict.AddOrUpdate("key", 42);

// Merge dictionaries
var merged = dict1.Merge(dict2);

// To query string
var queryParams = new Dictionary<string, string>
{
    { "name", "John" },
    { "age", "30" }
};
string query = queryParams.ToQueryString();
// "name=John&age=30"

Stream & Byte Extensions ✨ NEW

// Stream operations
byte[] bytes = stream.ToByteArray();
string text = stream.ReadToString();
stream.SaveToFile("output.dat");

// Byte array operations
string base64 = bytes.ToBase64();
byte[] decoded = base64String.FromBase64();

// Format file sizes
long size = 1536000;
string formatted = size.ToFormattedSize();  // "1.46 MB"

Enum Extensions ✨ NEW

public enum Status
{
    [Description("Active User")]
    Active,
    Inactive
}

// Get description
string desc = Status.Active.GetDescription();

// Parse with default
var status = "Active".ParseEnum(Status.Inactive);

// Get all values
Status[] all = Extensions.GetEnumValues<Status>();

Numeric Range Extensions ✨ NEW

// Range checks
bool inRange = value.InRange(1, 100);

// Clamping
int clamped = value.Clamp(0, 100);

// Tolerance checking
bool close = value.IsInTolerance(target, 0.001);

// Percentages
double percent = value.PercentageOf(total);

Extension Methods Reference

String Extensions

  • ByteToString() - Convert byte array to hex string
  • CompressString() - GZip compress string to Base64
  • DecompressString() - Decompress GZip Base64 string
  • ConvertWhitespacesToSingleSpaces() - Normalize whitespace
  • CountOccurrences() - Count pattern occurrences
  • IsValidEmail() - Validate email with IDN support
  • IsValidEmailAddress() - Validate email with DataAnnotations
  • IsValidJson<T>() - Validate and test JSON deserialization
  • RemoveWhitespace() - Reduce consecutive whitespace
  • StripToNumber() - Extract numeric characters
  • ToDBString() - Escape single quotes for SQL
  • ToDecimal() - Safe decimal conversion
  • ToInt32() - Safe integer conversion
  • To<T>() - Deserialize JSON to type
  • ToJson() - Serialize to compact JSON
  • ToJsonIndented() - Serialize to formatted JSON
  • TrimAndReduce() - Trim and normalize whitespace
  • TrueFalseValue() - Convert "true"/"false" to tri-state

DateTime Extensions ✨ NEW

  • StartOfDay() - Get midnight of the date
  • EndOfDay() - Get 23:59:59.999 of the date
  • IsWeekend() - Check if Saturday or Sunday
  • IsBusinessDay() - Check if Monday-Friday
  • AddBusinessDays() - Add business days, skipping weekends
  • Age() - Calculate age from birth date
  • AgeAt() - Calculate age as of specific date
  • ToUnixTimestamp() - Convert to Unix timestamp
  • FromUnixTimestamp() - Convert from Unix timestamp
  • ToFriendlyString() - Get relative time string ("2 hours ago")

Collection Extensions ✨ NEW

  • IsNullOrEmpty() - Check if collection is null or empty
  • OrEmpty() - Return empty collection if null
  • JoinString() - Join elements with separator
  • Chunk() - Split into chunks of specified size
  • SafeFirst() - Get first element or default value
  • ForEach() - Execute action for each element
  • DistinctBy() - Get distinct elements by key selector

StringBuilder Extensions

  • ClearAppend() - Clear and append string
  • ClearAppendLine() - Clear and append with newline
  • AppendIf() - Append only if condition is true ✨ NEW
  • AppendLineIf() - Append line only if condition is true ✨ NEW
  • AppendJoin() - Append collection with separator ✨ NEW

DataTable Extensions

  • HasRows() - Check if DataTable has rows
  • ToExcel() - Export to Excel (.xlsx)
  • ToHTMLTable() - Convert to HTML table
  • ToDataTable<T>() - Convert IList<T> to DataTable

DataRow Extensions

  • GetInt() - Extract integer from DataRow field

Dictionary Extensions ✨ NEW

  • GetOrDefault() - Get value or return default
  • AddOrUpdate() - Add or update key-value pair
  • Merge() - Merge two dictionaries
  • ToQueryString() - Convert to URL query string format

Stream Extensions ✨ NEW

  • ToByteArray() - Convert stream to byte array
  • ReadToString() - Read stream as string
  • SaveToFile() - Save stream to file path
  • Reset() - Reset stream position to beginning

Byte Array Extensions ✨ NEW

  • ToBase64() - Convert byte array to Base64 string
  • FromBase64() - Convert Base64 string to byte array
  • ToStream() - Convert byte array to stream
  • ToMemoryStream() - Convert byte array to MemoryStream
  • ToFormattedSize() - Format bytes as human-readable size

Enum Extensions ✨ NEW

  • GetDescription() - Get Description attribute value
  • ParseEnum<T>() - Parse string to enum with default
  • GetEnumValues<T>() - Get all enum values as array
  • GetEnumValuesEnumerable<T>() - Get all values as IEnumerable

Hashing Extensions

  • GetHashString() - SHA-512 hash (7 overloads for string, byte[], Stream, FileInfo, etc.)

Time Conversion Extensions

  • MinToMs() - Minutes to milliseconds
  • MinToSec() - Minutes to seconds
  • MsToMin() - Milliseconds to minutes
  • MsToSec() - Milliseconds to seconds
  • ToTime() - Milliseconds to HH:MM:SS format

Numeric Extensions

  • IsEven() - Check if integer is even
  • IsOdd() - Check if integer is odd
  • IsNumericType() - Check if type is numeric
  • NegativeNumber() - Convert to negative value

Numeric Range Extensions ✨ NEW

  • InRange() - Check if value is in range (int, double, decimal)
  • Clamp() - Constrain value to range (int, double)
  • RoundTo() - Round decimal with rounding mode
  • IsInTolerance() - Check if within tolerance
  • PercentageOf() - Calculate percentage (double, decimal)

Stopwatch Extensions

  • ResetStart() - Reset and start stopwatch

Type Validation Extensions

  • IsNumericType() - Check if object/type is numeric

Platform Support

  • .NET Framework 4.8
  • .NET 8.0 (Windows)
  • .NET 9.0 (Windows)
  • .NET 10.0 (Windows)

Statistics

  • 90+ Extension Methods across 15+ categories
  • 178 Unit Tests with 100% pass rate
  • 100% Test Coverage on all methods
  • Fully Documented with XML comments and examples

Dependencies

  • Newtonsoft.Json - JSON serialization
  • ClosedXML - Excel file generation
  • System.Data.DataSetExtensions - DataTable extensions

Issue Reporting

If you encounter any issues or have feature requests, please report them on the GitHub Issues.

If you find this library helpful, consider supporting development:

Buy Me a Coffee

License

Licensed under the MIT License.

Author

Solutions Group Unlimited, LLC

Copyright © 2025 Solutions Group Unlimited, LLC. All rights reserved.

Product Compatible and additional computed target framework versions.
.NET net8.0-windows7.0 is compatible.  net9.0-windows was computed.  net9.0-windows7.0 is compatible.  net10.0-windows was computed.  net10.0-windows7.0 is compatible.  net10.0-windows10.0.26100 is compatible. 
.NET Framework net48 is compatible.  net481 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
2.8.1 87 1/14/2026
2.7.12 104 1/2/2026
2.7.11 99 12/30/2025
2.7.7 88 12/30/2025