Clavem stores your builds and answers GET /v1/releases/:productId/latest. A license that is valid for the product gets release notes and files with signed download links. Any other key gets only version and published_at. The release docs list the fields. This page is the C# side: the check, the version comparison, a download that resumes, and the install step. It reuses the static HttpClient pattern from license key validation in C#. The C# code was not compiled or run, because no .NET SDK was available.
Check
using System.Net;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.Json;
using NuGet.Versioning;
public sealed record ReleaseFile(long Id, string Filename, long Size, string? Platform, string? Url);
public sealed record Release(string Version, string? Notes, string PublishedAt, List<ReleaseFile>? Files);
public enum UpdateState { UpToDate, Available, Locked, Failed }
public sealed record UpdateInfo(UpdateState State, Release? Release = null, ReleaseFile? File = null, string? Reason = null);
public static class Updater
{
private static readonly JsonSerializerOptions Snake = new(JsonSerializerDefaults.Web) { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
/// The label you chose at upload, for example windows-x64, macos-arm64 or linux-x64.
public static string PlatformLabel() =>
(OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linux")
+ "-" + RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant();
public static string CurrentVersion() =>
Assembly.GetEntryAssembly()!.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion;
public static async Task<UpdateInfo> CheckAsync(HttpClient http, long productId, string? licenseKey, CancellationToken ct = default)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"v1/releases/{productId}/latest?platform={Uri.EscapeDataString(PlatformLabel())}");
if (licenseKey is not null) request.Headers.Add("X-License-Key", licenseKey); // a header keeps it out of logs
try
{
using var response = await http.SendAsync(request, ct);
switch (response.StatusCode)
{
case HttpStatusCode.OK: break;
case HttpStatusCode.NotFound: return new(UpdateState.UpToDate); // nothing published yet
default: return new(UpdateState.Failed, Reason: $"HTTP {(int)response.StatusCode}, Retry-After {response.Headers.RetryAfter?.Delta}");
}
var release = await response.Content.ReadFromJsonAsync<Release>(Snake, ct);
if (release is null || !NuGetVersion.TryParse(release.Version, out var latest) || !NuGetVersion.TryParse(CurrentVersion(), out var current))
return new(UpdateState.Failed, Reason: "version is not semver");
if (latest <= current) return new(UpdateState.UpToDate);
return release.Files?.FirstOrDefault(f => f.Url is not null) is { } file
? new(UpdateState.Available, release, file)
: new(UpdateState.Locked, release); // newer, but the key is missing or not valid
}
catch (Exception e) when (e is HttpRequestException or TaskCanceledException or JsonException)
{
return new(UpdateState.Failed, Reason: "offline");
}
}
}
SnakeCaseLower binds published_at to PublishedAt. Locked is the useful middle case: a lapsed customer learns that a newer version exists and can be sent to renew. For the live demo product the real API answers 404 with not_found, and the code maps that to up to date.
Pass the version your build reports. Assembly.GetName().Version has four numeric parts and no pre-release tag. InformationalVersion carries the string you set, and the SDK can append +commit metadata that NuGetVersion accepts and ignores in comparisons.
Download, with resume and progress
Request the link when the user clicks Update, by calling CheckAsync again, and download from that fresh response. Use ResponseHeadersRead so the body streams, and a client whose timeout is not the 8 seconds of the license client:
private static readonly HttpClient DownloadHttp = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) })
{
Timeout = Timeout.InfiniteTimeSpan, // stalls are handled by the CancellationToken you pass
};
public static async Task DownloadAsync(ReleaseFile file, string destination, IProgress<int>? progress = null, CancellationToken ct = default)
{
var part = destination + ".part";
long have = File.Exists(part) ? new FileInfo(part).Length : 0;
if (have > file.Size) { File.Delete(part); have = 0; }
if (have < file.Size)
{
using var request = new HttpRequestMessage(HttpMethod.Get, file.Url);
if (have > 0) request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(have, null);
using var response = await DownloadHttp.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new InvalidOperationException("The download link expired. Check for updates again.");
if (response.StatusCode == HttpStatusCode.OK) have = 0; // Range ignored: start over
else if (response.StatusCode != HttpStatusCode.PartialContent) response.EnsureSuccessStatusCode();
await using var source = await response.Content.ReadAsStreamAsync(ct);
await using var target = new FileStream(part, have > 0 ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None);
var buffer = new byte[81920];
int last = -1, read;
while ((read = await source.ReadAsync(buffer, ct)) > 0)
{
await target.WriteAsync(buffer.AsMemory(0, read), ct);
have += read;
var percent = (int)(have * 100 / file.Size);
if (percent != last) { last = percent; progress?.Report(percent); }
}
}
if (new FileInfo(part).Length != file.Size)
throw new InvalidOperationException("Size does not match. Keep the .part file and resume.");
File.Move(part, destination, overwrite: true);
}
The response has no checksum field, so Size is the only integrity check the API gives. Sign your installers, and let Windows or macOS verify the signature. With ResponseHeadersRead, HttpClient.Timeout applies until the headers arrive and the body streams afterward, so a cancellation token is how you stop a stalled download. Wire IProgress<int> to a Progress<int> created on the UI thread, and it will report back to it.
Install
On Windows a running executable cannot be overwritten. Start the downloaded installer and exit:
Process.Start(new ProcessStartInfo(destination) { UseShellExecute = true });
Application.Current.Shutdown(); // WPF; use Application.Exit in WinForms
On macOS, open the DMG and let the customer drag the new app over the old one. On Linux, replace an AppImage and chmod +x it. ClickOnce and MSIX have their own update mechanisms and feed formats, and this endpoint does not feed them. If your app ships that way, use this endpoint to tell the customer a build exists and send them to the download.
Limits and timing
The releases endpoint allows 120 requests a minute per IP address, counted apart from validation. Check once at launch or once a day. “Latest” is the most recently published release, not the highest version number: a backport published after 3.2.1 becomes the answer, so a customer on 3.2.1 sees nothing newer.
Doing this with Clavem
Upload each installer in the dashboard, give it a platform label such as windows-x64, and publish. The same key that turns the app on fetches the download. Licenses imported from Lemon Squeezy have no order page, so for them this endpoint is how builds are delivered. See the release docs for limits and storage.
Questions
How do I compare versions in .NET?
Use NuGetVersion from the NuGet.Versioning package. It parses 3.10.0 and 4.0.0-beta.2, and orders a pre-release below its release. System.Version cannot parse a pre-release tag, and comparing strings gets 3.10.0 wrong.
Which version should my app report?
Read AssemblyInformationalVersionAttribute. It holds the version you set, plus build metadata after a plus sign that the SDK may append. Strip the metadata or let NuGetVersion ignore it. Assembly.GetName().Version always has four numeric parts and no pre-release tag.
Can a .NET desktop app replace itself?
Not while it runs on Windows. Download the installer or the new package, start it with UseShellExecute, and exit. ClickOnce and MSIX have their own update mechanisms and feeds, which this endpoint does not replace.