![]() |
VOOZH | about |
dotnet add package NeeLib --version 2.3.0
NuGet\Install-Package NeeLib -Version 2.3.0
<PackageReference Include="NeeLib" Version="2.3.0" />
<PackageVersion Include="NeeLib" Version="2.3.0" />Directory.Packages.props
<PackageReference Include="NeeLib" />Project file
paket add NeeLib --version 2.3.0
#r "nuget: NeeLib, 2.3.0"
#:package NeeLib@2.3.0
#addin nuget:?package=NeeLib&version=2.3.0Install as a Cake Addin
#tool nuget:?package=NeeLib&version=2.3.0Install as a Cake Tool
Author: SRTECH
Developer: SRTECH
Version: 2.3.0
NeeLib is a compact, production-ready .NET utility library for ASP.NET Core developers. It bundles a set of well-tested helpers for common web application tasks: alert payloads, in-memory caching, preference storage, session & cookie helpers, email (SMTP + Microsoft Graph), file I/O, secure random generation, date/time utilities, Excel export, HTML→PDF conversion, QR/barcode generation, REST client helpers, and encryption/password handling.
Target framework: .NET 10.0
Quick links
NeeLib solves recurring infrastructure tasks developers reimplement across web projects. Instead of rebuilding email senders, Excel exports, file utilities, or cryptography helpers, NeeLib provides a focused, dependency-light toolkit that:
Use cases: send transactional email, cache computed data, export DataTables to Excel, convert generated HTML to PDF, create QR codes for receipts, securely protect small secrets, and call external REST APIs.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Required for CacheMemory
builder.Services.AddMemoryCache();
// Required for SessionCookies
builder.Services.AddHttpContextAccessor();
builder.Services.AddSession();
// Required for Data Protection usage in Protector (if you want shared key management)
builder.Services.AddDataProtection();
var app = builder.Build();
app.UseSession();
app.Run();
Notes:
This section lists the main public classes in the package and example usage for their most important functions. Each example is self-contained and demonstrates typical usage.
Class summary A small utility that constructs JSON alert payloads (SweetAlert2 style) with minimal allocations. Designed for generating ready-to-send JSON objects used by client-side alert libraries.
Public functions
Function explanation
Example
using NeeLib;
var json = Alerts.AlertBox("Saved", "Your item was saved successfully.", Alerts.Success, false);
// json -> {"title":"Saved","text":"Your item was saved successfully.","icon":"success","toast":false}
Purpose: produces a compact JSON string that front-end code can pass to an alert library. Ensure client-side HTML encoding to avoid XSS.
Class summary Wrapper around IMemoryCache with recommended patterns: generic read/write, GetOrSet factory (async & sync), and sized entries. Provides typed access and prevents cache stampedes.
Main public functions
Example (async factory)
// inside a controller/service with IMemoryCache injected
var cacheUtil = new CacheMemory(memoryCache);
var options = cacheUtil.ConfigCache(TimeSpan.FromMinutes(5), TimeSpan.FromHours(1), size:1);
string value = await cacheUtil.GetOrSetCacheAsync<string>("greeting", async () => {
await Task.Delay(10);
return "Hello from DB";
}, options);
Purpose: avoid duplicate work (cache stampede protection via GetOrCreateAsync) and keep memory usage explicit.
Class summary Process-lifetime in-memory key-value store optimized for concurrent access using ConcurrentDictionary. Good for quick application-scoped flags or small cached values.
Public functions (examples)
Example
Preference.SetString("Theme","dark");
var theme = Preference.GetString("Theme"); // "dark"
Preference.SetInt("MaxItems", 50);
int max = Preference.GetInt("MaxItems"); // 50
Purpose: fast, thread-safe in-memory store for app preferences. Not persisted across restarts.
Class summary Helper bound to IHttpContextAccessor for safe read/write of cookies and session values, including object serialization to JSON and Base64 encoding of cookie values. Designed to be registered with DI and used in controllers/services.
Important public functions
Example (cookie)
// assume injected SessionCookies sessionCookies
sessionCookies.WriteCookie("user", "alice@example.com", DateTime.UtcNow.AddDays(7));
string user = sessionCookies.ReadCookie("user");
Example (session object)
sessionCookies.WriteSessionObject("cart", new { Items = 3, Total = 29.99m });
var cart = sessionCookies.ReadSessionObject<dynamic>("cart");
Prerequisites: Register IHttpContextAccessor and enable sessions in the web host.
Class summary High-level email utilities supporting SMTP (sync/async) and Microsoft Graph. Supports file attachments and asynchronous sending. Provides helper EmailModel DTO for common properties.
Key functions
Example (async SMTP)
var model = new EmailModel
{
From = "sender@example.com",
Password = "smtp-password",
Host = Email.GmailHost,
Port = Email.Port_587,
Ssl = Email.GmailSsl,
To = new[] { "recipient@example.com" },
Subject = "Test",
Body = "Hello from NeeLib",
BodyType = Email.HTML
};
string result = await Email.SendTextSMTPAsync(model, cc:false, bcc:false);
// result == "OK" on success
Notes: For Microsoft Graph usage, populate Tenantid, Clientid, Secretid in EmailModel and call SendTextApi/SendFileApi. Use GetUsersAsync to avoid sync-over-async.
Class summary File and directory utilities with async I/O, base64 file creation, and safe directory management.
Key functions
Example
await FilesIO.CreateFile("/tmp/log.txt", "Log entry at " + DateTime.UtcNow);
await FilesIO.CreateFileToBase64("/tmp/picture.png", base64Data);
Purpose: consistent cross-platform file operations with asynchronous APIs.
Class summary Secure random generation helpers that use RandomNumberGenerator for cryptographic security and zero-allocation string creation.
Public functions
Example
var token = Generate.Word(32); // 32-character secure token
var otp = Generate.Number(6); // 6-digit secure OTP
Purpose: create secure tokens, OTPs, and identifiers.
Class summary Date/time formatting constants and timezone ID constants for conversion and display. Provides predefined format strings and common Windows timezone IDs.
Example
string now = DateTime.UtcNow.ToString(GetDateTime.LONG_TIME1); // e.g., "14:23:05"
Public functions / constants
Note: Timezone IDs are Windows standard; if running cross-platform you may need mapping to IANA names.
Class summary Excel/CSV export helpers using ClosedXML. Supports DataTable and generic IEnumerable<T> exports to XLSX and FileContentResult for direct controller responses.
Key functions
Example
var bytes = MSOffice.CreateExcelSheet(dataTable);
System.IO.File.WriteAllBytes("out.xlsx", bytes);
Purpose: quickly produce Excel files for download or storage.
Function explanation (selected)
Class summary HTML minifier and HTML→PDF conversion via iText7. Includes resource-safe file creation.
Key functions
Example
string html = await Pdf.Minifier("templates/invoice.html");
Pdf.Create("https://example.com/assets/", html, "invoice.pdf");
Purpose: convert server-generated HTML pages to PDF documents suitable for printing or archival.
Function explanation (selected)
Class summary Uses QRCoder + ImageSharp + ZXing to produce raster (PNG/JPG/GIF), SVG QR codes and 1D barcodes. Supports logo compositing and cross-platform image handling.
Key functions
Example (PNG QR)
var cfg = new QrConfig { Payload = "https://example.com", PixelsPerModule = 20, Format = CodeImageFormat.Png };
byte[] png = CodeGenerator.GenerateQrCode(cfg);
File.WriteAllBytes("qrcode.png", png);
Purpose: create printable and web-friendly QR/barcode assets without System.Drawing.
Function explanation (selected)
Class summary High-performance REST client offering GET/POST/PUT/PATCH/DELETE, JSON (strongly-typed) helpers, multipart/form-data and form-url-encoded posting, and a shared static HttpClient for connection pooling.
Key functions (selected)
Example (Post JSON and parse response)
var result = await RestClient.PostAsJsonAsync<RequestModel, ResponseModel>("https://api.example.com/submit", new RequestModel { Name = "Alice" });
Purpose: reduce HttpClient boilerplate and ensure safe, efficient calls.
Function explanation (selected)
Class summary Comprehensive cryptography and encoding helpers: Base64/Hex, URL-safe Base64, Data Protection API wrappers (Lock/UnLock), MD5/SHA hashing, HMAC, AES-CBC and AES-GCM encryption, BCrypt password hashing, and constant-time comparison.
Key functions (selected)
Example (protect small secret)
string protectedBase64 = Protector.Lock("my-secret-value");
string original = Protector.UnLock(protectedBase64);
string aesCipher = Protector.Encrypt("password-key", "sensitive text");
string decrypted = Protector.Decrypt("password-key", aesCipher);
Security notes: use AesGcm for new development when authenticated encryption is required. Configure Data Protection key storage for multi-instance deployments.
Function explanation (selected)
Class summary Small entry point used during development to exercise library functions. Not required by consumers of the NuGet package.
Scenario: Generate a secure token, protect it, create a QR containing the protected token, export a small Excel report, and email the report with the QR image attached. Log timestamps at each step.
Prerequisites:
Example (console app)
using System;
using System.IO;
using System.Threading.Tasks;
using NeeLib;
class Demo
{
public static async Task Main()
{
// 1) Generate a secure token and timestamp it
string token = Generate.Word(32);
string timestamp1 = DateTime.UtcNow.ToString("o"); // ISO 8601
Console.WriteLine($"[{timestamp1}] Generated token: {token}");
// 2) Protect the token with Data Protection API and produce URL-safe base64
string protectedToken = Protector.Lock(token);
string protectedTokenUrl = Protector.ToBase64Url(protectedToken);
string timestamp2 = DateTime.UtcNow.ToString("o");
Console.WriteLine($"[{timestamp2}] Protected token (URL-safe): {protectedTokenUrl}");
// 3) Create a QR code that contains a verification URL with the protected token
var qrCfg = new QrConfig
{
Payload = $"https://example.com/verify?t={protectedTokenUrl}",
PixelsPerModule = 6,
Format = CodeImageFormat.Png
};
byte[] qrPng = CodeGenerator.GenerateQrCode(qrCfg) ?? Array.Empty<byte>();
File.WriteAllBytes("verify_qr.png", qrPng);
string timestamp3 = DateTime.UtcNow.ToString("o");
Console.WriteLine($"[{timestamp3}] QR code written to verify_qr.png");
// 4) Build a simple DataTable report and export to Excel
var dt = new System.Data.DataTable("Report");
dt.Columns.Add("GeneratedAt");
dt.Columns.Add("TokenPreview");
dt.Rows.Add(DateTime.UtcNow.ToString("o"), token.Substring(0, 8));
byte[] excelBytes = MSOffice.CreateExcelSheet(dt);
File.WriteAllBytes("report.xlsx", excelBytes);
string timestamp4 = DateTime.UtcNow.ToString("o");
Console.WriteLine($"[{timestamp4}] Excel report written to report.xlsx");
// 5) Send an email with report and QR attached (SMTP async)
var email = new EmailModel
{
From = "sender@example.com",
Password = "smtp-password",
Host = Email.GmailHost,
Port = Email.Port_587,
Ssl = Email.GmailSsl,
To = new[] { "recipient@example.com" },
Subject = "Verification Report",
Body = $"Report generated at {DateTime.UtcNow:o}",
BodyType = Email.TEXT,
Filespath = new[] { "report.xlsx", "verify_qr.png" }
};
var smtpResult = await Email.SendFileSMTPAsync(email, cc: false, bcc: false);
string timestamp5 = DateTime.UtcNow.ToString("o");
Console.WriteLine($"[{timestamp5}] Email send result: {smtpResult}");
}
}
Explanation of steps and expected results
At each step the example writes a UTC timestamp (ISO 8601) to the console to demonstrate traceability and ordering.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 net8.0 is compatible. 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 is compatible. 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 is compatible. 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. |
This package is not used by any NuGet packages.
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated | |
|---|---|---|---|
| 2.3.0 | 71 | 5/14/2026 | |
| 2.2.5 | 460 | 4/22/2025 | |
| 2.2.0 | 337 | 1/22/2025 | |
| 2.1.5 | 521 | 10/20/2024 | |
| 2.1.0 | 416 | 10/20/2024 | 2.1.0 is deprecated because it is no longer maintained. |
| 2.0.1 | 372 | 10/20/2024 | 2.0.1 is deprecated because it is no longer maintained. |
| 2.0.0 | 473 | 10/20/2024 | 2.0.0 is deprecated because it is no longer maintained. |
| 1.5.0 | 571 | 3/4/2024 | |
| 1.4.5 | 451 | 3/3/2024 | |
| 1.4.0 | 409 | 3/3/2024 | |
| 1.3.0 | 464 | 3/3/2024 | |
| 1.2.5 | 599 | 1/24/2024 | |
| 1.2.0 | 603 | 1/9/2024 | |
| 1.1.0 | 675 | 11/17/2023 | |
| 1.0.54 | 924 | 10/26/2023 | |
| 1.0.53 | 796 | 10/26/2023 | 1.0.53 is deprecated because it is no longer maintained. |
| 1.0.52 | 783 | 10/26/2023 | 1.0.52 is deprecated because it is no longer maintained. |
| 1.0.51 | 848 | 10/26/2023 | |
| 1.0.50 | 890 | 10/4/2023 | |
| 1.0.44 | 996 | 8/2/2023 |
Version 2.3.0 Update RestClient Class in Post data with Multipart Form Data and Form Url Encoded Data.