Activation ties a license key to one computer and returns an instance.id. Validation then sends it on each launch. This page covers the C# specifics: reading the machine id on three platforms, binding snake_case JSON to records, and the null activation_limit of an unlimited license. The C# code in this guide was not compiled or run, because no .NET SDK was available.
A fingerprint
The API accepts an optional fingerprint, up to 200 characters. With one, activating again from the same computer returns the same seat and updates its name. Without one, each reinstall takes another seat. Read the operating system’s id and hash it with a constant that belongs to your app, so the value you send cannot be matched to anything outside it:
using System.Diagnostics;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;
public static class Device
{
private const string Salt = "com.example.inkwell"; // a constant of your own
public static string? Fingerprint()
{
var id = MachineId();
return id is null ? null : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{Salt}:{id}"))).ToLowerInvariant();
}
private static string? MachineId()
{
try
{
if (OperatingSystem.IsWindows()) return WindowsGuid();
if (OperatingSystem.IsMacOS()) return MacUuid();
foreach (var path in new[] { "/etc/machine-id", "/var/lib/dbus/machine-id" })
if (File.Exists(path) && File.ReadAllText(path).Trim() is { Length: > 0 } id) return id;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) { }
return null;
}
[SupportedOSPlatform("windows")]
private static string? WindowsGuid()
{
using var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); // same value for 32 and 64-bit builds
using var key = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography");
return key?.GetValue("MachineGuid") as string;
}
private static string? MacUuid()
{
using var p = Process.Start(new ProcessStartInfo("/usr/sbin/ioreg", "-rd1 -c IOPlatformExpertDevice")
{ RedirectStandardOutput = true, UseShellExecute = false })!;
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit(5000);
return Regex.Match(output, "\"IOPlatformUUID\" = \"([^\"]+)\"") is { Success: true } m ? m.Groups[1].Value : null;
}
}
The result is 64 hex characters. Environment.MachineName is a good instance_name, because it is what the customer recognizes on the device page. If the id cannot be read, send no fingerprint. Activation still works, and the price is a seat per reinstall.
Activate
JsonNamingPolicy.SnakeCaseLower binds the reply’s snake_case names to C# properties. activation_limit is null for an unlimited license, so it is an int?:
using System.Net.Http.Json;
using System.Text.Json;
public enum ActivationKind { Activated, LimitReached, Refused, Unavailable }
public sealed record Activation(ActivationKind Kind, string? InstanceId = null, string? Token = null,
string? Reason = null, int Used = 0, int Limit = 0, TimeSpan? RetryAfter = null);
public sealed partial class LicenseClient
{
private static readonly JsonSerializerOptions Snake = new(JsonSerializerDefaults.Web)
{ PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
private sealed record LicenseInfo(int? ActivationUsage, int? ActivationLimit);
private sealed record InstanceInfo(string? Id);
private sealed record ActivateReply(string? Error, string? Token, InstanceInfo? Instance, LicenseInfo? LicenseKey);
public async Task<Activation> ActivateAsync(string key, CancellationToken ct = default)
{
var body = new Dictionary<string, string> { ["license_key"] = key, ["instance_name"] = Environment.MachineName };
if (Device.Fingerprint() is { } fp) body["fingerprint"] = fp;
try
{
using var response = await Http.PostAsJsonAsync("v1/licenses/activate", body, ct);
ActivateReply? r = null;
try { r = await response.Content.ReadFromJsonAsync<ActivateReply>(Snake, ct); } catch (JsonException) { }
switch ((int)response.StatusCode)
{
case 200 when r?.Instance?.Id is { } id && r.Token is { } token:
return new(ActivationKind.Activated, id, token);
case 400 or 404:
if (r?.LicenseKey is { ActivationUsage: { } used, ActivationLimit: { } limit } && used >= limit
&& r.Error?.Contains("activation limit") == true)
return new(ActivationKind.LimitReached, Reason: r.Error, Used: used, Limit: limit);
return new(ActivationKind.Refused, Reason: r?.Error); // expired, disabled, unknown key
default:
return new(ActivationKind.Unavailable, RetryAfter: response.Headers.RetryAfter?.Delta); // 429 or 5xx
}
}
catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
{
return new(ActivationKind.Unavailable); // offline or timeout
}
}
}
On Activated, call LicenseStore.Save(new Saved(key, id, token)). The property pattern { ActivationLimit: { } limit } matches only when the value is not null, so an unlimited license never reaches the comparison.
When every seat is taken
The 400 body carries the license with activation_usage and activation_limit. Say “This key is active on 3 of 3 computers” and open the device page, where the customer enters their key, sees each computer and removes one, with no account:
Process.Start(new ProcessStartInfo("https://clavem.io/licenses/manage") { UseShellExecute = true });
Do not offer a retry. It cannot succeed until a seat is free.
Deactivate
public async Task<bool> DeactivateAsync(string key, string instanceId, CancellationToken ct = default)
{
try
{
using var response = await Http.PostAsJsonAsync("v1/licenses/deactivate",
new Dictionary<string, string> { ["license_key"] = key, ["instance_id"] = instanceId }, ct);
return response.StatusCode is System.Net.HttpStatusCode.OK or System.Net.HttpStatusCode.NotFound; // 404: already gone
}
catch (Exception e) when (e is HttpRequestException or TaskCanceledException) { return false; }
}
On true, call LicenseStore.Clear(). On false, keep the saved ids, say that the seat is still taken, and mention the device page. Wire it to a menu item named Move this license, never to Application.Exit or a finalizer.
What differs on .NET
- 32-bit and 64-bit builds.
RegistryView.Registry64makes both read the sameMachineGuid. Without it a 32-bit process on 64-bit Windows can be redirected. - Sysprep and cloned images. A Windows image captured with the same
MachineGuidgives every clone one fingerprint, so clones share a seat. - MAUI and Blazor Hybrid. There is no hardware id API, so the platform code above runs only on the desktop targets. On mobile, use a random id from secure storage.
- Trimming and AOT. Records bound by
System.Text.Jsonneed source generation or preserved members under trimming. Test a trimmed publish before you ship.
Doing this with Clavem
The device limit comes from the product, three by default, and PATCH /v1/admin/licenses/:id can change it for one license. Activation moves a license from inactive to active, and the last deactivation moves it back. See the API reference for the fields and errors.
Questions
How do I get a stable machine id in .NET?
There is no cross-platform call. On Windows read the MachineGuid registry value from the 64-bit view, on macOS read IOPlatformUUID from ioreg, and on Linux read the machine-id file. Hash the result with a salt before you send it.
Does .NET MAUI give me a device id?
Not a stable one. MAUI's DeviceInfo offers the device name, model and platform, but no hardware identifier. Use the platform code above, or a random id kept in secure storage as a weaker fallback.
Why bind JSON with SnakeCaseLower?
Clavem's replies use snake_case names such as activation_limit. JsonNamingPolicy.SnakeCaseLower, available since .NET 8, maps them to record properties like ActivationLimit without an attribute on every field.