NeeLib 2.3.0

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

NeeLib

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

  • Project: NeeLib
  • License: MIT (see LICENSE.txt)

Project Introduction

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:

  • Reduces boilerplate and accelerates development
  • Uses secure, modern primitives (RandomNumberGenerator, AesGcm, DataProtection, BCrypt)
  • Is optimized for performance (zero-allocation patterns, stream-based JSON, static HttpClient)
  • Is cross-platform (ImageSharp & ZXing for images instead of System.Drawing)

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.


Prerequisites & Setup

  • .NET 10 SDK
  • Register services in your ASP.NET Core app when using DI-dependent features:
// 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:

  • For sending email via Microsoft Graph, configure Azure AD credentials (TenantId, ClientId, Client Secret).
  • The library targets .NET 10 and uses modern APIs (AesGcm, RandomNumberGenerator, System.Text.Json where appropriate).

Class Details and Function Examples

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.

Alerts

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

  • AlertBox(string title, string message, string icon, bool toast)

Function explanation

  • AlertBox: returns a compact JSON string representing alert configuration. Use on server to emit payloads consumed by front-end notification components.

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.


CacheMemory

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

  • ConfigCache(TimeSpan sliding, TimeSpan absolute, long size)
    • Explanation: returns MemoryCacheEntryOptions configured with sliding and absolute expirations and estimated size.
  • WriteCache(string key, string value, MemoryCacheEntryOptions options)
    • Explanation: writes string value only if key does not exist; prevents overwrites.
  • ReadCache(string key)
    • Explanation: returns cached string or null if missing.
  • WriteCache<T>(string key, T value, MemoryCacheEntryOptions options)
    • Explanation: generic variant to store any object
  • ReadCache<T>(string key)
    • Explanation: typed read; returns default(T) if not present
  • GetOrSetCacheAsync<T>(string key, Func<Task<T>> factory, MemoryCacheEntryOptions options)
    • Explanation: atomic async factory to prevent concurrent requests from triggering duplicate work

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.


Preference

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)

  • SetString/GetString/ClearString
    • Explanation: store, retrieve, or clear plain string values
  • SetBool/GetBool/ClearBool
    • Explanation: boolean flags storage
  • SetInt/GetInt/ClearInt
    • Explanation: integer values
  • SetFloat/GetFloat/ClearFloat
    • Explanation: float values
  • SetDouble/GetDouble/ClearDouble
    • Explanation: double values

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.


SessionCookies

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

  • WriteCookie(string key, string value, DateTime expire)
    • Explanation: appends an HttpOnly, Secure cookie with SameSite=strict and base64-encoded value
  • ReadCookie(string key)
    • Explanation: returns decoded cookie value or empty string
  • DeleteCookie(string key)
    • Explanation: removes cookie from response
  • WriteCookieObject<T>(string key, T value, DateTime expire)
    • Explanation: serializes object to JSON then stores as cookie
  • ReadCookieObject<T>(string key)
    • Explanation: reads cookie and deserializes JSON to T
  • WriteSessionString/ReadSessionString/DeleteSession/ClearSession
    • Explanation: session string lifecycle helpers (base64 encoded for strings)
  • WriteSessionObject<T>/ReadSessionObject<T>
    • Explanation: stores and retrieves JSON-serialized objects in session

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.


Email

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

  • SendTextSMTP/SendFileSMTP (sync) — legacy
    • Explanation: synchronous SMTP send; blocks calling thread (use async in web apps)
  • SendTextSMTPAsync/SendFileSMTPAsync (async) — recommended
    • Explanation: async SMTP send using SmtpClient.SendMailAsync
  • SendTextApi/SendFileApi (Microsoft Graph)
    • Explanation: sends email via GraphServiceClient using ClientSecretCredential
  • GetUsers (sync) and GetUsersAsync
    • Explanation: list Graph users; prefer GetUsersAsync to avoid deadlocks

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.


FilesIO

Class summary File and directory utilities with async I/O, base64 file creation, and safe directory management.

Key functions

  • CreateDir(string dirPath)
    • Explanation: creates directory if missing; returns string status
  • CreateFile(string filePath, string data) (async)
    • Explanation: writes text content asynchronously
  • CreateFile(string filePath, byte[] data) (async)
    • Explanation: writes binary content asynchronously
  • CreateFileToBase64(string filePath, string base64string) (async)
    • Explanation: decodes base64 and writes binary file
  • Other helpers for deletes and existence checks

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.


Generate

Class summary Secure random generation helpers that use RandomNumberGenerator for cryptographic security and zero-allocation string creation.

Public functions

  • Word(int length) — alphanumeric
    • Explanation: returns secure alphanumeric string; prevents leading '0' when requested
  • Number(int length) — numeric string
    • Explanation: returns secure numeric string of requested length
  • NumberAsInt(int length) — int
    • Explanation: returns secure integer in range for given digits (1-9)
  • NumberAsLong(int length) — long
    • Explanation: returns secure long for lengths up to 18 digits

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.


GetDateTime

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

  • LONG_TIME1, LONG_TIME2, ISO_8601, etc.
    • Explanation: predefined date/time format strings for consistent formatting across the app. Use these constants to avoid magic format strings.
  • WindowsTimeZoneIds (collection)
    • Explanation: common Windows timezone identifier constants to be used when converting or displaying localized times.

Note: Timezone IDs are Windows standard; if running cross-platform you may need mapping to IANA names.


MSOffice

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

  • CreateExcelSheet(DataTable)
  • CreateExcelSheets(List<DataTable>)
  • CreateExcelSheet<T>(IEnumerable<T> data)
  • ExportExcelSheet / ExportExcelSheets (FileContentResult)

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)

  • CreateExcelSheet(DataTable)
    • Explanation: converts a DataTable into an in-memory XLSX and returns the byte[] ready to be written or returned from a controller.
  • CreateExcelSheet<T>(IEnumerable<T>)
    • Explanation: serializes a sequence of POCOs into an XLSX worksheet using property names as headers.
  • ExportExcelSheet / ExportExcelSheets
    • Explanation: convenience helpers that return FileContentResult for direct use in ASP.NET Core controller actions.

Pdf

Class summary HTML minifier and HTML→PDF conversion via iText7. Includes resource-safe file creation.

Key functions

  • Minifier(string filePath) : Task<string>
  • Create(string baseUri, string htmlString, string filePath) : bool

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)

  • Minifier(string filePath)
    • Explanation: reads an HTML template and removes unnecessary whitespace/comments to reduce PDF size and improve rendering determinism.
  • Create(string baseUri, string htmlString, string filePath)
    • Explanation: renders provided HTML (resolving relative resources against baseUri) into a PDF file saved at filePath using iText7.

CodeGenerator (QR & Barcode)

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

  • GenerateQrCode(QrConfig config) : byte[]? (raster)
  • GenerateQrCodeSvg(QrConfig config) : string? (SVG)
  • GenerateBarcode(BarcodeConfig config) : byte[]?

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)

  • GenerateQrCode(QrConfig config)
    • Explanation: produces a raster image (PNG/JPG/GIF) from the provided configuration, optionally compositing a logo and returning image bytes.
  • GenerateQrCodeSvg(QrConfig config)
    • Explanation: generates a scalable SVG representation of the QR payload suitable for inline HTML or vector print output.
  • GenerateBarcode(BarcodeConfig config)
    • Explanation: creates a 1D barcode image (e.g., CODE128) as raw bytes for inclusion in documents or labels.

RestClient

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)

  • Get/GetBytes/GetStream
  • Post/PostBytes/PostStream
  • PostFormUrlEncoded/PostFormData
  • GetFromJsonAsync<T>
  • PostAsJsonAsync<TRequest,TResponse>

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)

  • Get(url): performs GET and returns string content.
    • Explanation: use for small JSON/plain-text responses where buffering is acceptable.
  • GetBytes(url): returns raw bytes (useful for images/files).
    • Explanation: stream-optimized for binary payloads.
  • GetStream(url): returns Stream for large responses.
    • Explanation: avoids buffering large responses in memory.
  • PostAsJsonAsync<TRequest,TResponse>(url, request): post JSON and parse typed response.
    • Explanation: serializes request using System.Text.Json and deserializes response to TResponse.
  • PostFormData(url, multipart): posts multipart/form-data.
    • Explanation: use for file uploads or complex form payloads.

Protector

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)

  • ToBase64/FromBase64, ToBase64Url/FromBase64Url
  • Lock(string)/UnLock(string) // Data Protection API
  • MD5Hash / SHA256Hash / SHA512Hash
  • HMACSHA256 / HMACSHA512
  • Encrypt/Decrypt (AES-CBC, random IV prepended)
  • EncryptGcm/DecryptGcm (AES-GCM)
  • HashPassword / VerifyPassword (BCrypt Enhanced)
  • SecureEquals / GenerateSecureRandomString

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)

  • ToBase64/FromBase64
    • Explanation: encode/decode binary or text to standard Base64 strings.
  • ToBase64Url/FromBase64Url
    • Explanation: produce URL-safe Base64 (replace +/ with -_) and trim padding.
  • Lock/UnLock
    • Explanation: wrapper around ASP.NET Core Data Protection to persist small secrets tied to application keys.
  • Encrypt/Decrypt
    • Explanation: AES-CBC with random IV prepended to ciphertext; suitable for legacy compatibility but not for new data.
  • EncryptGcm/DecryptGcm
    • Explanation: AES-GCM authenticated encryption; use for new scenarios requiring integrity protection.
  • HashPassword/VerifyPassword
    • Explanation: BCrypt-based password hashing utilities with configurable cost factor.
  • SecureEquals
    • Explanation: constant-time comparison to mitigate timing attacks when comparing secrets.

Program (test harness)

Class summary Small entry point used during development to exercise library functions. Not required by consumers of the NuGet package.


Practical Use Case Example — End-to-End

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:

  • ASP.NET Core or console app with access to NeeLib
  • SMTP credentials if using SMTP sample

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

  1. Generate a cryptographically secure token and log the timestamp.
  2. Protect the token with the library's Data Protection wrapper and produce a URL-safe form so it can be embedded into a verification link.
  3. Generate a QR image pointing to a verification URL and save it to disk.
  4. Produce a one-row Excel report and save it as report.xlsx.
  5. Send an email with both the report and QR image attached using SMTP async API; log the send result.

At each step the example writes a UTC timestamp (ISO 8601) to the console to demonstrate traceability and ordering.


Recommendations & Best Practices

  • Use async APIs in ASP.NET Core (SendTextSMTPAsync, GetOrSetCacheAsync, etc.).
  • Configure Data Protection key storage for multi-instance apps (Azure Blob, Redis, or key vault).
  • Prefer AES-GCM (EncryptGcm/DecryptGcm) for new symmetric encryption use-cases.
  • Keep secrets (SMTP passwords, Azure client secrets) in secure stores (Azure Key Vault, user secrets, environment variables).

Product Compatible and additional computed target framework versions.
.NET 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 is compatible.  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 is compatible.  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.

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
2.3.0 0 5/14/2026
2.2.5 385 4/22/2025
2.2.0 324 1/22/2025
2.1.5 511 10/20/2024
2.1.0 407 10/20/2024 2.1.0 is deprecated because it is no longer maintained.
2.0.1 363 10/20/2024 2.0.1 is deprecated because it is no longer maintained.
2.0.0 464 10/20/2024 2.0.0 is deprecated because it is no longer maintained.
1.5.0 558 3/4/2024
1.4.5 439 3/3/2024
1.4.0 398 3/3/2024
1.3.0 454 3/3/2024
1.2.5 587 1/24/2024
1.2.0 591 1/9/2024
1.1.0 670 11/17/2023
1.0.54 915 10/26/2023
1.0.53 790 10/26/2023 1.0.53 is deprecated because it is no longer maintained.
1.0.52 776 10/26/2023 1.0.52 is deprecated because it is no longer maintained.
1.0.51 844 10/26/2023
1.0.50 886 10/4/2023
1.0.44 992 8/2/2023
Loading failed

Version 2.3.0 Update RestClient Class in Post data with Multipart Form Data and Form Url Encoded Data.