![]() |
VOOZH | about |
dotnet add package ClearTools.Abstraction --version 1.1.0
NuGet\Install-Package ClearTools.Abstraction -Version 1.1.0
<PackageReference Include="ClearTools.Abstraction" Version="1.1.0" />
<PackageVersion Include="ClearTools.Abstraction" Version="1.1.0" />Directory.Packages.props
<PackageReference Include="ClearTools.Abstraction" />Project file
paket add ClearTools.Abstraction --version 1.1.0
#r "nuget: ClearTools.Abstraction, 1.1.0"
#:package ClearTools.Abstraction@1.1.0
#addin nuget:?package=ClearTools.Abstraction&version=1.1.0Install as a Cake Addin
#tool nuget:?package=ClearTools.Abstraction&version=1.1.0Install as a Cake Tool
A comprehensive .NET Standard 2.1 utility library providing robust, production-ready tools for common development tasks. ClearTools offers utilities for string manipulation, cryptography, image processing, Azure services integration, HTTP client operations, and much more.
👁 NuGet Version
👁 License: MIT
dotnet add package ClearTools
using ClearTools.Extensions;
using Clear.Tools;
// String extensions
string text = "Hello 123 World!";
int number = text.ToInt32(); // Extracts numbers: 123
string cleaned = StringUtility.StripSymbols(text); // Removes symbols, preserves spaces: "Hello 123 World"
// Image processing
var scaledImage = ImageUtility.ScaleImage(originalImage, 800, 600);
// Cryptography
string salt = Crypto.CreateSalt();
string hash = Crypto.EncodeSHA256("password", salt);
// OTP generation
var otpResult = OtpUtility.GenerateCode("user@example.com", 12345, TimeSpan.FromMinutes(5));
NEW! Strongly-typed, attribute-driven configuration framework for parsing and managing connection strings and key-value configuration strings.
[ConnectionStringKey][Required] attributeAddConnectionString<T>()using ClearTools.Configuration.BuiltIn;
using ClearTools.Extensions;
// Parse SQL Server connection string
var sqlConfig = new SqlServerConnectionString(
"Server=localhost;Database=MyDb;User Id=sa;Password=mypass");
Console.WriteLine(sqlConfig.Server); // "localhost"
Console.WriteLine(sqlConfig.Database); // "MyDb"
// Register with DI
services.AddConnectionString<SqlServerConnectionString>(
configuration, "ConnectionStrings:MyDatabase");
// Inject into services
public class MyService
{
public MyService(SqlServerConnectionString config)
{
_connectionString = config.ToString();
}
}
Azure Services:
ServiceBusConnectionString - Azure Service BusAppConfigurationConnectionString - Azure App ConfigurationKeyVaultConnectionString - Azure Key VaultSqlServerConnectionString - SQL Server / Azure SQLCosmosDbConnectionString - Azure Cosmos DBBlobStorageConnectionString - Azure Blob StorageNon-Azure Services:
MongoDbConnectionString - MongoDBPostgreSqlConnectionString - PostgreSQLRedisConnectionString - RedisRabbitMqConnectionString - RabbitMQpublic class MyServiceConfig : ConnectionStringBase
{
[ConnectionStringKey("ApiUrl")]
[Required]
public string? ApiUrl { get; set; }
[ConnectionStringKey("ApiKey")]
[Required]
public string? ApiKey { get; set; }
[ConnectionStringKey("Timeout")]
public int? Timeout { get; set; }
public MyServiceConfig(string connectionString)
: base(connectionString) { }
}
// Store in Key Vault as single string
// "ApiUrl=https://api.example.com;ApiKey=secret123;Timeout=30"
// Use with DI
services.AddConnectionString<MyServiceConfig>(keyVaultSecret);
|, ,, or any delimiter instead of ;\;ToString() (excludes nulls)See for comprehensive examples.
StringUtility)Comprehensive string manipulation and processing tools:
// URL and SEO-friendly string generation
string urlKey = StringUtility.GenerateUrlKey("My Blog Post Title!"); // "my-blog-post-title"
// HTML and symbol stripping
string cleanText = StringUtility.StripHTML("<p>Hello <b>World</b></p>"); // "Hello World"
string alphanumeric = StringUtility.StripSymbols("Hello @World! 123"); // "Hello World 123"
// Date-based unique identifiers
string dateCode = StringUtility.GetDateCode(); // File time-based code
string updateId = StringUtility.AddUpDate(); // Timestamp-based ID
// Tag generation
string tags = StringUtility.GenerateTags("tag1", "tag2", "tag3"); // "tag1,tag2,tag3"
ImageUtility)Advanced image manipulation capabilities:
// Image scaling with aspect ratio preservation
Image scaledImage = ImageUtility.ScaleImage(sourceImage, 800, 600, ImageSizePreference.Width);
// Image cropping and resizing
Image croppedImage = ImageUtility.CropImage(sourceBitmap, 300, 300);
Bitmap resizedImage = ImageUtility.ResizeImage(sourceImage, 400, 300);
// Format conversion
byte[] imageBytes = ImageUtility.ConvertBitmapToBytes(bitmap, ImageFormat.Jpeg);
string base64Image = ImageUtility.ConvertImageToBase64(image, ImageFormat.Png);
// High-quality JPEG saving
ImageUtility.SaveJpegToFile("output.jpg", image, quality: 85);
Encryption)string key = "MySecretEncryptionKeyThatIsLongEnough123"; // 32+ chars required
string encrypted = Encryption.Encrypt("sensitive data", key);
string decrypted = Encryption.Decrypt(encrypted, key);
Crypto)// Hashing algorithms
string salt = Crypto.CreateSalt(128);
string sha256Hash = Crypto.EncodeSHA256("password", salt);
string sha512Hash = Crypto.EncodeSHA512("password", salt);
string sha1Hash = Crypto.EncodeSHA1("password");
// Base64 encoding/decoding
string encoded = Crypto.EncodeBase64("text to encode");
string decoded = Crypto.DecodeBase64(encoded);
OtpUtility)// Generate OTP with custom expiry
var otpResult = OtpUtility.GenerateCode("user@example.com", 12345, TimeSpan.FromMinutes(5));
Console.WriteLine($"Code: {otpResult.Code}, Expires: {otpResult.ExpiryTime}");
// Validate OTP
bool isValid = OtpUtility.ValidateCode("user@example.com", 12345, "123456", otpResult.ExpiryTime);
BaseConverter)Convert numbers between different bases and formats:
// Convert from any base to decimal
long decimal = BaseConverter.ConvertToDecimal("1010", 2); // Binary to decimal: 10
long hexDecimal = BaseConverter.ConvertToDecimal("FF", 16); // Hex to decimal: 255
// Convert decimal to any base
string binary = BaseConverter.ConvertFromDecimal(10, 2); // "1010"
string hex = BaseConverter.ConvertFromDecimal(255, 16); // "FF"
// Convert to alphabetic representation
string alpha = BaseConverter.ConvertToAlpha(26); // "BA"
EditorJS)Parse and convert EditorJS content to HTML:
// Parse EditorJS JSON to HTML
string html = EditorJS.Parse(editorJsJsonString);
// Supports: headers, paragraphs, lists, images, embeds (YouTube, Vimeo)
StringExtensions)Powerful string manipulation extensions:
// Value toggling
string toggled = "active".Toggle("inactive"); // "inactive"
// Case-insensitive operations
bool contains = "Hello World".Search("WORLD"); // true
bool equals = "Hello".EqualsNoCase("HELLO"); // true
// Number and symbol extraction
string numbers = "abc123def456".ExtractNumbers(); // "123456"
string clean = "Hello;World*".StripSymbols(); // "HelloWorld" (removes specific symbols)
// Type conversions
int number = "abc123".ToInt32(); // 123
decimal price = "Price: $29.99".ToDecimal(); // 29.99
// CSV processing
List<string> items = "apple,banana,cherry".ToListFromCsv();
HashSet<string> uniqueItems = "apple,banana,apple".ToHashSetFromCsv();
DateTimeExtensions)Enhanced DateTime formatting:
DateTime now = DateTime.Now;
string dateStr = now.ToDateString(); // "15/Aug/2025"
string dateTimeStr = now.ToDateTimeString(); // "15/Aug/2025 14:30:15"
StringBuilderExtensions)NEW in v3.2.1 - Fluent conditional string building:
using System.Text;
using ClearTools.Extensions;
var sb = new StringBuilder();
// Conditionally append content based on boolean conditions
sb.AppendIfTrue(isActive, "Active")
.AppendIfTrue(hasWarnings, " (warnings)")
.AppendLineIfTrue(isComplete, "Process complete");
// Example: Build dynamic messages
bool isAdmin = true;
bool hasErrors = false;
string message = new StringBuilder()
.Append("User logged in")
.AppendIfTrue(isAdmin, " with admin privileges")
.AppendIfTrue(hasErrors, " - errors detected")
.ToString();
// Result: "User logged in with admin privileges"
// Example: Conditional HTML generation
var html = new StringBuilder()
.Append("<div class='user'")
.AppendIfTrue(isPremium, " premium")
.AppendIfTrue(isVerified, " verified")
.AppendLine(">")
.AppendLineIfTrue(showDetails, "<p>User details...</p>")
.Append("</div>");
AppConfigurationExtensions)NEW in v3.2.0 - Comprehensive Azure App Configuration support with advanced features:
// Define settings class with regular config and feature flags
public class AppSettings
{
public string DatabaseConnectionString { get; set; }
[AppConfigurationKey("MyApp:ApiKey")]
public string ApiKey { get; set; }
public int MaxRetries { get; set; }
// Feature flags (bool/bool? only)
[FeatureFlag("enable-new-ui")]
public bool NewUiEnabled { get; set; }
[FeatureFlag("beta-features")]
public bool? BetaFeaturesEnabled { get; set; }
}
// Web Applications - Using Managed Identity (recommended for Azure)
var builder = WebApplication.CreateBuilder(args);
builder.AddAppConfigurationForWebApplication<AppSettings>(
appConfigEndpoint: new Uri("https://myapp.azconfig.io"),
out AppSettings settings,
label: "Production", // Environment-specific config
keyFilter: "MyApp:*", // Filter keys by prefix
credential: new DefaultAzureCredential()
);
// Web Applications - Using Connection String (flexible)
builder.AddAppConfigurationForWebApplication<AppSettings>(
connectionString: Environment.GetEnvironmentVariable("AppConfigConnectionString"),
out AppSettings settings,
label: "Staging"
);
// Azure Functions - Direct client access with environment fallback
hostBuilder.AddAppConfigurationForAzureFunctions<AppSettings>(
appConfigEndpoint: new Uri("https://myapp.azconfig.io"),
out AppSettings functionSettings,
skipDevelopment: true // Uses environment variables in dev
);
// Optional: Configuration refresh with sentinel keys
var refreshOptions = new AppConfigurationRefreshOptions
{
EnableRefresh = true,
RefreshInterval = TimeSpan.FromMinutes(5), // Minimum 30s recommended
SentinelKeys = new[] { "AppSettings:Version" }, // Trigger refresh
OnRefreshError = ex => logger.LogWarning(ex, "Config refresh failed")
};
builder.AddAppConfigurationForWebApplication<AppSettings>(
appConfigEndpoint: new Uri("https://myapp.azconfig.io"),
out AppSettings settings,
refreshOptions: refreshOptions
);
Key Features:
MyApp:*, Database:*)KeyVaultExtensions)Robust Azure Key Vault integration for secrets management:
// Define your settings class
public class AppSettings
{
public string DatabaseConnectionString { get; set; }
[KeyVaultKey("api-key")]
public string ApiKey { get; set; }
}
// For ASP.NET Web Applications
var builder = WebApplication.CreateBuilder(args);
builder.AddKeyVaultForWebApplication<AppSettings>(
keyVaultUri: "https://your-keyvault.vault.azure.net/",
out AppSettings settings
);
// For Azure Functions
hostBuilder.AddKeyVaultForAzureFunctions<AppSettings>(
keyVaultUri: "https://your-keyvault.vault.azure.net/",
out AppSettings functionSettings
);
AzureStorageManager)Azure Blob Storage operations:
string connectionString = "DefaultEndpointsProtocol=https;AccountName=...";
// Upload operations
AzureStorageManager.UploadToAzure(connectionString, "container", stream, "application/pdf", "file.pdf", "folder");
// Download operations
AzureStorageManager.DownloadFromAzure(connectionString, "container", fileInfo, "folder");
// Check folder existence
bool exists = AzureStorageManager.AzureFolderExists(connectionString, "container", "folder");
ServicesExtensions)Automatic service registration by interface:
// Register all services implementing IService
services.AddScopedServicesByInterface<IService>();
services.AddSingletonServicesByInterface<IRepository>();
services.AddTransientServicesByInterface<IValidator>();
ApiClient)Comprehensive HTTP client with built-in error handling and serialization:
// Initialize
var apiClient = new ApiClient(httpClient);
// GET with various options
var user = await apiClient.GetAsync<User>("https://api.example.com/users/1");
var userWithAuth = await apiClient.GetAsync<User>("https://api.example.com/users/1", bearerToken);
// POST operations
var response = await apiClient.PostAsync("https://api.example.com/users", newUser);
var createdUser = await apiClient.PostAsync<User, User>("https://api.example.com/users", newUser);
// reCAPTCHA validation
var captchaResult = await apiClient.ValidateGoogleCaptcharAsync(secretKey, response, remoteIp);
RequestValidationMiddleware)ASP.NET Core middleware for API key validation with flexible path exclusion:
// Basic setup
services.AddRequestValidation("your_secret_api_key", skipForDevelopment: true);
app.UseRequestValidation();
// With excluded paths (e.g., health checks, public endpoints)
services.AddRequestValidation(
"your_secret_api_key",
skipForDevelopment: true,
skipRootEndPoint: true,
excludedPaths: new[] { "/health", "/api/public", "/webhooks" }
);
app.UseRequestValidation();
// Using RequestValidationOption for more control
var options = new RequestValidationOption(
validationKey: "your_secret_api_key",
skipForDevelopment: true,
skipForRootEndPoint: true,
excludedPaths: new[] { "/health", "/metrics", "/api/public" }
);
services.AddSingleton(new RequestValidationMiddleware(options));
app.UseRequestValidation();
// Client usage - include key in headers
client.DefaultRequestHeaders.Add("key", "your_secret_api_key");
Features:
/)/health matches only /health/api/public matches /api/public, /api/public/users, etc.RequestValidationOption for advanced scenariosCommon Use Cases for Excluded Paths:
/health, /healthz)/metrics, /prometheus)/api/public)SmartEnum<TEnum>)Type-safe enumeration base class with value and name support:
// Define your SmartEnum
public class OrderStatus : SmartEnum<OrderStatus>
{
public static readonly OrderStatus Pending = new OrderStatus("Pending", 1);
public static readonly OrderStatus Processing = new OrderStatus("Processing", 2);
public static readonly OrderStatus Shipped = new OrderStatus("Shipped", 3);
public static readonly OrderStatus Delivered = new OrderStatus("Delivered", 4);
private OrderStatus(string name, int value) : base(name, value) { }
}
// Usage examples
var status = OrderStatus.Parse(2); // Get by value: Processing
var statusByName = OrderStatus.Parse("Shipped"); // Get by name: Shipped
// List all values
foreach (var status in OrderStatus.List())
{
Console.WriteLine($"{status.Name}: {status.Value}");
}
// Type-safe comparisons
OrderStatus current = OrderStatus.Processing;
if (current.Equals(OrderStatus.Processing))
{
Console.WriteLine("Order is being processed");
}
Features:
FluentDictionary<TKey, TValue>)Chainable dictionary operations with fluent API:
using Clear;
// Create and populate in one fluent chain
var config = new FluentDictionary<string, string>()
.Add("host", "localhost")
.Add("port", "5432")
.Add("database", "mydb")
.Add("username", "admin");
// Use the static factory method
var settings = FluentDictionary<string, int>.Create("timeout", 30)
.Add("retries", 3)
.Add("maxConnections", 100);
// Chain Add and Remove operations
var userPrefs = new FluentDictionary<string, bool>()
.Add("darkMode", true)
.Add("notifications", true)
.Add("autoSave", false)
.Remove("autoSave")
.Add("autoSave", true);
// All Dictionary<TKey, TValue> methods available
bool hasKey = config.ContainsKey("host");
bool hasValue = config.TryGetValue("port", out string portValue);
Features:
Fluent, chainable API for dictionary operations
Returns this for method chaining on Add() and Remove()
Static Create() factory method for initialization
Inherits all standard Dictionary<TKey, TValue> functionality
Type-safe with full generic support
Simplifies builder pattern and configuration setup
ValidationCodeResult: OTP generation results with code and expiry
CaptcherResponse: Google reCAPTCHA validation response
EditorJS Models: Complete data structures for EditorJS content parsing
# Via .NET CLI
dotnet add package ClearTools
# Via PackageReference
<PackageReference Include="ClearTools" Version="3.1.0" />
ClearTools targets .NET Standard 2.1 and includes:
public class ImageProcessor
{
public async Task<string> ProcessAndUploadImage(IFormFile file)
{
using var stream = file.OpenReadStream();
var image = Image.FromStream(stream);
// Process image
var scaledImage = ImageUtility.ScaleImage(image, 800, 600);
var imageBytes = ImageUtility.ConvertBitmapToBytes((Bitmap)scaledImage, ImageFormat.Jpeg);
// Generate unique filename
var fileName = StringUtility.GenerateFileName(file.FileName, "jpg");
// Upload to Azure
using var uploadStream = new MemoryStream(imageBytes);
AzureStorageManager.UploadToAzure(connectionString, "images", uploadStream, "image/jpeg", fileName, "uploads");
return fileName;
}
}
public class OtpService
{
private readonly int _secretKey = 123456;
public ValidationCodeResult GenerateOtp(string email)
{
return OtpUtility.GenerateCode(email, _secretKey, TimeSpan.FromMinutes(5));
}
public bool ValidateOtp(string email, string code, DateTime expiry)
{
return OtpUtility.ValidateCode(email, _secretKey, code, expiry);
}
}
For comprehensive documentation covering all methods and use cases, see:
✅ String Utilities: URL generation, HTML stripping, text processing
✅ Image Processing: Scaling, cropping, format conversion, quality optimization
✅ Cryptography: Hashing, encryption, salt generation, secure tokens
✅ OTP Management: Generation, validation, expiry handling
✅ Azure Integration: Key Vault, Blob Storage, managed identity support
✅ HTTP Client: RESTful API client with authentication and serialization
✅ Extensions: String, DateTime, Byte array, and service collection extensions
✅ Middleware: Request validation, API key authentication
✅ EditorJS: Content parsing and HTML conversion
✅ Base Conversion: Number base conversion utilities
✅ File Management: File I/O operations and utilities
This repository includes a GitHub Actions workflow that manually publishes both NuGet packages (ClearTools and ClearTools.Abstraction) to nuget.org.
NUGET_API_KEYThe workflow will restore, build (Release), pack both projects, and push all .nupkg files to nuget.org, skipping any versions that are already published.
We welcome contributions! Please see our for details.
This project is licensed under the MIT License - see the file for details.
ClearTools - Making .NET development clearer, one utility at a time. 🚀
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 was computed. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 was computed. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 was computed. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp1.0 netcoreapp1.0 was computed. netcoreapp1.1 netcoreapp1.1 was computed. netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard1.2 netstandard1.2 is compatible. netstandard1.3 netstandard1.3 was computed. netstandard1.4 netstandard1.4 was computed. netstandard1.5 netstandard1.5 was computed. netstandard1.6 netstandard1.6 was computed. netstandard2.0 netstandard2.0 was computed. netstandard2.1 netstandard2.1 was computed. |
| .NET Framework | net451 net451 was computed. net452 net452 was computed. net46 net46 was computed. net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 was computed. net481 net481 was computed. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen30 tizen30 was computed. tizen40 tizen40 was computed. tizen60 tizen60 was computed. |
| Universal Windows Platform | uap uap was computed. uap10.0 uap10.0 was computed. |
| Windows Phone | wpa81 wpa81 was computed. |
| Windows Store | netcore451 netcore451 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 1 NuGet packages that depend on ClearTools.Abstraction:
| Package | Downloads |
|---|---|
|
ClearTools
A set of general utilities suitable for any .net project. These utilities include, string manipulation, image, cryptography, http client, number base utility, Azure App Configuration, Azure Key Vault integration, and more. |
This package is not used by any popular GitHub repositories.