C# SDK
The C# SDK is a .NET 8 wrapper around the C SDK, which in turn is the stable interface of the Rust SDK. It has the same calls, states and error codes, and speaks protocol version 1. Source: sdks/dotnet/.
Pre-release. Versions
0.x.y-alpha.nare test versions and not meant for production.LicenseClient.IsPrereleaseistruefor them. The package nameLicenseSdkis provisional.
Get it
- Package: one NuGet package,
LicenseSdk, for .NET 8 or newer. It contains the managed library and the native library per platform underruntimes/<rid>/native/; .NET picks the right one at run time. It is not published yet. Build it withsdks/dotnet/pack.sh(writes todist/dotnet/) and add that folder as a local package source. Signed releases contain the package and an SBOM. - Platforms: the package holds the native libraries it was packed with. Without arguments
pack.shbuilds the one for the current machine; libraries for other systems come from the prebuilt C SDK packages:pack.sh linux-x64=<dir> win-x64=<dir> osx-arm64=<dir>. - Native AOT and trimming: supported. The SDK uses source-generated interop (
LibraryImport) and no reflection.
Quickstart
using LicenseSdk;
using var client = new LicenseClient(new LicenseOptions
{
ProductId = "prod_01J...",
Environment = LicenseEnvironment.Live,
ApiBase = "https://...", // your Client API base URL
AppVersion = "1.4.0",
PublicKeys = { "k4.public...." }, // from the dashboard
});
// At every start: check locally, no network needed.
LicenseStatus status;
try
{
status = client.Check();
}
catch (LicenseException e) when (e.Code == "not_activated")
{
try
{
status = await client.ActivateAsync(keyFromUser);
}
catch (LicenseException failed)
{
ShowActivationScreen(failed.Code);
return;
}
}
using (status)
{
var pro = status.Has("pro");
var seats = status.Limit("seats"); // null if the plan has no such limit
}
Start() combines both steps for app start: it checks locally and, if a token is stored, renews it in the background. The app can continue on the local result at once.
var start = client.Start();
using var renewal = start.Renewal; // null if nothing was stored
if (start.Status is { } local) { /* use it now */ }
if (renewal is not null)
{
try { using var fresh = await renewal.WaitAsync(); }
catch (LicenseException e) when (e.IsTransient) { /* offline: keep the local result */ }
}
Disposing a renewal without awaiting it lets it finish on its own, which is the usual case. The renewal waits for a random point in the token's window, usually hours away, and retries on its own after network failures and rate_limited while the token is usable offline (when the SDK renews). Disposing the client ends a waiting renewal.
Calls
| Call | Network | What it does |
|---|---|---|
Check() |
No | Verifies the stored license token: signature, product, environment, clock, offline end, device. Use it at every start and before gated features |
Start() |
Background | Check() now, then a renewal on a background thread |
ActivateAsync(key, deviceName) |
Yes | Activates this device. The only call that reads hardware features for the first time. The device name comes from the user or is null |
SignInAsync(email, password, totpCode) |
Yes | Signs the end customer in with their account at your company, for products with identity mode account or both (protocol section 6.3). Your app asks for email and password; the SDK sends them once and keeps neither. Returns an account valid for 10 minutes, kept in memory only. Error code totp_required: ask for the six digits of the authenticator app and call again with the code. Wrong email, password or code give invalid_credentials, five failures in a row rate_limited. Reads no hardware. Returns an Account (ExpiresAt, IDisposable) |
ActivateWithAccountAsync(account, deviceName) |
Yes | Activates this device with the account's license for this product, like activate with a key. invalid_credentials means the account expired or the password changed: sign in again |
ActivateWithUserTokenAsync(userToken, deviceName) |
Yes | Activates this device for a user of your own account system, with a user token your backend signed. It sends the token once and keeps it nowhere; invalid_credentials means the token expired or does not verify, ask your backend for a new one. How your backend signs it: protocol section 6.5 |
ValidateAsync() |
Yes | Renews the token. Due when the state is TokenState.Grace, and at least once a day |
HeartbeatAsync() |
Yes | Reports a running session, returns the time until the next heartbeat |
DeactivateAsync() |
Yes | Frees this device's activation and deletes the stored token |
OfflineRequest(deviceName) |
No | Starts an offline activation. Returns the request code to show as text or QR code. Reads hardware features like ActivateAsync |
ImportOffline(file) |
No | Imports the license file issued for the pending request and stores its token |
RevocationsSeq() |
No | Sequence number of the revocation list this device holds, or null |
RemoteConfigAsync() |
Yes | Fetches the remote config of the license and keeps the values the schema of ConfigSchema allows |
CachedRemoteConfig() |
No | The last remote config answer while the stored token passes Check(), or null |
Calls with network run on the thread pool. A CancellationToken stops waiting, not the request itself; the request ends at the latest after the transport's timeout. A client is thread-safe; calls on one client run one after another.
A LicenseStatus gives State, ExpiresAt, OfflineUntil, LicenseExpiresAt (null for perpetual licenses), LicenseGraceUntil (end of the grace period once the term has ended, else null), LicenseId, ActivationId, Channel (release channel, for example beta, else null), entitlements (Has, Limit, Variant) and all claims as JSON (ClaimsJson). Dispose it when done, or leave it to the garbage collector.
Remote config
var client = new LicenseClient(new LicenseOptions
{
// ...
ConfigSchema = File.ReadAllText("config-schema.json"), // from GET /v1/products/{id}/config-schema
});
var config = await client.RemoteConfigAsync(); // or client.CachedRemoteConfig() offline, null if none
var dark = config.GetBoolean("dark_mode") ?? false;
var maxProjects = config.GetInteger("max_projects") ?? 5;
GetNumber, GetText, Keys(), Json, Dropped, Omitted and ServerTime complete the class. Only values the schema allows reach the app; the keys of the others are listed as dropped. Keys the server left out because the answer would have been too large are listed as omitted. What the schema may contain and how the cache works is explained in the Rust SDK.
Approved builds
If your product checks builds (build_check in the product settings), tell the client the SHA-256 of the program you ship:
var options = new LicenseOptions
{
// ...
BuildDigest = LicenseClient.BuildDigestOf(typeof(Program).Assembly),
};
BuildDigestOf hashes the file of your main assembly, not the .NET runtime; in a single-file app it hashes the executable. Register the digest of that same file. LicenseClient.BuildDigestOfFile(path) hashes any other file; both throw config_invalid if the file cannot be read.
The SDK then sends it as build with validate, heartbeat, update checks, remote config and downloads (protocol, section 6.8). In your build pipeline, register the digest of the same file for its release and platform with POST /v1/releases/{id}/builds (sha256sum of the shipped file). With build_check set to deny, a build the server does not know gets an empty remote config and no updates; with flag it is only recorded. The license keeps working either way. The digest is what the device reports: it catches a patched program that still runs the SDK unchanged, not one whose author also patches the digest.
Updates
CheckUpdateAsync(language) asks whether a newer release is published for this device's channel and platform (protocol, section 6.4) and returns null when the app is current:
var update = await client.CheckUpdateAsync("en");
if (update is not null)
{
Console.WriteLine($"Version {update.Version} is available.");
if (update.Notes is { } notes) Console.WriteLine(notes); // plain text, never HTML
}
UpdateInfo also has Channel, PublishedAt, NotesLanguage, NotesTruncated and Required. The stored token stays as it is.
If the release has a file for this platform, ask for a short-lived link and fetch it (protocol, section 6.9):
if (update?.File is not null)
{
using var download = await client.RequestDownloadAsync(update.Version);
if (download is not null)
{
var dest = Path.Combine(Path.GetTempPath(), download.File.Name);
await download.FetchAsync(dest); // checks size and SHA-256
// Hand the file to your updater. The SDK never runs it.
}
}
FetchAsync saves the bytes to a temporary file next to the destination and gives the file its final name only once size and SHA-256 match; an encrypted file (Rust SDK) is decrypted first. It fails with file_mismatch (kind verify) if the file does not match, server_unreachable if the link fails or has expired (ask for a new one), and storage_failed if the destination cannot be written. RequestDownloadAsync gives null if the server offers no file of that version to this device; with release keys, only files your signed list names are accepted. Fetching the file yourself is possible with the link (Url) and the size and SHA-256 of the file, but not for encrypted files.
- Installing, checking the installation and rolling back are the job of your updater. The SDK never runs anything it gets.
requiredis true when the running version was blocked or is below the minimum version: install that release before the app carries on.validatethen refuses withversion_outdated; the update check still works.- After installing, report the outcome from the version that runs then:
await client.ReportUpdateAsync(version, rolledBack: false)when the new version started,truewhen your updater went back to the earlier one. A rolled-back release is not offered to this device again, and too many rollbacks pause the rollout for every device (protocol, section 6.10).
To make sure not even a compromised server can offer a foreign, older or revoked version, sign your release lists in your pipeline as described in the Rust SDK and embed both public keys:
var options = new LicenseOptions
{
// ...
ReleaseKeys = { "k4.public.…active…", "k4.public.…reserve…" },
};
From then on the update check accepts only versions the newest list names and does not revoke, never one older than the running app, and fails with token_mismatch otherwise (key_unknown while no list has arrived yet). ReleaseListSeq() gives the sequence number of the newest list the client accepted.
Assets
Files outside releases, such as models or content packs: ListAssetsAsync(language) returns the AssetInfo records this license may fetch, RequestAssetDownloadAsync(name) an AssetDownload or null, and its FetchAsync(dest) saves and checks the file like LicenseDownload.FetchAsync. See Assets for visibility, groups and an example.
Usage quotas
An entitlement of the plan with an integer value, such as "exports": 1000, is a quota for the whole term of the license. await client.ReportUsageAsync("exports", 1, reportId) reports what this device used and returns a UsageGrant with Counted, Used, Limit and Remaining (protocol, section 6.15). The same report_id counts once, so send it again with the same ID when an answer got lost; counted is then false. A report past the quota fails with quota_exhausted (LicenseException, kind server), counts nothing and keeps the stored license token. Vendors grant more units through the Management API.
Proxy calls
await client.CallProxyAsync("weather", "{\"city\":\"Berlin\"}") calls an endpoint of yours through the platform, so its URL and credentials never ship in your app (protocol, section 6.16). It returns a ProxyResult with Target, Status and Body (a JsonElement) of the endpoint's answer, or Failure (timeout, unreachable, response_too_large, response_invalid); null if the license may not call a target of that name. The body is optional. Set up the target in the Management API; your endpoint gets license, activation and plan with each call, signed like a webhook. A target name the SDK refuses (1 to 100 of a-z, 0-9, ., _, -) or a body that is not a JSON object or array of at most 8 KiB fails with config_invalid before anything is sent. The call needs an activation and keeps the stored license token.
Remote actions
Set ActionSchema in LicenseOptions to the action definitions your app accepts, the answer of GET /v1/products/{id}/remote-action-types. await client.RemoteActionsAsync() then returns the actions sent to this device, each a RemoteAction with Id, Name, Params (a JsonElement object), SentBy (vendor or customer), IssuedAt and ExpiresAt (protocol, section 6.17). Each action comes once and the list holds up to 20, oldest first; call again until it is empty. The SDK drops actions with an unknown name, parameters that do not fit your definitions or an expiry in the past. Without an action schema the call fails with config_invalid, and a schema the SDK cannot use fails when the client is created. The call needs an activation and keeps the stored license token. See Remote actions.
Crash reports
CrashReporter queues crash and error reports on disk, LicenseClient.SendCrashReportsAsync sends them, and InstallUnhandledExceptionHandler turns unhandled exceptions into crash reports with their stack. Off until your app creates a reporter. See Crash and error reports.
Modules
ModuleRuntime runs WebAssembly modules you signed with your release key, in a sandbox without files, network or processes, so you can change logic such as a quote without a release. See Modules.
Devices without internet
var request = client.OfflineRequest("Lab PC 3"); // show as text and QR code
// Later, with the content of the license file (.lic):
using var status = client.ImportOffline(File.ReadAllText("license.lic"));
// From now on Check() works without network, until the file's end.
The file works only on the device that made the request and only for that request. A changed file fails with signature_invalid, a file from another device with device_mismatch or nonce_mismatch. What offline licenses mean for revocation and refunds is explained in the Rust SDK.
Errors
Every failure is a LicenseException. Decide on Code, the same code as in every SDK, for example not_activated, license_revoked, token_expired, server_unreachable, storage_failed, config_invalid (full list in protocol section 7). The message is English text for logs, never for end users.
Kindgroups the codes:NotActivated,Server,Verify,Unreachable,Storage,Config,InvalidArgument,Internal.IsTransientistruewhen trying again later can help;RetryAftergives the wait time the server sent.internal_erroris a bug in the SDK. Please report it.
The constructor throws with kind Config for an unusable configuration, for example a malformed public key or a plain http:// URL other than localhost.
Offline behavior is that of the Rust SDK: without a usable answer a call fails with server_unreachable, and the stored token keeps working until its offline end.
Storage and transport
By default the client uses the operating system's secure storage under <product_id>.<environment> and HTTPS with a 10 second timeout.
- Own storage (headless Linux, containers): implement
ILicenseStore(Load,Save,Remove) and setLicenseOptions.Store. Protect it like a password store: it holds the device secret. - Own transport (proxies, an
HttpClientyou already configure): implementILicenseTransport.Post(url, body)and setLicenseOptions.Transport. Return HTTP error statuses as aTransportReply; throw only if no answer arrived.
Both are called from any thread, never at the same time for the same client. An exception in your implementation never crosses into the native library; the SDK turns it into storage_failed or server_unreachable. The client keeps your objects alive until it is disposed.
Security properties
As for the Rust SDK: public keys only, no secret in the app, no plain http:// except for localhost, no code from the server is ever run. The package contains no test hooks; those exist only in a native library built with the cargo feature test-hooks, which the SDK's own tests use.