SkyWebFramework.Utilities 1.0.1

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

⚡ SkyWebFramework.Utilities

<div align="center">

A comprehensive .NET utility library for everyday development

String manipulation • Date handling • Security helpers • Collection extensions • Math utilities

NuGet Downloads License .NET

</div>


🎯 Why SkyWebFramework.Utilities?

Stop writing the same utility methods in every project. Get battle-tested, production-ready helpers for the most common development tasks. Clean, efficient, and zero-dependency.

// It's this simple
using SkyWebFramework.Utility;

var slug = EasyString.Slugify("Hello World! 123"); // "hello-world-123"
var timeAgo = EasyDate.ToRelativeTime(someDate);    // "5 minutes ago"
var hash = EasySecurity.Sha256Hash(password);       // Secure hashing

✨ What's Included

🔤 EasyString - String Manipulation

  • Slugify - URL-friendly strings
  • Case Conversion - camelCase, PascalCase, TitleCase
  • Validation - Email, phone number validation
  • Text Processing - Truncate, mask, extract digits
  • Diacritics Removal - "Café" → "Cafe"
  • Initials Extraction - "John Doe" → "JD"

📅 EasyDate - Date & Time Utilities

  • Relative Time - "5 minutes ago", "2 days ago"
  • Time Rounding - Round to seconds, minutes, or hours
  • Range Helpers - Start/end of day, week, month
  • Business Days - Calculate working days between dates
  • Age Calculation - From birth date
  • ISO 8601 Formatting - Standard date formatting

🔐 EasySecurity - Cryptography & Security

  • Secure Random Generation - Cryptographically secure strings
  • Password Generation - Strong passwords with requirements
  • Hashing - SHA256 hashing for sensitive data
  • Simple Hashing - Fast non-cryptographic hashing

📦 EasyCollection - Collection Extensions

  • Batch Processing - Split collections into chunks
  • Safe Dictionary Access - GetValueOrDefault
  • Null Checks - IsNullOrEmpty for collections
  • DistinctBy - Unique items by property
  • Delimited Strings - Convert collections to CSV-like strings

🔢 EasyMath - Math & Number Helpers

  • Clamp - Constrain values to ranges
  • Range Validation - IsInRange checks
  • Percentage Calculation - Quick percentage math
  • File Size Formatting - "1024" → "1 KB"
  • Significant Digits - Smart number rounding

📦 Installation

dotnet add package SkyWebFramework.Utilities

Supports: .NET 6.0, .NET 7.0, .NET 8.0

🚀 Quick Start Examples

String Operations

using SkyWebFramework.Utility;

// URL-friendly slugs
var slug = EasyString.Slugify("Hello World! 123");
// Result: "hello-world-123"

// Email validation
if (EasyString.IsValidEmail("user@example.com"))
{
    // Valid email
}

// Mask sensitive data
var masked = EasyString.Mask("1234567890", visibleChars: 4);
// Result: "******7890"

// Case conversion
var camel = EasyString.ToCamelCase("Hello World");      // "helloWorld"
var pascal = EasyString.ToPascalCase("hello world");    // "HelloWorld"
var title = EasyString.ToTitleCase("hello world");      // "Hello World"

// Extract initials
var initials = EasyString.GetInitials("John Michael Doe");
// Result: "JMD"

// Truncate with ellipsis
var truncated = EasyString.Truncate("Long text here", 10, addEllipsis: true);
// Result: "Long te..."

Date & Time Operations

using SkyWebFramework.Utility;

// Relative time (perfect for social media apps)
var posted = DateTime.UtcNow.AddMinutes(-45);
var timeAgo = EasyDate.ToRelativeTime(posted);
// Result: "45 minutes ago"

// Date range helpers
var startOfWeek = EasyDate.StartOfWeek(DateTime.Today);
var endOfMonth = EasyDate.EndOfMonth(DateTime.Today);

// Business days calculation
var workDays = EasyDate.GetBusinessDays(startDate, endDate);
// Excludes weekends automatically

// Age calculation
var age = EasyDate.CalculateAge(birthDate);

// Time rounding
var rounded = EasyDate.UtcNowRoundedMinutes();

// ISO 8601 formatting
var iso = EasyDate.ToIso8601(DateTime.UtcNow);
// Result: "2024-01-15T14:30:45.123Z"

// Date checks
if (EasyDate.IsToday(someDate)) { }
if (EasyDate.IsPast(deadline)) { }
if (EasyDate.IsFuture(appointment)) { }

Security Operations

using SkyWebFramework.Utility;

// Generate secure random tokens
var token = EasySecurity.GenerateSecureRandomString(32);
// Cryptographically secure 32-character string

// Generate strong passwords
var password = EasySecurity.GenerateSecurePassword(
    length: 16, 
    requireSpecialChars: true
);
// Result: "aB3$xY9&pQ2@mN8!"

// SHA256 hashing
var hash = EasySecurity.Sha256Hash("sensitive-data");
// Result: "2c26b46b68ffc68ff99b453c1d30413413422d706..."

// Fast non-cryptographic hashing
var simpleHash = EasySecurity.SimpleHash("cache-key");
// For cache keys, quick lookups, etc.

Collection Operations

using SkyWebFramework.Utility;

// Safe dictionary access
var config = new Dictionary<string, string>();
var value = config.GetValueOrDefault("key", "default-value");

// Null or empty check
if (myList.IsNullOrEmpty())
{
    // Handle empty collection
}

// Batch processing
var items = Enumerable.Range(1, 100);
foreach (var batch in items.Batch(10))
{
    // Process 10 items at a time
    ProcessBatch(batch);
}

// Distinct by property
var users = GetUsers();
var uniqueEmails = users.DistinctBy(u => u.Email);

// Convert to delimited string
var ids = new[] { 1, 2, 3, 4, 5 };
var csv = ids.ToDelimitedString(", ");
// Result: "1, 2, 3, 4, 5"

Math Operations

using SkyWebFramework.Utility;

// Clamp values
var clamped = temperature.Clamp(0, 100);
// Ensures value is between 0 and 100

// Range validation
if (age.IsInRange(18, 65))
{
    // Within valid range
}

// Percentage calculation
var percent = EasyMath.Percentage(25, 200);
// Result: 12.5

// File size formatting
var size = EasyMath.FormatFileSize(1048576);
// Result: "1 MB"

// Round to significant digits
var rounded = EasyMath.RoundToSignificantDigits(12345.6789, 3);
// Result: 12300

📚 Complete API Reference

EasyString Methods

Method Description Example
Slugify(string) URL-safe slug "Hello!" → "hello"
ToTitleCase(string) Title case "hello" → "Hello"
ToCamelCase(string) camelCase "Hello World" → "helloWorld"
ToPascalCase(string) PascalCase "hello world" → "HelloWorld"
Truncate(string, int, bool) Truncate text ("Long text", 5, true) → "Lo..."
Mask(string, int, char) Mask sensitive data "123456" → "**3456"
ExtractDigits(string) Extract numbers "abc123" → "123"
RemoveDiacritics(string) Remove accents "Café" → "Cafe"
GetInitials(string) Get initials "John Doe" → "JD"
IsValidEmail(string) Validate email "user@example.com" → true
IsValidPhone(string) Validate phone "+1234567890" → true
EqualsIgnoreCase(string, string) Case-insensitive compare -
GenerateRandomString(int, string) Random string -

EasyDate Methods

Method Description Example
ToRelativeTime(DateTime) Human-readable time "5 minutes ago"
UtcNowRoundedSeconds() Round to seconds -
UtcNowRoundedMinutes() Round to minutes -
UtcNowRoundedHours() Round to hours -
StartOfDay(DateTime) 00:00:00 of date -
EndOfDay(DateTime) 23:59:59 of date -
StartOfWeek(DateTime) Monday of week -
StartOfMonth(DateTime) First day of month -
EndOfMonth(DateTime) Last day of month -
IsToday(DateTime) Check if today -
IsPast(DateTime) Check if past -
IsFuture(DateTime) Check if future -
CalculateAge(DateTime) Calculate age birthDate → 25
GetBusinessDays(DateTime, DateTime) Working days 5 days excluding weekends
ToIso8601(DateTime) ISO format "2024-01-15T14:30:45.123Z"

EasySecurity Methods

Method Description Use Case
GenerateSecureRandomString(int, string) Crypto-secure random API tokens, session IDs
GenerateSecurePassword(int, bool) Strong password User passwords
Sha256Hash(string) SHA256 hash Password storage, data integrity
SimpleHash(string) Fast hash Cache keys, quick lookups

EasyCollection Methods

Method Description Example
GetValueOrDefault<K,V>(K, V) Safe dictionary access -
IsNullOrEmpty<T>() Check empty collection -
Batch<T>(int) Split into chunks Process 100 items in batches of 10
DistinctBy<T>(Func) Unique by property Unique users by email
ToDelimitedString<T>(string) Join with delimiter [1,2,3] → "1, 2, 3"

EasyMath Methods

Method Description Example
Clamp<T>(T, T, T) Constrain to range Clamp(150, 0, 100) → 100
IsInRange<T>(T, T, T) Range validation IsInRange(50, 0, 100) → true
Percentage(double, double) Calculate % Percentage(25, 200) → 12.5
FormatFileSize(long) Human-readable size 1024 → "1 KB"
RoundToSignificantDigits(double, int) Smart rounding -

🎯 Real-World Use Cases

Building a Blog System

// Create URL-friendly slugs
var slug = EasyString.Slugify(blogPost.Title);
// "10 Tips for Developers!" → "10-tips-for-developers"

// Show relative post time
var timeAgo = EasyDate.ToRelativeTime(blogPost.CreatedAtUtc);
// Display: "Posted 2 hours ago"

// Extract author initials for avatar
var initials = EasyString.GetInitials(author.FullName);
// "John Smith" → "JS"

User Registration Flow

// Validate email
if (!EasyString.IsValidEmail(model.Email))
{
    return BadRequest("Invalid email format");
}

// Generate secure password reset token
var resetToken = EasySecurity.GenerateSecureRandomString(64);

// Hash password before storage
var passwordHash = EasySecurity.Sha256Hash(model.Password);

// Calculate age for validation
var age = EasyDate.CalculateAge(model.BirthDate);
if (!age.IsInRange(18, 120))
{
    return BadRequest("Invalid age");
}

Data Processing Pipeline

var records = await GetLargeDataSetAsync();

// Process in batches to avoid memory issues
foreach (var batch in records.Batch(100))
{
    await ProcessBatchAsync(batch);
    
    // Log progress
    var progress = EasyMath.Percentage(processedCount, totalCount);
    _logger.LogInformation($"Progress: {progress:F1}%");
}

File Upload Handler

public IActionResult UploadFile(IFormFile file)
{
    // Format file size for display
    var sizeDisplay = EasyMath.FormatFileSize(file.Length);
    // "5242880" → "5 MB"
    
    // Generate secure filename
    var secureFilename = EasySecurity.GenerateSecureRandomString(16) 
                       + Path.GetExtension(file.FileName);
    
    // Create URL slug for display name
    var displayName = EasyString.Slugify(
        Path.GetFileNameWithoutExtension(file.FileName)
    );
    
    return Ok(new { sizeDisplay, secureFilename, displayName });
}

Report Generation

// Date range for report
var startDate = EasyDate.StartOfMonth(DateTime.Today);
var endDate = EasyDate.EndOfMonth(DateTime.Today);
var businessDays = EasyDate.GetBusinessDays(startDate, endDate);

// Format report data
var report = new
{
    Period = $"{startDate:yyyy-MM-dd} to {endDate:yyyy-MM-dd}",
    BusinessDays = businessDays,
    TotalRevenue = revenue.ToString("C"),
    GrowthRate = $"{EasyMath.Percentage(growth, previousTotal):F1}%",
    UniqueCustomers = customers.DistinctBy(c => c.Email).Count()
};

💡 Best Practices

✅ Do's

// Use appropriate methods for the task
var slug = EasyString.Slugify(title);           // For URLs
var hash = EasySecurity.Sha256Hash(password);   // For security

// Validate user input
if (EasyString.IsValidEmail(email))
{
    // Process valid email
}

// Use safe dictionary access
var setting = config.GetValueOrDefault("key", "default");

❌ Don'ts

// Don't use SimpleHash for security
var hash = EasySecurity.SimpleHash(password); // ❌ Use Sha256Hash instead

// Don't ignore validation
await SaveUser(email); // ❌ Validate first with IsValidEmail

// Don't reinvent the wheel
var slug = title.ToLower().Replace(" ", "-"); // ❌ Use Slugify instead

🔧 Performance Considerations

  • Regex Patterns: Pre-compiled for better performance
  • String Operations: Optimized with StringBuilder where appropriate
  • Security: Uses cryptographically secure random number generation
  • Collections: Lazy evaluation with yield return for memory efficiency

🤝 Contributing

Contributions are welcome! If you have ideas for new utilities or improvements:

  1. Fork the repository
  2. Create a feature branch
  3. Submit a pull request

📄 License

MIT License - Free for commercial and personal use.

Copyright © 2025 Surya Pratap Singh


<div align="center">

Built with ❤️ for the .NET community

NuGet PackageReport IssuesDocumentation

</div>

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  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 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • 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
1.0.1 120 11/1/2025
1.0.0 168 10/13/2025

Version 1.0.0 - Initial Release

✨ String Utilities:
- Truncate with ellipsis
- Slugify for URLs
- ToTitleCase, ToCamelCase, ToPascalCase, ToSnakeCase
- RemoveWhitespace, RemoveSpecialCharacters
- IsNullOrWhiteSpace extensions
- Email/URL validation
- Mask sensitive data
- Extract numbers, words, lines
- Reverse, shuffle, repeat

📅 Date and Time Utilities:
- Calculate age, business days
- Add/subtract business days
- IsWeekend, IsBusinessDay
- StartOfDay, EndOfDay, StartOfMonth, EndOfMonth
- TimeAgo formatting ("2 hours ago")
- IsInRange, IsBetween
- Quarter calculations
- Unix timestamp conversions

📦 Collection Utilities:
- Batch/chunk operations
- Shuffle, sample random items
- DistinctBy, MaxBy, MinBy (pre-.NET 6)
- IsNullOrEmpty, SafeAny, SafeFirst
- ForEach extensions
- AddRange, RemoveAll
- Paginate collections
- Safe indexing

🔒 Security Utilities:
- MD5, SHA256, SHA512 hashing
- AES encryption/decryption
- Secure random token generation
- Password hashing (BCrypt-style)
- GUID generation helpers
- Base64 encoding/decoding
- Secure string comparison

🔢 Math Utilities:
- Percentage calculations
- Clamp values
- IsInRange, IsBetween
- Round to nearest, up, down
- Absolute value
- Min/max of multiple values
- Average calculations
- Unit conversions

🎯 Object Utilities:
- Deep clone
- Null-safe property access
- Object mapping
- Type checking
- Default value helpers
- JSON serialization helpers

🚀 Performance:
- Zero external dependencies
- Optimized algorithms
- Minimal memory allocation
- Thread-safe operations where applicable

📦 Compatibility:
- .NET 8.0, 7.0, and 6.0
- Works with ASP.NET Core, Blazor, MAUI, Console Apps
- Nullable reference types support
- Modern C# language features