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)