Snipster 1.0.3
dotnet add package Snipster --version 1.0.3
NuGet\Install-Package Snipster -Version 1.0.3
<PackageReference Include="Snipster" Version="1.0.3" />
<PackageVersion Include="Snipster" Version="1.0.3" />
<PackageReference Include="Snipster" />
paket add Snipster --version 1.0.3
#r "nuget: Snipster, 1.0.3"
#:package Snipster@1.0.3
#addin nuget:?package=Snipster&version=1.0.3
#tool nuget:?package=Snipster&version=1.0.3
Snipster
Snipster is a lightweight, open-source .NET utility library that provides a comprehensive collection of helper and extension methods for everyday development tasks — including validation, data formatting, parsing, security, and more. It also includes a generic repository interface with an optional EF Core-based implementation, as well as a flexible cache service for in-memory caching with configurable expiration and validation support.
Available on NuGet
License: MIT
Tags: .NET
, utilities, helpers, validations, dotnet, repository, caching
NuGet Packages Used
Package | Version |
---|---|
Microsoft.EntityFrameworkCore | 3.1.32 |
Newtonsoft.Json | 13.0.1 |
Installation
dotnet add package Snipster
Available Utilities
Validation Extensions
Category | Method Highlights | Description |
---|---|---|
CollectionValEx | IsNullOrEmpty<T>() HasDuplicates<T>() |
Check if a collection is null/empty or has duplicates |
CreditCardValEx | IsValidCreditCard() |
Validates if a string is a valid card number |
DateTimeValEx | IsToday() IsFuture() IsPast() IsWeekend() IsWeekday() IsValidDate(format) |
Various date validation helpers |
JsonValEx | IsValidJson() |
Checks if a string is valid JSON |
SecurityValEx | IsValidEmail() IsStrongPassword(minLength) IsValidIPv4() |
Email, password, and IPv4 validations |
StringValEx | IsContainsIgnoreCase() IsValidSriLankanPhone() IsValidInternationalPhone() IsNumeric() IsAlphabetic() IsAlphanumeric() |
String-related validations |
Extension Methods
Category | Method Highlights | Description |
---|---|---|
CollectionEx | ChunkBy() ToSafeDictionary() RandomItem() ForEach() MostCommon() Shuffle() LeastCommon() ExceptSafe() |
LINQ-style enhancements for collections |
CreditCardEx | GetCreditCardType() |
Detects the card brand from a number |
DateTimeEx | ToUnixTimestamp() FromUnixTimestamp() ToTimeAgo() StartOfDay() EndOfDay() ToTimeZone() FromTimeZone() ToDateString() ToTimeString() ToFullDateTimeString() GetWeekStartDate() GetWeekEndDate() GetWeekOfYear() ToAge() |
Rich date/time formatting and conversions |
JsonEx | ToJson() FromJson<T>() |
Object-to-JSON and JSON-to-object |
NumberEx | ToOrdinal() ToIntSafe() ToDoubleSafe() |
Numeric formatting and safe conversion |
SecurityEx | ToSha256() |
Secure hash generation |
StringEx | CapitalizeFirst() ToTitleCase() OnlyDigits() Truncate() Slugify() ToBase64() FromBase64() OrDefault() StripHtmlTags() SanitizeAlphanumeric() RemoveSpecialCharacters() ToCamelCase() ToPascalCase() ToKebabCase() RemoveWhitespace() NormalizeSpaces() GetDescription() ToCleanQueryString() |
Powerful string manipulation toolkit |
Helper Methods
Category | Method Highlights | Description |
---|---|---|
JsonFx | Minify() Prettify() |
Minify and format JSON strings |
SecurityFx | RandomString() GenerateSecureToken() PasswordHash() VerifyPassword() |
Security and password utilities |
StringFx | FormatBytes() GenerateUniqueUsername() GenerateGuid() |
Friendly sizes, safe usernames, GUID control |
IGenericRepository Interface Methods
Method Highlights | Description |
---|---|
GetAllAsync() GetAllByConditionAsync() GetByConditionAsync() GetSelectedColumnsAsync() IsExistAsync() AddAsync() AddRangeAsync() Update() UpdateRange() Remove() RemoveAsync() SaveChangesAsync() |
Common generic CRUD operations using Entity Framework Core. Designed for asynchronous and synchronous data handling. |
ICacheService Interface Methods
Method Highlights | Description |
---|---|
SetCacheAsync() |
Sets a cache entry with default duration (5 min) asynchronously |
SetCacheAsync(duration) |
Sets a cache entry with a specified duration asynchronously |
SetLongCacheAsync() |
Sets a cache entry with a long (60 min) expiration asynchronously |
RemoveCache() |
Removes a cache entry |
ITableLogger Interface Methods
Method Highlights | Description |
---|---|
LogToTableAsync() |
Enqueues a log entry for storage in a database table. Logs are processed in batches by a background task. Supports cancellation via a CancellationToken. Throws ArgumentNullException if the log is null. |
Example Usage
String: Slugify & Case Conversion
using Snipster.Library.Extensions;
var title = "Hello World!";
var slug = title.Slugify();
// Output: "hello-world"
Collection: Chunk and Random Item
using Snipster.Library.Extensions;
var numbers = Enumerable.Range(1, 10);
var chunks = numbers.ChunkBy(3);
// Output: [[1,2,3],[4,5,6],[7,8,9],[10]]
JSON: Safe Serialization
using Snipster.Library.Extensions;
var json = new { Name = "Dev" }.ToJson();
// Output: {"Name":"Dev"}
var obj = "{"Name":"Dev"}".FromJson<Dictionary<string, string>>();
Console.WriteLine(obj["Name"]);
// Output: Dev
DateTime: Time Ago & Start of Day
using Snipster.Library.Extensions;
var ago = DateTime.UtcNow.AddMinutes(-10).ToTimeAgo();
// Output: "10 minutes ago"
Security: Hash a password
using Snipster.Library.Helpers;
SecurityFx.PasswordHash("myPassword", out var hash, out var salt);
bool isValid = SecurityFx.VerifyPassword("myPassword", hash, salt);
// Output: true/false based on verification
Implement IGenericRepository
using Snipster.Library.Repository;
public class MyRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
private readonly DbContext _context;
private readonly DbSet<TEntity> _dbSet;
public MyRepository(DbContext context)
{
_context = context;
_dbSet = context.Set<TEntity>();
}
public async Task AddAsync(TEntity entity)
{
await _dbSet.AddAsync(entity);
}
...
}
IGenericRepository with DI
// Register in DI
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
// Then use it in your services
using Snipster.Library.Repository;
public class UserService
{
private readonly IGenericRepository<User> _userRepository;
public UserService(IGenericRepository<User> userRepository)
{
_userRepository = userRepository;
}
public async Task PrintAllUsersAsync()
{
var users = await _userRepository.GetAllAsync();
foreach(var user in users)
{
Console.WriteLine(user.Name);
}
}
...
}
Implement ICacheService
using Snipster.Library.Cache;
public class MyCacheService : ICacheService
{
private readonly IMemoryCache _cache;
public MyCacheService(IMemoryCache cache)
{
_cache = cache;
}
public async Task<T?> SetCacheAsync<T>(string key, Func<Task<T>> create) where T : class
{
...
}
...
}
ICacheService with DI
// Register in DI
services.AddSingleton<ICacheService, CacheService>();
// Then use it in your services
using Snipster.Library.Cache;
public class MyService
{
private readonly ICacheService _cacheService;
public MyService(ICacheService cacheService)
{
_cacheService = cacheService;
}
public async Task<string?> GetDataAsync()
{
const string cacheKey = "my_data";
return await _cacheService.SetCacheAsync(cacheKey, async () =>
{
// Simulate fetching data from a database or API
await Task.Delay(100);
return "Hello from database!";
});
}
...
}
Implement ITableLogger
using Snipster.Library.Logger;
public class TableLogger<TLog> : ITableLogger<TLog> where TLog : class
{
private readonly IDbContextFactory<MyDbContext> _dbContextFactory;
public TableLogger(IDbContextFactory<MyDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory ?? throw new ArgumentNullException(nameof(dbContextFactory));
}
public async Task LogToTableAsync(TLog log, CancellationToken cancellationToken = default)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
...
}
...
}
ITableLogger with DI
using Snipster.Library.Logger;
// Register DbContext
services.AddDbContext<MyLogDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
// Register ITableLogger
services.AddScoped<ITableLogger<MyErrorLog>>(sp =>
new TableLogger<MyErrorLog>(() => sp.GetRequiredService<MyLogDbContext>()));
// Then use it in your services
using Snipster.Library.Logger;
public class MyService
{
private readonly ITableLogger<MyErrorLog> _logger;
public MyService(ITableLogger<MyErrorLog> logger)
{
_logger = logger;
}
public async Task DoSomething()
{
try
{
...
}
catch (Exception ex)
{
// Log object
var logEntry = new TestLog
{
Message = "Test log message.",
StackTrace = ex.StackTrace,
Source = "Test source."
}
await _logger.LogToTableAsync(logEntry);
}
}
}
Contributions
Pull requests, suggestions, and feedback are welcome!
Feel free to fork and improve or extend the utility set for the .NET community.
Contributors
Thanks to these wonderful people for their contributions!
Contributors Graph
Maintainers
This project is maintained by:
Support & Contact
Email : dar.dev.mail@gmail.com
LinkedIn: darwijesinghe
GitHub : darwijesinghe
Website : Portfolio
License
This project is licensed under the MIT License.
Product | Versions 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 was computed. 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. |
-
.NETStandard 2.0
- Microsoft.EntityFrameworkCore (>= 3.1.32)
- Newtonsoft.Json (>= 13.0.1)
GitHub repositories
This package is not used by any popular GitHub repositories.
See full release notes at https://github.com/darwijesinghe/Snipster/blob/main/RELEASE_NOTES.md