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
<PackageReference Include="SGU.Tools_Extensions" Version="2.8.1" />
<PackageVersion Include="SGU.Tools_Extensions" Version="2.8.1" />
<PackageReference Include="SGU.Tools_Extensions" />
paket add SGU.Tools_Extensions --version 2.8.1
#r "nuget: SGU.Tools_Extensions, 2.8.1"
#:package SGU.Tools_Extensions@2.8.1
#addin nuget:?package=SGU.Tools_Extensions&version=2.8.1
#tool nuget:?package=SGU.Tools_Extensions&version=2.8.1
SGU.Tools_Extensions
A comprehensive collection of 90+ .NET extension methods providing utility functions for strings, data conversion, compression, JSON serialization, collections, dates, and much more.
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 stringCompressString()- GZip compress string to Base64DecompressString()- Decompress GZip Base64 stringConvertWhitespacesToSingleSpaces()- Normalize whitespaceCountOccurrences()- Count pattern occurrencesIsValidEmail()- Validate email with IDN supportIsValidEmailAddress()- Validate email with DataAnnotationsIsValidJson<T>()- Validate and test JSON deserializationRemoveWhitespace()- Reduce consecutive whitespaceStripToNumber()- Extract numeric charactersToDBString()- Escape single quotes for SQLToDecimal()- Safe decimal conversionToInt32()- Safe integer conversionTo<T>()- Deserialize JSON to typeToJson()- Serialize to compact JSONToJsonIndented()- Serialize to formatted JSONTrimAndReduce()- Trim and normalize whitespaceTrueFalseValue()- Convert "true"/"false" to tri-state
DateTime Extensions ✨ NEW
StartOfDay()- Get midnight of the dateEndOfDay()- Get 23:59:59.999 of the dateIsWeekend()- Check if Saturday or SundayIsBusinessDay()- Check if Monday-FridayAddBusinessDays()- Add business days, skipping weekendsAge()- Calculate age from birth dateAgeAt()- Calculate age as of specific dateToUnixTimestamp()- Convert to Unix timestampFromUnixTimestamp()- Convert from Unix timestampToFriendlyString()- Get relative time string ("2 hours ago")
Collection Extensions ✨ NEW
IsNullOrEmpty()- Check if collection is null or emptyOrEmpty()- Return empty collection if nullJoinString()- Join elements with separatorChunk()- Split into chunks of specified sizeSafeFirst()- Get first element or default valueForEach()- Execute action for each elementDistinctBy()- Get distinct elements by key selector
StringBuilder Extensions
ClearAppend()- Clear and append stringClearAppendLine()- Clear and append with newlineAppendIf()- Append only if condition is true ✨ NEWAppendLineIf()- Append line only if condition is true ✨ NEWAppendJoin()- Append collection with separator ✨ NEW
DataTable Extensions
HasRows()- Check if DataTable has rowsToExcel()- Export to Excel (.xlsx)ToHTMLTable()- Convert to HTML tableToDataTable<T>()- Convert IList<T> to DataTable
DataRow Extensions
GetInt()- Extract integer from DataRow field
Dictionary Extensions ✨ NEW
GetOrDefault()- Get value or return defaultAddOrUpdate()- Add or update key-value pairMerge()- Merge two dictionariesToQueryString()- Convert to URL query string format
Stream Extensions ✨ NEW
ToByteArray()- Convert stream to byte arrayReadToString()- Read stream as stringSaveToFile()- Save stream to file pathReset()- Reset stream position to beginning
Byte Array Extensions ✨ NEW
ToBase64()- Convert byte array to Base64 stringFromBase64()- Convert Base64 string to byte arrayToStream()- Convert byte array to streamToMemoryStream()- Convert byte array to MemoryStreamToFormattedSize()- Format bytes as human-readable size
Enum Extensions ✨ NEW
GetDescription()- Get Description attribute valueParseEnum<T>()- Parse string to enum with defaultGetEnumValues<T>()- Get all enum values as arrayGetEnumValuesEnumerable<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 millisecondsMinToSec()- Minutes to secondsMsToMin()- Milliseconds to minutesMsToSec()- Milliseconds to secondsToTime()- Milliseconds to HH:MM:SS format
Numeric Extensions
IsEven()- Check if integer is evenIsOdd()- Check if integer is oddIsNumericType()- Check if type is numericNegativeNumber()- 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 modeIsInTolerance()- Check if within tolerancePercentageOf()- 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:
License
Licensed under the MIT License.
Author
Solutions Group Unlimited, LLC
Copyright © 2025 Solutions Group Unlimited, LLC. All rights reserved.
| Product | Versions 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. |
-
.NETFramework 4.8
- ClosedXML (>= 0.105.0)
- Newtonsoft.Json (>= 13.0.4)
- System.ComponentModel.Annotations (>= 5.0.0)
- System.IO.Packaging (>= 10.0.1)
- System.Net.Http (>= 4.3.4)
- System.Text.RegularExpressions (>= 4.3.1)
-
net10.0-windows10.0.26100
- ClosedXML (>= 0.105.0)
- Newtonsoft.Json (>= 13.0.4)
- System.ComponentModel.Annotations (>= 5.0.0)
-
net10.0-windows7.0
- ClosedXML (>= 0.105.0)
- Newtonsoft.Json (>= 13.0.4)
- System.ComponentModel.Annotations (>= 5.0.0)
-
net8.0-windows7.0
- ClosedXML (>= 0.105.0)
- Newtonsoft.Json (>= 13.0.4)
- System.IO.Packaging (>= 10.0.1)
-
net9.0-windows7.0
- ClosedXML (>= 0.105.0)
- Newtonsoft.Json (>= 13.0.4)
- System.IO.Packaging (>= 10.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.