Skip to navigation

C# guide

This page walks through the whole C# SDK in the order you would use it. Each step starts with the shortest code that works, then shows the other ways to write it. The examples work the same in a console app, WinForms and WPF; where they differ, the page says so.

Download the C# SDK or install it from NuGet if you have not done so yet.

Requirements

SupportedRecommended
C#7.3 and newerThe default for your project
.NET.NET Framework 4.5 to 4.8.1, .NET Standard 2.0, .NET Core 3.1, .NET 5 to 10.NET 8 or .NET Framework 4.8
Project typesConsole, WinForms, WPF, class libraries
WindowsWindows 7 SP1 or newer, 64-bit and 32-bit

Add the SDK to your project

The easiest way is NuGet:

dotnet add package AuthlyX --prerelease

In Visual Studio you can also right-click the project, choose Manage NuGet Packages, tick Include prerelease and install AuthlyX.

To use the source file instead, add AuthlyX.cs to your project and install BouncyCastle.Cryptography (or BouncyCastle 1.8.9 or newer) and Newtonsoft.Json. On .NET Framework, also add a reference to System.Net.Http.

Then add the namespace at the top of each file that uses the SDK:

using AuthlyXSDK;

Create the client

public static AuthlyX app = new AuthlyX("YOUR_APP_KEY", "1.0.0");

The first value is your app’s AppKey. Find it in the dashboard under your application’s credentials. The second is the version of the program you are building. AuthlyX compares it with the versions you allow in the dashboard, so raise it each time you ship a new build. See Allowed Versions.

Create one client for the whole program. A public static field in Program is the simplest place, because every form and class can then reach it as Program.app:

static class Program
{
public static AuthlyX app = new AuthlyX("YOUR_APP_KEY", "1.0.0");
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new LoginForm());
}
}

Creating the client does not connect yet. Nothing is sent until you call init.

The constructor takes a few optional settings by name:

public static AuthlyX app = new AuthlyX(
"YOUR_APP_KEY",
"1.0.0",
requestTimeout: TimeSpan.FromSeconds(15),
updatePrompt: false);

All of them are listed in Options near the end of this page.

Three ways to call the SDK

Calls that talk to AuthlyX, such as init, login or getVariable, can be used in three ways. You can mix them in one program.

StyleLooks likeUse it when
Callbackapp.init(result => { ... });WinForms and WPF. The callback runs on the UI thread, so you can update controls in it.
awaitvar result = await app.init();Any async method: console apps, async void button handlers, services
Waitvar result = app.init().GetAwaiter().GetResult();Small console tools that do not use async

The callback style never throws. If something goes wrong, the result it receives has ok set to false with a code and message. With await or waiting, a refused call throws AuthlyXException instead, so wrap it in try.

Do not wait with GetResult(), .Result or .Wait() on a UI thread. The window freezes until AuthlyX replies.

Start the SDK

Call init once, before signing in. It checks your AppKey and version, sets up this installation and reads update information. initialize is the same method with a longer name.

With a callback

app.init(result =>
{
if (!result.ok)
{
MessageBox.Show(result.message);
Application.Exit();
return;
}
loginButton.Enabled = true;
});

This returns straight away. In WinForms and WPF the callback runs on the UI thread, which is why it can touch loginButton directly. The parameter is the result; you can name it anything.

With await

static async Task Main()
{
var started = await app.init();
if (!started.ok)
{
Console.WriteLine(started.message);
return;
}
Console.WriteLine("Connected");
}

async Task Main needs C# 7.1 or newer, which every supported project has.

init gives you a result even when something is wrong, instead of throwing. These are the codes you can get:

CodeokWhat happened
APP_INITIALIZEDtrueConnected. Continue to sign-in.
OFFLINE_MODEtrueNo internet, but this PC has saved offline access. See Offline access.
NETWORK_...falseNo internet and nothing saved. Ask the user to try again.
UPDATE_REQUIREDfalseThis version is older than the one set in your dashboard. The SDK has already shown an update box.
VERSION_MISMATCHfalseThis version is newer than the dashboard version and is not allowed.
APP_DISABLEDfalseYou paused the app in the dashboard.

Sign in

app.login("YOUR_LICENSE_KEY", result => { });
app.login("YOUR_USERNAME", "YOUR_PASSWORD", result => { });
app.deviceLogin(result => { });

One value is a license key, two values are a username and password, and deviceLogin signs in the current Windows user with no form. Device login only works for devices you approved first; see Device login. Use the methods you enabled in the dashboard; see Choose a sign-in method.

With a callback

private void loginButton_Click(object sender, EventArgs e)
{
loginButton.Enabled = false;
Program.app.login(licenseBox.Text, result =>
{
loginButton.Enabled = true;
if (result.ok)
{
new MainForm().Show();
Hide();
}
else
{
MessageBox.Show(result.message, "Sign-in failed");
}
});
}

result.message is ready to show to the user. result.code is a fixed code for your own checks, such as INVALID_CREDENTIALS, LICENSE_NOT_FOUND, LICENSE_EXPIRED, LICENSE_BANNED, DEVICE_NOT_ALLOWED or DEVICE_LIMIT_REACHED. All codes are on the Errors page.

With await

private async void loginButton_Click(object sender, EventArgs e)
{
try
{
await Program.app.login(licenseBox.Text);
new MainForm().Show();
Hide();
}
catch (AuthlyXException error)
{
MessageBox.Show(error.Message, "Sign-in failed");
}
}

If await returns, the sign-in worked. error.Kind says what sort of problem it was:

KindMeaningWhat to do
FailureKind.ServerAuthlyX answered and said noShow the message
FailureKind.NetworkNo answer: no internet, firewall, timeoutAsk the user to retry. Do not treat it as a ban.
FailureKind.SecurityA reply failed verificationDo not unlock anything
FailureKind.StorageThe SDK could not read or save its protected filesUsually a permissions problem on the PC
FailureKind.CancelledThe request was cancelled or the client was disposedNothing

A sign-in method you can reuse

static async Task<bool> SignIn(string license)
{
try
{
await app.login(license);
return true;
}
catch (AuthlyXException error)
{
Console.WriteLine(error.Message);
return false;
}
}

Create an account, change the password, add time

app.registerUser("YOUR_USERNAME", "YOUR_PASSWORD", "YOUR_LICENSE_KEY", result =>
{
MessageBox.Show(result.ok ? "Account created" : result.message);
});
app.changePassword("CURRENT_PASSWORD", "NEW_PASSWORD", result =>
{
MessageBox.Show(result.ok ? "Password changed" : result.message);
});
app.redeemLicense("ANOTHER_LICENSE_KEY", result =>
{
MessageBox.Show(result.ok ? "Time added" : result.message);
});

registerUser creates a user account and signs it in. changePassword and redeemLicense need a signed-in user. Each one also has an await form, for example await app.redeemLicense("ANOTHER_LICENSE_KEY");.

Read the account

After sign-in, app.userData holds the account details:

var username = app.userData.Username;
var plan = app.userData.Plan;
var expiry = app.userData.ExpiryDate;
PropertyTypeNotes
UsernamestringOnly set for username and password accounts
LicenseKeystringThe key used to sign in or linked to the account
EmailstringEmpty if none was given
Plan, SubscriptionstringSame value under two names
ExpiryDateDateTimeOffset?null for lifetime access
IsLifetimeboolTrue when access never ends
RegisteredAt, LastLoginDateTimeOffset?
SID, HwidstringThe Windows user ID this sign-in is bound to
DeviceLimitintDevices allowed for this account
IpAddress, CountrystringWhere the sign-in came from
LoginTypestringuser, license or device
IdstringThe account’s ID
FeaturesIReadOnlyList<string>Enabled on/off features
FeatureValues, MetadataIReadOnlyDictionary<string, object>See Features and metadata

app.user is the same object as app.userData. Before sign-in, after sign-out, and when access ends, the text properties are empty and ExpiryDate is null.

You can read userData from any thread. Features and metadata in it refresh on every heartbeat, so read them again when you need the latest values instead of keeping them in a field for hours.

Methods that return text, numbers and yes/no

Text:

static string BuildTopLine()
{
var u = app.userData;
if (string.IsNullOrEmpty(u.LicenseKey))
return " License: Null";
return " License: " + u.LicenseKey + " | Expiry: " + ExpiryText();
}
static string ExpiryText()
{
var u = app.userData;
if (u.IsLifetime)
return "Lifetime";
return u.ExpiryDate?.ToLocalTime().ToString("yyyy/MM/dd") ?? "N/A";
}
static string GetRemainingDays()
{
var u = app.userData;
if (string.IsNullOrEmpty(u.Plan))
return "N/A";
if (u.IsLifetime)
return "Lifetime";
return DaysLeft() + "D";
}

Numbers:

static int DaysLeft()
{
var expiry = app.userData.ExpiryDate;
if (expiry == null)
return 0;
var days = Math.Ceiling((expiry.Value - DateTimeOffset.UtcNow).TotalDays);
return days > 0 ? (int)days : 0;
}

Yes or no:

static bool IsSignedIn() => app.HasAccess;
static bool ExpiresSoon() => !app.userData.IsLifetime && DaysLeft() <= 3;
static bool IsPremium() => app.userData.Plan == "Premium";

Features and metadata

Features come from the plan and the account. Some are on/off, some carry a value such as "high" or 90. Metadata is extra information attached to accounts, such as a Discord name or a level. See Features and metadata.

Read them from the account

These do not contact AuthlyX, so they are safe to call often:

bool aim = app.hasFeature("aim");
var values = app.userData.FeatureValues;
string quality = values.TryGetValue("quality", out var q) ? Convert.ToString(q) : "";
var meta = app.userData.Metadata;
string discord = meta.TryGetValue("discord", out var d) ? Convert.ToString(d) : "";

hasFeature is true when that on/off feature is enabled and the user has access. The values refresh on every heartbeat, so dashboard changes show up without signing in again.

Small helpers for text, numbers and yes/no values:

static string Feature(string name, string fallback = "") =>
app.userData.FeatureValues.TryGetValue(name, out var value) && value != null
? Convert.ToString(value, CultureInfo.InvariantCulture)
: fallback;
static int FeatureInt(string name, int fallback = 0) =>
int.TryParse(Feature(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number)
? number
: fallback;
static bool FeatureBool(string name, bool fallback = false)
{
var text = Feature(name).ToLowerInvariant();
if (text == "true" || text == "1" || text == "yes" || text == "on") return true;
if (text == "false" || text == "0" || text == "no" || text == "off") return false;
return fallback;
}
int fov = FeatureInt("fov", 90);
bool rainbow = FeatureBool("rainbow");

Use the same pattern with app.userData.Metadata for metadata. These helpers need using System.Globalization;.

Ask AuthlyX directly

These calls get the current value from the server:

var all = await app.getFeatures();
var quality = await app.getFeature("quality");
var aim = await app.checkFeature("aim");
bool enabled = (bool?)aim.data["enabled"] ?? false;
var everything = await app.getAllMetadata();
var discord = await app.getMetadata("discord");
string name = (string)discord.data["value"] ?? "";
var vip = await app.checkMetadata("vip");

data is a JObject (Newtonsoft.Json). getFeatures returns data["features"], getAllMetadata returns data["metadata"], getFeature and getMetadata(key) return data["value"], and the two check calls return data["enabled"]. Each also has a callback form, such as app.getFeature("quality", result => { ... });.

Save metadata

await app.setMetadata("discord", "maya#1234");
await app.setMetadata("level", 5);
await app.setMetadata("vip", true);

Only keys you allowed for SDK writes in the dashboard can be changed.

Cloud variables

Cloud variables are values you store in the dashboard, such as a download link or a message of the day. See Cloud variables.

app.getVariable("motd", result =>
{
if (result.ok)
motdLabel.Text = result.data;
});
var motd = await app.getVariable("motd");
Console.WriteLine(motd.data);

For variables, data is the value itself as a string. To change one that you allowed the app to write:

await app.updateVariable("last_build", "1.4.2");

Scripts

Scripts are signed text you store in the dashboard. The SDK checks the signature before giving it to you; it does not run the script. See Scripts.

var script = await app.getScript("startup");
string content = (string)script.data["content"];
var older = await app.getScript("startup", 3);

With a callback:

app.getScript("startup", result =>
{
if (result.ok)
Console.WriteLine((string)result.data["content"]);
});

Logs and webhooks

await app.log("Opened the settings page");
await app.sendWebhook("purchase.clicked", new JObject
{
["item"] = "skin_42",
["price"] = 4.99
});

log writes a line to your app’s logs in the dashboard. sendWebhook sends an event to a webhook you set up in the dashboard; the second value is any JSON. Both also take a callback, for example app.log("Opened settings", result => { });, if you do not want to await them. JObject needs using Newtonsoft.Json.Linq;.

Staying signed in

After sign-in the SDK keeps the session alive by itself. It checks in with AuthlyX in the background (a heartbeat), by default about every 10 minutes, and refreshes features and metadata each time. If you ban, pause or expire the account in the dashboard, the next heartbeat ends the session.

Check access

app.HasAccess is true while the user is signed in. It does not contact AuthlyX:

if (!app.HasAccess)
{
new LoginForm().Show();
Close();
}

Get told when access ends

app.SessionInvalidated += error =>
{
mainForm.BeginInvoke((Action)(() =>
{
MessageBox.Show(error.Message, "Signed out");
Application.Exit();
}));
};
app.ConnectionChanged += state => Console.WriteLine("Connection: " + state);

SessionInvalidated fires when AuthlyX ends the session, for example after a ban. ConnectionChanged fires with Online, Disconnected, Untrusted or Disposed, and app.Connection holds the current state. Both events run on a background thread, so use BeginInvoke in WinForms or Dispatcher.BeginInvoke in WPF before touching controls.

Check now

app.checkSession(result =>
{
if (!result.ok)
MessageBox.Show(result.message);
});

onResume() does the same and is meant for when your app wakes from sleep. To run the heartbeat yourself, create the client with heartbeat: "manual" and call checkSession from your own timer. Most apps should leave it automatic. More in Sessions and heartbeats.

Offline access

Offline access lets someone keep using your app for a while without internet. You turn it on and set how long it lasts in the dashboard. See Offline access.

Save it after a successful online sign-in:

app.saveOfflineAccess(result =>
{
if (!result.ok)
Console.WriteLine(result.message);
});

Later, without internet, init returns OFFLINE_MODE with ok true, and the user signs in with the same license key or username and password. The SDK checks them against the saved permit and the sign-in succeeds with the code OFFLINE_ACCESS. userData works as normal; online-only calls such as getVariable fail until the connection returns.

app.HasOfflineAccess tells you whether this PC has a valid saved permit. Signing out deletes it.

Updates

When this version is not allowed, init fails with UPDATE_REQUIRED or VERSION_MISMATCH, and the SDK shows a message box with the new version, release notes and a button to open your download page. When a newer version exists but this one is still allowed, the SDK shows an Update available box once after sign-in.

To show your own window, turn the box off and read the details yourself:

public static AuthlyX app = new AuthlyX("YOUR_APP_KEY", "1.0.0", updatePrompt: false);
var started = await app.init();
if (started.code == "UPDATE_REQUIRED" || started.code == "VERSION_MISMATCH")
{
var update = started.data?["update"] as JObject;
string latest = (string)update?["version"] ?? "";
string link = (string)update?["url"] ?? "";
string notes = (string)update?["notes"] ?? "";
MessageBox.Show(started.message + "\n\n" + latest + "\n" + notes + "\n" + link);
}

Set versions and download links under your app’s Updates settings. See Automatic updates.

Sign out

app.logout(result => Application.Restart());
await app.logout();

This ends the session on AuthlyX, clears userData and deletes saved offline access on this PC. Without internet it still signs out locally; the await form then throws a Network error, and the callback form reports it in the result.

When your program exits you do not need to do anything else. To shut the client down earlier, call app.Dispose(). A disposed client cannot be used again.

Threads and UI apps

  • Callbacks capture the thread they were started from. Start them from a form or window and they come back on the UI thread, so you can set label.Text directly. Started from a console app or a background thread, they run on a thread-pool thread.
  • await in an async void button handler also comes back to the UI thread.
  • Events (SessionInvalidated, ConnectionChanged) run on a background thread. Use BeginInvoke before touching controls.
  • userData, HasAccess and HasOfflineAccess can be read from any thread at any time.
  • Network calls can be started from any thread. The SDK sends them one at a time, so starting several at once is fine; they queue.

Cancel a call

Every await form takes a CancellationToken as its last value:

var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var motd = await app.getVariable("motd", cancel.Token);

A cancelled call throws OperationCanceledException or an AuthlyXException with Kind set to Cancelled.

Results and errors

Every call returns, or passes to your callback, a Result<T>:

MemberMeaning
ok / SuccessTrue when the call worked
failedThe opposite of ok
code / CodeFixed code such as APP_INITIALIZED or LICENSE_EXPIRED
message / MessageText you can show to the user
requestId / RequestIdQuote this when you contact support
data / DataThe call’s data: a string for getVariable, a SessionInfo for sign-in, a JObject for the rest

AuthlyXException has Message, Code, Kind, Status, RequestId and Data.

Options

Pass these by name to the constructor:

SettingDefaultWhat it does
requestTimeout8 secondsHow long one call may take, including retries
retryLimit2How many times a failed request is retried (0 to 5)
heartbeat"server""manual" to run session checks yourself
updatePrompttrueShow the built-in update boxes
debugfalseWrite request details to the debug output

For full control, build a ClientOptions from AuthlyX.defaultOptions(appKey, version) and pass it to new AuthlyX(options). It also has BuildHash for Application hashes and Storage to keep the SDK’s protected files in another folder with new WindowsProtectedStore(path).

Common problems

'AuthlyX' does not contain a definition for 'response' or for Login. That is V2 code. See Move from V2 to V3.

The window freezes when signing in. Something is waiting with .Result, .Wait() or GetResult() on the UI thread. Use a callback or await.

Cross-thread operation not valid. A SessionInvalidated or ConnectionChanged handler touched a control. Wrap the code in BeginInvoke.

Sign-in fails with DEVICE_NOT_ALLOWED. The account is locked to another PC or Windows user. Reset its device in the dashboard.

A complete console program

using System;
using System.Threading.Tasks;
using AuthlyXSDK;
static class Program
{
static AuthlyX app = new AuthlyX("YOUR_APP_KEY", "1.0.0");
static async Task Main()
{
var started = await app.init();
if (!started.ok)
{
Console.WriteLine(started.message);
return;
}
Console.Write("License key: ");
var license = Console.ReadLine();
try
{
await app.login(license);
}
catch (AuthlyXException error)
{
Console.WriteLine(error.Message);
return;
}
var u = app.userData;
Console.WriteLine("Plan: " + u.Plan);
Console.WriteLine("Expires: " + (u.IsLifetime ? "Lifetime" : u.ExpiryDate?.ToString("yyyy/MM/dd")));
if (app.hasFeature("beta"))
Console.WriteLine("Beta features are on");
Console.WriteLine("Press Enter to sign out");
Console.ReadLine();
try
{
await app.logout();
}
catch (AuthlyXException)
{
}
}
}

Each method also has its own page with every language side by side under SDK methods.