Add licensing to a C# or .NET app
At the end, your .NET 8 or Unity app unlocks paid features with one line.
1. Install
Download PermitPlane.0.1.0.nupkg into C:\nuget-local. Then add it:
dotnet nuget add source C:\nuget-local --name permitplane
dotnet add package PermitPlane --version 0.1.0From your product page in PermitPlane (app.permitplane.com/ops/vendor/), click Download permitplane.json and put the file next to your app. Click Create test key to get a key to try.
2. Unlock a feature
using PermitPlane;
if (PPLicense.IsLicensed("export"))
EnableExport();
else
ShowUpgradeOffer();The check works offline. It returns false until the user enters a key.
3. Let users enter a key
var r = await PPLicense.ActivateAsync(key);
if (!r.Ok) Show(r.Message);r.Message is ready to show, for example "This key has reached its device limit".
Going further
Show the licence
LicenceInfo info = PPLicense.Status; // IsActive, Status, ExpiresAt, Message
PPLicense.Changed += (_, _) => RefreshLicenceUi();Changedruns on a thread-pool thread. Marshal to your UI thread.PPLicense.Deactivate()frees this device so the key works on another one.- Use
ActivateAsyncandDeactivateAsyncfrom async code.
Change the defaults
Call Configure once, before the first check:
PPLicense.Configure(o =>
{
o.ConfigPath = @"C:\Program Files\MyApp\permitplane.json";
o.StoreScope = StoreScope.Machine; // a Windows service, or all users of a PC
o.DeviceName = "Lab PC";
});- The config is found in this order:
ConfigJson,ConfigPath, thePERMITPLANE_CONFIGvariable, the app's folder. - To keep users from swapping the file, embed it as a resource and pass it as
ConfigJson. StateStore,KeyStore,ClockandHttpreplace a built-in service.
Use the full client
PPLicense.Client is the shared PermitPlaneClient. Use it for limits, floating seats and offline activation.
PermitPlaneClient client = PPLicense.Client!;
Limit seats = client.FeatureValue("seats");
string max = seats.Unlimited ? "unlimited" : seats.Value.ToString();Use a floating seat
Take a seat when the app starts and return it when it exits. The client renews an online seat while it is held.
SeatLease seat = await PPLicense.Client!.CheckoutSeatAsync();
// ... the app runs; IsLicensed works while the seat is held ...
await PPLicense.Client!.ReleaseSeatAsync(); // on exitclient.Status().Leaseshows the seat's kind and when it ends.- To use the app offline,
await client.CheckoutSeatAsync(borrowHours: 24)borrows a seat for 1 to 504 hours. - If every seat is taken,
ApiCodeisseats_exhaustedandRetryAftersays when to try again. The status is thenseat_unavailable.
Activate without internet
For a PC that cannot reach the service, make a request file, take it to the vendor portal and import the answer.
var client = PPLicense.Client!;
// 1. Make the request file; the client saves it as pending.
string request = client.CreateOfflineRequest(OfflineRequestKind.Activate, "Lab PC");
File.WriteAllText("request.json", request);
// 2. Upload request.json in the vendor portal and download the response file.
// 3. Import the response on the same PC.
client.ImportOfflineResponse(File.ReadAllText("response.json"));- Import the response before its import deadline, on the PC that made the request.
- To free the seat, make a request with
OfflineRequestKind.Deactivateand upload it. It ends the rights on this PC at once.
Errors from the full client
PPLicense never throws for a bad key or a network failure. Calls on PermitPlaneClient throw PermitPlaneException.
| Error | What to do |
|---|---|
Code is not_a_license_key | The key is mistyped. Ask the user to check it. |
ApiCode is invalid_license_key | The key is unknown or revoked. Ask for the key from the purchase email. |
ApiCode is device_limit | Every device slot is taken. Deactivate another device first. |
ApiCode is license_expired, license_suspended or license_revoked | Show a renew or contact link. |
Code is transport | The network failed. Retry later. Unlocked features keep working. |
More
- Unattended and offline activation: installers, services and the machine-directory ACL.
- Network requirements: what your customer's firewall must allow.
- Reference: your own client, platform services, threading and Unity.
Reference
Your own client
PPLicense covers one licence per app. For more control, create the client yourself:
var config = File.ReadAllText("permitplane.json");
using var client = new PermitPlaneClient(config, new CompositeHost());
await client.ActivateWithKeyAsync("PP-7KQ4M-X9T2H-B6WRN-3FJ8D", "Office PC");
if (client.HasFeature("export"))
EnableExport();
client.StatusChanged += (_, s) => Console.WriteLine($"Licence is now {s.Status}");client.Status().Statusisfree,trial,paid,online_required,expired,recovery_requiredorseat_unavailable.DeactivateAsync()frees the device and clears the local state.
Package contents
- Check the download: compare
Get-FileHash -Algorithm SHA256 .\PermitPlane.0.1.0.nupkgwith manifest.json. - The
PermitPlanepackage targetsnet8.0andnetstandard2.1. - It carries
permitplane.dllfor Windows x86_64 underruntimes/win-x64/native. - Downloads need no sign-in.
Platform services
CompositeHost builds four services from the defaults. Pass your own to replace any one.
| Service | Default | Behaviour |
|---|---|---|
IStateStore | FileStateStore | Atomic file in the user or machine directory. DPAPI on Windows, mode 0600 elsewhere. It holds a bearer installation token. |
IKeyStore | DefaultKeyStore | One ECDSA P-256 key per namespace. DPAPI on Windows, a 0600 file elsewhere. |
IClock | SystemClock | Monotonic time that includes suspend, plus a boot id. Reports Confident = false where it cannot guarantee both. |
IHttpTransport | HttpClientTransport | HttpClient, https only, no redirects, 1 MiB response cap. |
- An
HttpClientyou pass in must haveAllowAutoRedirect = false. - For a Windows service, put both stores in the machine scope:
var host = new CompositeHost(
state: new FileStateStore(scope: StoreScope.Machine),
key: new DefaultKeyStore(StoreScope.Machine));Machine directory rules
- The machine directory is
%ProgramData%\PermitPlane. - The client creates it with a locked-down ACL: SYSTEM, Administrators and the creating user.
- It checks the directory on every save, load and key creation.
- It refuses a directory that another account owns or can read or write.
- The error says "machine directory ... is not private".
- Pre-create the directory only with that ACL.
- Activate under the service account that will use the store.
- Installers create
<Vendor>\<Product>for SYSTEM and Administrators only. - The
icaclsrecipe is in Unattended and offline activation.
Upgrade notes
- An existing machine directory with default permissions is now refused.
- A machine directory whose parent other accounts can modify is now refused.
Exception fields
| Property | Holds |
|---|---|
Status, Code | The library status and its short name. |
ApiCode, HttpStatus | The service error code and HTTP status, when the service answered. |
RetryAfter | When to retry, for example after seats_exhausted. |
LastError | The raw error JSON. |
InnerException | The exception one of your own services threw. |
Seat heartbeat
- A timer runs only while an online seat is held and
AutoRefreshis on. A borrowed seat has none. - It renews at about half of
Lease.TtlSeconds, one call at a time, through the same gate asRefreshAsync. Checks never wait for it. - After a failed renewal it waits 1, 2, 4 ... minutes (at most half of the seat time) and tries again, sooner when the seat is about to run out.
- It keeps trying after the seat's time ran out, so the seat comes back when the network returns.
- It stops on
ReleaseSeatAsync(), onDispose(), when the licence is revoked and when another device took the seat (seat_unavailable). - With
AutoRefreshoff, callRenewSeatAsync()yourself at about half ofLease.TtlSeconds. - While a seat is held, checks do not start refreshes, because the renewals keep the grant current.
Your own services
- Implement
IHost, or pass your own services toCompositeHost. - A service must not call back into the same client. That call fails with
PpStatus.Busy. CreateOfflineRequestandImportOfflineResponseare synchronous: behind a refresh or seat call in flight they block until it ends (at most itsrequest_timeout_ms). Call them off the UI thread if that matters. They never wait for your UI thread, so they cannot deadlock it.- The native boundary catches exceptions from your services.
- They surface as a
Hosterror, or asSignerforIKeyStore.Sign.
Threading
- You can share one client between threads.
- The library serialises calls on one client. Feature and status checks never wait for a refresh in flight.
- Cancelling a token does not abort a call that is already running.
StatusChangedruns on a thread-pool thread. In WinForms, WPF or Unity, marshal to the UI thread (BeginInvoke,Dispatcher.BeginInvoke, or a main-thread queue).
Background refresh
- A check never makes a request itself. When the grant is due, it starts one refresh in the background and returns the cached answer.
- The first check after start also refreshes a grant older than an hour, so renewals and revocations show up soon after launch.
- A status other than
trialorpaidis retried at once, then after 1, 2, 4 ... minutes (at most the refresh interval). - Check features where you use them, not only once at startup. A long-running app notices a revocation at its next check.
- A service can read
client.NextRefreshDueand callRefreshAsync()on its own schedule. - Turn it off with
new PermitPlaneClient(config, host, new ClientOptions { AutoRefresh = false }). Dispose()saves the clock high-water mark; it does not wait for a refresh in flight.
Unity
- Use the
netstandard2.1build ofPermitPlane.dll. - Copy it and
permitplane.dllintoAssets/Plugins. - In the native DLL's import settings, select Windows x86_64 only.
- Put
permitplane.jsoninAssets/StreamingAssetsand seto.ConfigPath = Path.Combine(Application.streamingAssetsPath, "permitplane.json")inPPLicense.Configure. - The default key store and clock work in the editor and in Windows players.
HttpClientTransportworks in Unity too.- For the platform network stack, implement
IHttpTransportwithUnityWebRequest.
Good to know
- The client never stores the licence key.
- Refreshes and
Dispose()save the clock high-water mark;Persist()is only for a client that is never disposed.PPLicensesaves it when the process exits. DeactivateAsync()also clears the local state.