Snipster 1.0.4
See the version list below for details.
dotnet add package Snipster --version 1.0.4
NuGet\Install-Package Snipster -Version 1.0.4
<PackageReference Include="Snipster" Version="1.0.4" />
<PackageVersion Include="Snipster" Version="1.0.4" />
<PackageReference Include="Snipster" />
paket add Snipster --version 1.0.4
#r "nuget: Snipster, 1.0.4"
#:package Snipster@1.0.4
#addin nuget:?package=Snipster&version=1.0.4
#tool nuget:?package=Snipster&version=1.0.4
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, uow, excel
NuGet Packages Used
Package | Version |
---|---|
Microsoft.EntityFrameworkCore | 3.1.32 |
Newtonsoft.Json | 13.0.1 |
ClosedXML | 0.105.0 |
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) |
Email, password validations |
StringValEx | IsContainsIgnoreCase() IsValidSriLankanPhone() IsValidInternationalPhone() IsNumeric() IsAlphabetic() IsAlphanumeric() |
String-related validations |
NetworkValEx | IsValidIPv4() |
Network-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 |
NetworkFx | IsHostAvailableAsync(host) BuildUrl(baseUrl, params) |
Network & URL Utilities (with Query Parameter Support) |
FileFx | SafeReadText() SafeReadBytes() SafeWriteText() SafeWriteBytes() CreateTempFile() GetDirectorySize() SanitizeFileName() |
File Handling & Directory Utilities |
ExcelFx | WriteToExcel() WriteToMemory() |
Write data to a file or memory stream |
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. |
IUnitOfWork Interface Methods
Method Highlights | Description |
---|---|
Repository<TEntity>() BeginTransactionAsync() CommitAsync() RollbackAsync() SaveChangesAsync() |
Centralized transaction and repository management with EF Core, supporting async and sync operations. |
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 |
Example Usage for Extensions
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"
Example Usage for Helpers
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
File: Create a temporary file with the specified extension
using Snipster.Library.Helpers;
var tempFile = FileFx.CreateTempFile(".log");
// Verify if the file was created successfully
bool exists = File.Exists(tempFile);
Console.WriteLine($"File created: {exists} | Path: {tempFile}");
Excel: Create an Excel file with data, column definitions, and export options
using Snipster.Library.Helpers;
using Snipster.Library.Models;
using Snipster.Library.Enums;
// Your data list object
var data = new List<TestObject>
{
new TestObject { Id = 1, Name = "John", Value = 1000, Age = 30, IsMember = true, JoinDate = new DateTime(2023, 01, 15), Salary = 5000.25, Commission = 0.075 },
new TestObject { Id = 2, Name = "Anika", Value = 2500, Age = 27, IsMember = false, JoinDate = new DateTime(2024, 06, 05), Salary = 7250.50, Commission = 0.10 }
}
// Column definitions
var columns = new List<ExcelColumn>
{
new ExcelColumn { Name = "Id", DataType = typeof(int), HeaderText = "ID", Format = ExcelFormats.Integer, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "Name", DataType = typeof(string), HeaderText = "Full Name", Format = ExcelFormats.Text, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "Value", DataType = typeof(int), HeaderText = "Value", Format = ExcelFormats.Integer, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "Age", DataType = typeof(int), HeaderText = "Age", Format = ExcelFormats.Integer, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "IsMember", DataType = typeof(bool), HeaderText = "Membership", TrueText = "Yes", FalseText = "No", Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "JoinDate", DataType = typeof(DateTime), HeaderText = "Join Date", Format = ExcelFormats.DateTime, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "Salary", DataType = typeof(double), HeaderText = "Salary", Format = ExcelFormats.Currency, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left },
new ExcelColumn { Name = "Commission", DataType = typeof(double), HeaderText = "Commission", Format = ExcelFormats.Percent, Width = 25, Alignment = ExcelAlignment.Left, HeaderAlignment = ExcelAlignment.Left }
};
// Meta info
string sheetName = "TestSheet";
string tempFilePath = Path.GetTempPath();
string tempFileName = $"test-{Guid.NewGuid()}.xlsx";
// Write the file with export options
ExcelFx.WriteToExcel(data, columns, tempFilePath, tempFileName, opts =>
{
opts.AutoFitColumns = false;
opts.FreezeHeader = true;
opts.AlternateRowColors = true;
opts.HeaderBackground = XLColor.LightGray;
opts.AlternateRowColor = XLColor.LightYellow;
opts.SheetName = sheetName;
});
// Verify if the file was created successfully
string fullPath = Path.Combine(tempFilePath, tempFileName);
bool exists = File.Exists(fullPath);
Console.WriteLine($"File created: {exists} | Path: {fullPath}");
Repository & Unit of Work Patterns
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);
}
}
...
}
IUnitOfWork with DI
// Register in DI
services.AddScoped<IUnitOfWork, UnitOfWork>();
// Then use it in your services
using Snipster.Library.UOW;
public class OrderService
{
private readonly IUnitOfWork _uow;
private readonly IGenericRepository<Order> _orderRepo;
public OrderService(IUnitOfWork uow, IGenericRepository<Order> orderRepo)
{
_uow = uow;
_orderRepo = orderRepo;
}
public async Task PlaceOrderAsync(Order order)
{
await _uow.BeginTransactionAsync();
try
{
await _orderRepo.AddAsync(order);
await _uow.SaveChangesAsync();
// ... maybe add another entity
await _uow.CommitAsync();
}
catch
{
await _uow.RollbackAsync();
throw;
}
}
...
}
Cache Service
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!";
});
}
...
}
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
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
- ClosedXML (>= 0.105.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