One REST API call. Any language. Any platform.
Download this file from your dashboard and place it next to your executable.
[Licentio]
ProgramID=your-program-uuid
ClientID=your-client-uuid
APIKey=your-api-key
Your app also writes a licentio.cache file next to the executable at runtime — do not ship it, it is created on the first successful validation.
Set an Offline grace (days) on the license in your dashboard. On every successful validation the API returns a signed window the client caches, so a user can keep working when their internet — or your server — is temporarily unreachable.
Each client below follows the same algorithm when a request can't reach the server:
IssuedAt, ValidUntil (Unix epoch seconds, UTC) and Token.HMAC-SHA256(APIKey, "ClientID|IssuedAt|ValidUntil") and check it equals the cached Token — proves the window wasn't edited.now < IssuedAt (the clock was set back) or now > ValidUntil (grace expired). Otherwise, run.When you publish a release of the program in Pensum, every validation also returns latest_version and latest_released_at — plus release_notes_url if the program's public changelog is published.
Send the version your app is running as "app_version": "2.3.1" and the response adds update_available (true/false; versions compare as numbers, so 2.10 is newer than 2.9). Show a notice with the notes link when it is true. Apps that ignore these fields keep working exactly as before — they are not part of the offline signature.
Your app can send its crashes to POST https://licentio.dev/errors with the same program_id, client_id and api_key as the license check. Licentio cleans up each stack (line numbers, paths and values go) and groups identical crashes, whichever customer sent them. Each group becomes a bug card on the board that has Error reports turned on (board → Automation); the customers who hit it are added to the card, so they show up in the release plan. If the card is done and the crash comes back in the fixed version, the card reopens.
Fields: app_version, platform (windev, flutter, dotnet, python), os, error_type, message, stack, occurred_at, and optionally context (a small JSON object) and fingerprint (to group reports yourself). At most 64 KB per report and 120 reports per customer per hour.
Every snippet below saves the report to disk first and then sends whatever is pending, so crashes that happen offline arrive on the next start. Send only technical data — no personal data of your users. The license check's app_version also tells you which version each customer runs (Pensum → Errors & versions).
The simplest way to test the API from any terminal.
curl -X POST https://licentio.dev/validate \
-H "Content-Type: application/json" \
-d '{
"program_id": "your-program-uuid",
"client_id": "your-client-uuid",
"api_key": "your-api-key",
"app_version": "2.3.1"
}'
When the license has an offline grace, a valid response also carries the signed window the client caches (issued_at/valid_until are Unix epoch seconds).
{
"valid": true,
"message": "License valid",
"license_type": "EXPIRY_DATE",
"days_remaining": 17,
"warning": true,
"warning_message": "License expires in 17 days",
"offline_days": 7,
"issued_at": 1785484800,
"valid_until": 1786089600,
"offline_token": "3cce096c1eb9...b90ea1",
"offline_message": "Could not reach the license server.",
"latest_version": "2.4.0",
"latest_released_at": "2026-11-24T16:30:00Z",
"release_notes_url": "https://licentio.dev/changelog/Xk3…",
"update_available": true
}
The same call every snippet makes when the app crashes.
curl -X POST https://licentio.dev/errors \
-H "Content-Type: application/json" \
-d '{
"program_id": "your-program-uuid",
"client_id": "your-client-uuid",
"api_key": "your-api-key",
"app_version": "2.3.1",
"platform": "python",
"error_type": "KeyError",
"message": "'date'",
"stack": "Traceback (most recent call last):\n File \"export.py\", line 88, in export\nKeyError: '"'"'date'"'"'"
}'
# → {"ok": true, "group_id": "…", "new_group": true}
Uses NetWebClient (NetTalk) + jFiles. StringTheory only does plain hashes, so the HMAC uses CapeSoft Cryptonite — MakeHMAC(message, secret, hashType, hexEncode), which writes the hex result back into the message object. Add both global extensions.
INCLUDE('StringTheory.inc'),ONCE
INCLUDE('Cryptonite.inc'),ONCE
! --- Group to receive the JSON response ---
element GROUP,NAME('element')
valid BYTE,NAME('valid | boolean')
message STRING(255),NAME('message')
warning_message STRING(255),NAME('warning_message')
offline_token STRING(64),NAME('offline_token')
offline_message STRING(255),NAME('offline_message')
issued_at STRING(20),NAME('issued_at') ! epoch seconds (UTC), kept as text
valid_until STRING(20),NAME('valid_until') ! epoch seconds (UTC), kept as text
END
! --- Windows API: current UTC time ---
SYSTEMTIME GROUP,TYPE
wYear USHORT
wMonth USHORT
wDayOfWeek USHORT
wDay USHORT
wHour USHORT
wMinute USHORT
wSecond USHORT
wMilliseconds USHORT
END
MODULE('api')
GetSystemTime(*SYSTEMTIME),PASCAL,RAW,NAME('GetSystemTime')
END
crypto Cryptonite
stHMAC StringTheory
! ============ On a successful 200 response ============
! (after jFiles has loaded the body into `element`)
IF element.valid = TRUE
! Cache the signed offline window for future offline runs
IF element.offline_token <> ''
PUTINI('Cache','IssuedAt', CLIP(element.issued_at), 'licentio.cache')
PUTINI('Cache','ValidUntil',CLIP(element.valid_until), 'licentio.cache')
PUTINI('Cache','Token', CLIP(element.offline_token), 'licentio.cache')
PUTINI('Cache','Msg', CLIP(element.offline_message),'licentio.cache')
END
END
! ============ CheckOffline — when the server is unreachable ============
CheckOffline PROCEDURE(STRING pClientID, STRING pAPIKey)
sToken STRING(64)
sMyToken STRING(64)
sCanonical STRING(160)
nIssued LONG
nValid LONG
nNow LONG
ut LIKE(SYSTEMTIME)
CODE
IF NOT EXISTS('licentio.cache')
Message('No internet connection and no cached license.')
RETURN FALSE
END
nIssued = GETINI('Cache','IssuedAt','0','licentio.cache')
nValid = GETINI('Cache','ValidUntil','0','licentio.cache')
sToken = GETINI('Cache','Token','','licentio.cache')
! 1) Rebuild the HMAC-SHA256 and compare (proves the window wasn't edited)
sCanonical = CLIP(pClientID) & '|' & nIssued & '|' & nValid
stHMAC.SetValue(sCanonical)
! MakeHMAC(message, secret, hashType, hexEncode) -> the message object holds the result
IF crypto.MakeHMAC(stHMAC, CLIP(pAPIKey), cs:CALG_SHA_256, 1) <> Crypto:OK
Message('Could not verify the cached license.')
RETURN FALSE
END
stHMAC.Lower() ! server sends lowercase hex
sMyToken = stHMAC.GetValue()
IF sMyToken <> CLIP(sToken)
Message('Cached license is corrupt.')
RETURN FALSE
END
! 2) Current UTC time as Unix epoch seconds
GetSystemTime(ut)
nNow = (DATE(ut.wMonth, ut.wDay, ut.wYear) - DATE(1,1,1970)) * 86400 |
+ ut.wHour * 3600 + ut.wMinute * 60 + ut.wSecond
IF nNow < nIssued
Message('The system clock has been set back.') ; RETURN FALSE
END
IF nNow > nValid
Message('Offline grace period expired. Please reconnect.') ; RETURN FALSE
END
Message(GETINI('Cache','Msg','','licentio.cache')) ! your offline message
RETURN TRUE
Uses the native HTTPSend, HashString and INIWrite functions — no external libraries required.
PROCEDURE ValidateLicense() : boolean
sIniPath is string = fExeDir() + "\" + "licentio.ini"
sCachePath is string = fExeDir() + "\" + "licentio.cache"
IF NOT fFileExist(sIniPath) THEN
Error("License configuration file not found.")
RESULT False
END
sProgramID is string = INIRead("Licentio", "ProgramID", "", sIniPath)
sClientID is string = INIRead("Licentio", "ClientID", "", sIniPath)
sAPIKey is string = INIRead("Licentio", "APIKey", "", sIniPath)
sJSON is ANSI string = [
{"program_id":"%1","client_id":"%2","api_key":"%3","machine_id":"%4","app_version":"%5"}
]
sJSON = StringBuild(sJSON, sProgramID, sClientID, sAPIKey, NetMachineName(), ExeInfo(exeVersion))
oRequest is httpRequest
oResponse is httpResponse
oRequest..URL = "https://licentio.dev/validate"
oRequest..Method = httpPost
oRequest..ContentType = "application/json"
oRequest..Content = sJSON
! Try online; on ANY network failure, fall back to the cached offline grace
bNetError is boolean = False
WHEN EXCEPTION IN
oResponse = HTTPSend(oRequest)
DO
bNetError = True
END
IF bNetError OR ErrorOccurred OR oResponse..StatusCode <> 200 THEN
RESULT CheckOffline(sClientID, sAPIKey, sCachePath)
END
vResult is Variant = JSONToVariant(oResponse..Content)
IF NOT vResult.valid..Value THEN
Error("License invalid: " + vResult.message..Value)
RESULT False
END
! Cache the signed offline window (only present if the license enables grace)
sToken is string = vResult.offline_token..Value
IF sToken <> "" THEN
INIWrite("Cache", "IssuedAt", vResult.issued_at..Value, sCachePath)
INIWrite("Cache", "ValidUntil", vResult.valid_until..Value, sCachePath)
INIWrite("Cache", "Token", sToken, sCachePath)
INIWrite("Cache", "Msg", vResult.offline_message..Value, sCachePath)
END
IF vResult.warning..Value THEN Info(vResult.warning_message..Value) END
RESULT True
! --- Offline grace check --------------------------------------------
PROCEDURE CheckOffline(sClientID is string, sAPIKey is string, sCachePath is string) : boolean
IF NOT fFileExist(sCachePath) THEN
Error("No internet connection and no cached license.")
RESULT False
END
nIssuedAt is 8-byte int = Val(INIRead("Cache", "IssuedAt", "0", sCachePath))
nValidUntil is 8-byte int = Val(INIRead("Cache", "ValidUntil", "0", sCachePath))
sToken is string = INIRead("Cache", "Token", "", sCachePath)
sMsg is string = INIRead("Cache", "Msg", "", sCachePath)
! Rebuild the signature with our own API key and compare
sCanonical is string = sClientID + "|" + nIssuedAt + "|" + nValidUntil
bufHash is Buffer = HashString(HA_HMAC_SHA_256, sCanonical, sAPIKey)
sMyToken is string = BufferToHexa(bufHash, WithoutGrouping) // SansRegroupement in the FR IDE
IF sMyToken <> sToken THEN // WLanguage string compare is case-insensitive
Error("Cached license is corrupt.")
RESULT False
END
nNow is 8-byte int = DateTimeToEpoch(DateTimeLocalToUTC(Now()))
IF nNow < nIssuedAt THEN
Error("System clock has been set back.")
RESULT False
END
IF nNow > nValidUntil THEN
Error("Offline grace period has expired. Please reconnect.")
RESULT False
END
Info(sMsg)
RESULT True
! At program startup:
IF NOT ValidateLicense() THEN
EndProgram()
END
One general procedure catches every WLanguage exception (ExceptionChangeParameter with epExecuteProcedureOverall, in the project initialization code). ExceptionInfo(errStack) gives the call stack that groups the reports; errFullDetails travels as context. Compiled with WINDEV 2025.
// ── Project initialization code ────────────────────────────
ExceptionChangeParameter(epExecuteProcedureOverall, LicentioCrashHandler)
LicentioSendPendingErrors() // what was saved while offline
// ── Global procedures (e.g. in a COL_Licentio collection) ──
PROCEDURE LicentioErrorFolder() : string
sFolder is string = SysDir(srLocalAppData) + "\" + fExtractPath(ExeInfo(exeName), fFileName) + "\licentio-errors"
IF NOT fDirectoryExist(sFolder) THEN fMakeDir(sFolder)
RESULT sFolder
PROCEDURE LicentioCrashHandler()
sIniPath is string = fExeDir() + "\licentio.ini"
vContext is Variant
vReport is Variant
vContext.details = ExceptionInfo(errFullDetails)
vReport.program_id = INIRead("Licentio", "ProgramID", "", sIniPath)
vReport.client_id = INIRead("Licentio", "ClientID", "", sIniPath)
vReport.api_key = INIRead("Licentio", "APIKey", "", sIniPath)
vReport.app_version = ExeInfo(exeVersion)
vReport.platform = "windev"
vReport.os = "Windows " + SysWindowsVersion(sysVersionNumber)
vReport.error_type = ExceptionInfo(errCode)
vReport.message = ExceptionInfo(errMessage)
vReport.stack = ExceptionInfo(errStack)
vReport.occurred_at = DateTimeToString(DateTimeLocalToUTC(SysDateTime()), "YYYY-MM-DDTHH:mm:SSZ")
vReport.context = vContext
// Save first (works offline), then try to send everything pending
WHEN EXCEPTION IN
fSaveBuffer(LicentioErrorFolder() + "\err_" + GetGUID(guidRough) + ".json", StringToUTF8(VariantToJSON(vReport, psdMinified)))
LicentioSendPendingErrors()
DO
// never fail inside the crash handler
END
Error("An unexpected error occurred and has been reported. The application will close.")
RESULT opEndProgram
PROCEDURE LicentioSendPendingErrors()
oRequest is httpRequest
oResponse is httpResponse
bDone is boolean
FOR EACH STRING sFile OF fListFile(LicentioErrorFolder() + "\err_*.json", frFile) SEPARATED BY CR
oRequest.URL = "https://licentio.dev/errors"
oRequest.Method = httpPost
oRequest.ContentType = "application/json"
oRequest.Content = fLoadBuffer(sFile)
oRequest.Timeout = 5s
bDone = False
WHEN EXCEPTION IN
oResponse = HTTPSend(oRequest)
// 2xx = received; 4xx other than 429 = it will never be accepted. Either way, drop it.
bDone = (oResponse.StatusCode >= 200 AND oResponse.StatusCode < 500 AND oResponse.StatusCode <> 429)
DO
bDone = False
END
IF bDone THEN fDelete(sFile)
END
Uses the requests library. Install with pip install requests. Standard-library hmac handles the offline check.
import configparser, hmac, hashlib, time, os, socket, sys
import requests
INI, CACHE = "licentio.ini", "licentio.cache"
def _sign(api_key, client_id, issued_at, valid_until):
canonical = f"{client_id}|{issued_at}|{valid_until}"
return hmac.new(api_key.encode(), canonical.encode(), hashlib.sha256).hexdigest()
def validate_license():
cfg = configparser.ConfigParser(); cfg.read(INI)
program_id = cfg["Licentio"]["ProgramID"]
client_id = cfg["Licentio"]["ClientID"]
api_key = cfg["Licentio"]["APIKey"]
try:
data = requests.post("https://licentio.dev/validate", timeout=10, json={
"program_id": program_id, "client_id": client_id,
"api_key": api_key, "machine_id": socket.gethostname(),
"app_version": "2.3.1", # the version of your app
}).json()
except requests.RequestException:
return check_offline(client_id, api_key) # no connection → try grace
if not data["valid"]:
print(f"License invalid: {data['message']}")
return False
# Cache the signed offline window for future offline runs
if data.get("offline_token"):
c = configparser.ConfigParser()
c["Cache"] = {"IssuedAt": str(data["issued_at"]),
"ValidUntil": str(data["valid_until"]),
"Token": data["offline_token"],
"Msg": data.get("offline_message", "")}
with open(CACHE, "w") as f: c.write(f)
if data.get("warning"):
print(f"Warning: {data['warning_message']}")
return True
def check_offline(client_id, api_key):
if not os.path.exists(CACHE):
print("No internet connection and no cached license.")
return False
c = configparser.ConfigParser(); c.read(CACHE)
cache = c["Cache"]
issued_at, valid_until = int(cache["IssuedAt"]), int(cache["ValidUntil"])
now = int(time.time())
if not hmac.compare_digest(_sign(api_key, client_id, issued_at, valid_until), cache["Token"]):
print("Cached license is corrupt."); return False # tampered window
if now < issued_at:
print("System clock has been set back."); return False # anti-rollback
if now > valid_until:
print("Offline grace period has expired. Please reconnect."); return False
print(cache.get("Msg") or "Running offline.")
return True
if not validate_license():
sys.exit(1)
Standard library only. sys.excepthook and threading.excepthook catch what nothing else caught.
# licentio_errors.py — report crashes to Licentio (standard library only)
import configparser, datetime, json, os, pathlib, platform, sys, threading, traceback, urllib.error, urllib.request, uuid
APP_VERSION = "2.3.1" # or importlib.metadata.version("your-app")
URL = "https://licentio.dev/errors"
INI = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "licentio.ini")
QUEUE = pathlib.Path(os.environ.get("LOCALAPPDATA") or pathlib.Path.home() / ".local" / "share") / "YourApp" / "licentio-errors"
def _send(body: bytes) -> bool:
"""True when the report can be dropped: received, or rejected for good."""
req = urllib.request.Request(URL, data=body, headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=5):
return True
except urllib.error.HTTPError as e:
return e.code < 500 and e.code != 429
except OSError:
return False # offline: keep it for later
_lock = threading.Lock()
def send_pending():
with _lock: # startup and a crash may send at the same time
if QUEUE.exists():
for f in sorted(QUEUE.glob("err_*.json")):
if _send(f.read_bytes()):
f.unlink(missing_ok=True)
def report(exc_type, exc, tb):
try:
cfg = configparser.ConfigParser()
cfg.read(INI)
lic = cfg["Licentio"]
body = {
"program_id": lic["ProgramID"], "client_id": lic["ClientID"], "api_key": lic["APIKey"],
"app_version": APP_VERSION, "platform": "python", "os": f"{platform.system()} {platform.release()}",
"error_type": exc_type.__name__, "message": str(exc)[:4000],
"stack": "".join(traceback.format_exception(exc_type, exc, tb))[-32000:],
"occurred_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}
QUEUE.mkdir(parents=True, exist_ok=True)
(QUEUE / f"err_{uuid.uuid4().hex}.json").write_text(json.dumps(body), encoding="utf-8")
send_pending()
except Exception:
pass # never fail inside the crash handler
def install():
"""Call once at startup."""
previous = sys.excepthook
def hook(exc_type, exc, tb):
report(exc_type, exc, tb)
previous(exc_type, exc, tb)
sys.excepthook = hook
threading.excepthook = lambda a: report(a.exc_type, a.exc_value, a.exc_traceback)
threading.Thread(target=send_pending, daemon=True).start() # what was saved while offline
# At startup:
# import licentio_errors; licentio_errors.install()
# Tkinter apps also need: root.report_callback_exception = licentio_errors.report
Uses http and package_info_plus. For an offline grace, port the HMAC check of the C# tab with package:crypto.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
/// Validates the license and says whether a newer release exists.
Future<bool> validateLicense({required String programId, required String clientId, required String apiKey}) async {
final version = (await PackageInfo.fromPlatform()).version;
final r = await http.post(Uri.parse('https://licentio.dev/validate'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'program_id': programId, 'client_id': clientId, 'api_key': apiKey, 'app_version': version}));
final data = jsonDecode(r.body) as Map<String, dynamic>;
if (data['update_available'] == true) {
// Show a notice: data['latest_version'] and data['release_notes_url']
}
return data['valid'] == true;
}
Android, iOS and desktop. FlutterError.onError catches framework errors and PlatformDispatcher.instance.onError the rest. Add http, package_info_plus and path_provider to pubspec.yaml.
// licentio_errors.dart — report crashes to Licentio (Android, iOS, Windows, macOS, Linux)
// pubspec.yaml: http, package_info_plus, path_provider
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
class LicentioErrors {
static const _url = 'https://licentio.dev/errors';
static String _programId = '', _clientId = '', _apiKey = '', _version = '';
/// Call once in main(), after WidgetsFlutterBinding.ensureInitialized().
static Future<void> install({required String programId, required String clientId, required String apiKey}) async {
_programId = programId;
_clientId = clientId;
_apiKey = apiKey;
_version = (await PackageInfo.fromPlatform()).version;
final previous = FlutterError.onError;
FlutterError.onError = (details) {
report(details.exception, details.stack);
previous?.call(details);
};
PlatformDispatcher.instance.onError = (error, stack) {
report(error, stack);
return true;
};
sendPending(); // what was saved while offline
}
static Future<Directory> _queue() async =>
Directory('${(await getApplicationSupportDirectory()).path}/licentio-errors').create(recursive: true);
static Future<void> report(Object error, StackTrace? stack) async {
try {
final message = error.toString();
final trace = stack?.toString() ?? '';
final body = jsonEncode({
'program_id': _programId, 'client_id': _clientId, 'api_key': _apiKey,
'app_version': _version, 'platform': 'flutter',
'os': '${Platform.operatingSystem} ${Platform.operatingSystemVersion}',
'error_type': error.runtimeType.toString(),
'message': message.length > 4000 ? message.substring(0, 4000) : message,
'stack': trace.length > 32000 ? trace.substring(0, 32000) : trace,
'occurred_at': DateTime.now().toUtc().toIso8601String(),
});
final dir = await _queue();
await File('${dir.path}/err_${DateTime.now().microsecondsSinceEpoch}.json').writeAsString(body);
await sendPending();
} catch (_) {} // never fail inside the crash handler
}
static Future<void> _sending = Future.value();
/// One send at a time: startup and a crash may want to send together.
static Future<void> sendPending() => _sending = _sending.then((_) => _sendAll());
static Future<void> _sendAll() async {
try {
final dir = await _queue();
for (final f in dir.listSync().whereType<File>().where((f) => f.path.endsWith('.json'))) {
try {
final r = await http
.post(Uri.parse(_url), headers: {'Content-Type': 'application/json'}, body: await f.readAsString())
.timeout(const Duration(seconds: 5));
if (r.statusCode < 500 && r.statusCode != 429) await f.delete(); // received, or rejected for good
} catch (_) {} // offline: keep it
}
} catch (_) {}
}
}
// main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await LicentioErrors.install(programId: 'your-program-uuid', clientId: 'your-client-uuid', apiKey: 'your-api-key');
runApp(const MyApp());
}
Uses HttpClient, System.Text.Json and HMACSHA256 — all in the standard library.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
static class Licentio
{
const string Ini = "licentio.ini", Cache = "licentio.cache";
static Dictionary<string,string> ReadIni(string path, string section)
{
var d = new Dictionary<string,string>(); var cur = "";
foreach (var raw in File.ReadAllLines(path))
{
var line = raw.Trim();
if (line.StartsWith("[") && line.EndsWith("]")) cur = line[1..^1];
else if (cur == section && line.Contains('='))
{ var i = line.IndexOf('='); d[line[..i].Trim()] = line[(i+1)..].Trim(); }
}
return d;
}
static string Sign(string apiKey, string clientId, long issuedAt, long validUntil)
{
using var h = new HMACSHA256(Encoding.UTF8.GetBytes(apiKey));
var canonical = $"{clientId}|{issuedAt}|{validUntil}";
return Convert.ToHexString(h.ComputeHash(Encoding.UTF8.GetBytes(canonical))).ToLowerInvariant();
}
public static bool Validate()
{
var cfg = ReadIni(Ini, "Licentio");
string programId = cfg["ProgramID"], clientId = cfg["ClientID"], apiKey = cfg["APIKey"];
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
var body = JsonSerializer.Serialize(new {
program_id = programId, client_id = clientId,
api_key = apiKey, machine_id = Environment.MachineName,
app_version = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Version?.ToString() });
var resp = http.PostAsync("https://licentio.dev/validate",
new StringContent(body, Encoding.UTF8, "application/json")).Result;
var data = JsonSerializer.Deserialize<JsonElement>(resp.Content.ReadAsStringAsync().Result);
if (!data.GetProperty("valid").GetBoolean())
{
Console.WriteLine("License invalid: " + data.GetProperty("message").GetString());
return false;
}
if (data.TryGetProperty("offline_token", out var tok) && tok.ValueKind == JsonValueKind.String)
File.WriteAllText(Cache,
"[Cache]\n" +
$"IssuedAt={data.GetProperty("issued_at").GetInt64()}\n" +
$"ValidUntil={data.GetProperty("valid_until").GetInt64()}\n" +
$"Token={tok.GetString()}\n" +
$"Msg={data.GetProperty("offline_message").GetString()}\n");
return true;
}
catch (Exception) // no connection → try grace
{
return CheckOffline(clientId, apiKey);
}
}
static bool CheckOffline(string clientId, string apiKey)
{
if (!File.Exists(Cache)) { Console.WriteLine("No connection and no cached license."); return false; }
var c = ReadIni(Cache, "Cache");
long issuedAt = long.Parse(c["IssuedAt"]), validUntil = long.Parse(c["ValidUntil"]);
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (Sign(apiKey, clientId, issuedAt, validUntil) != c["Token"])
{ Console.WriteLine("Cached license is corrupt."); return false; }
if (now < issuedAt) { Console.WriteLine("System clock has been set back."); return false; }
if (now > validUntil) { Console.WriteLine("Offline grace period has expired. Please reconnect."); return false; }
Console.WriteLine(c.TryGetValue("Msg", out var m) ? m : "Running offline.");
return true;
}
static void Main() { if (!Validate()) Environment.Exit(1); }
}
Standard library only. Hooks AppDomain.UnhandledException and TaskScheduler.UnobservedTaskException; add the WinForms or WPF line for crashes on the UI thread. The version comes from the assembly (set <Version> in the .csproj).
// LicentioErrors.cs — report crashes to Licentio (.NET 6 or later, standard library only)
using System;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
public static class LicentioErrors
{
const string Url = "https://licentio.dev/errors";
static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(5) };
static readonly string Queue = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YourApp", "licentio-errors");
static readonly SemaphoreSlim Sending = new(1, 1); // startup and a crash may send at the same time
static string programId = "", clientId = "", apiKey = "";
// Call once at startup, with the values of licentio.ini.
public static void Install(string program, string client, string key)
{
(programId, clientId, apiKey) = (program, client, key);
AppDomain.CurrentDomain.UnhandledException += (_, e) => Report(e.ExceptionObject as Exception);
TaskScheduler.UnobservedTaskException += (_, e) => { Report(e.Exception); e.SetObserved(); };
// WinForms: Application.ThreadException += (_, e) => Report(e.Exception);
// WPF: Application.Current.DispatcherUnhandledException += (_, e) => Report(e.Exception);
_ = Task.Run(SendPendingAsync); // what was saved while offline
}
public static void Report(Exception? ex)
{
if (ex == null) return;
try
{
var body = JsonSerializer.Serialize(new
{
program_id = programId, client_id = clientId, api_key = apiKey,
app_version = Assembly.GetEntryAssembly()?.GetName().Version?.ToString(),
platform = "dotnet", os = RuntimeInformation.OSDescription,
error_type = ex.GetType().FullName, message = Cut(ex.Message, 4000),
stack = Cut(ex.ToString(), 32000), occurred_at = DateTime.UtcNow.ToString("o"),
});
Directory.CreateDirectory(Queue);
File.WriteAllText(Path.Combine(Queue, $"err_{Guid.NewGuid():N}.json"), body);
SendPendingAsync().Wait(TimeSpan.FromSeconds(10)); // the process may be ending
}
catch { /* never fail inside the crash handler */ }
}
public static async Task SendPendingAsync()
{
if (!Directory.Exists(Queue)) return;
await Sending.WaitAsync().ConfigureAwait(false);
try
{
foreach (var file in Directory.GetFiles(Queue, "err_*.json"))
{
try
{
using var content = new StringContent(File.ReadAllText(file), Encoding.UTF8, "application/json");
var code = (int)(await Http.PostAsync(Url, content).ConfigureAwait(false)).StatusCode;
if (code < 500 && code != 429) File.Delete(file); // received, or rejected for good
}
catch { /* offline: keep it */ }
}
}
finally { Sending.Release(); }
}
static string Cut(string s, int max) => s.Length <= max ? s : s[..max];
}
// At startup (Program.Main), with the values of licentio.ini:
// LicentioErrors.Install(programId, clientId, apiKey);
Ready to protect your software?
Get Started Free