Vai al contenuto
LICENTIVO / INTEGRATION

Licenze software C#: guida .NET e WinForms

Aggiungi l'attivazione tramite chiave a un'app .NET 8 o WinForms. Installa l'SDK con NuGet, proteggi le funzioni e verifica riavvii e accessi negati.

.NET 8+ · console e WinFormsAggiornato

1. Preparare le impostazioni del prodotto e una licenza di prova

Aggiungi chiavi di licenza per i clienti e permessi sulle funzioni alla tua applicazione C#/.NET o WinForms. Questa guida riguarda l'accesso al tuo software commerciale; scegliere una licenza open source per il codice è una decisione distinta. Inizia con una licenza legata al dispositivo e un'esportazione senza conteggio dei consumi.

La quota conta le attivazioni correnti e viene restituita al rilascio. Le licenze ordinarie contano anche offline; quelle flottanti restituiscono la quota anche alla scadenza del lease.

  1. Copia l’ID prodotto da Console > Prodotti. Apri le chiavi pubbliche di firma dello stesso prodotto e inserisci tutte le coppie ID chiave/chiave pubblica nel codice di inizializzazione, sostituendo YOUR_PRODUCT_ID, YOUR_KEY_ID e YOUR_PUBLIC_KEY. L’integrazione rapida può generare il codice. Non serve un file di configurazione; l’SDK usa https://www.licentivo.com per impostazione predefinita.
  2. Installare .NET 8 SDK o successivo. In Licentivo Integrazione rapida, crea o seleziona il tuo prodotto e consenti la funzionalità di esportazione nella sua politica e licenza.

2. Installare il pacchetto aggiunto .NET

Installa SDK 0.11.6 eseguendo il comando seguente nel tuo progetto o aggiungendo la dipendenza di compilazione. Il gestore di pacchetti scarica SDK; non servono archivi sorgente, estrazione manuale o percorsi locali.

Terminal
dotnet add package Licentivo.SDK --version 0.11.6
Terminal · new console project
dotnet new console --name LicensedApp --framework net8.0
cd LicensedApp
dotnet add package Licentivo.SDK --version 0.11.6

3. Attivare e proteggere un'operazione reale

Inizializza l’SDK all’avvio o nel gestore di attivazione della tua applicazione. Leggi la chiave cliente dal modulo e passa ID prodotto e chiavi attendibili. Mantieni il client fino alla chiusura. Inserisci RunFeature nell’operazione reale e sostituisci l’esportazione con la tua funzione.

C# · complete Program.cs
using Licentivo;

// BEGIN LICENTIVO PRODUCT
// Copy Product ID and all key ID/public key pairs from Console > Products > Signing public keys.
const string ProductId = "YOUR_PRODUCT_ID";
var TrustedKeys = new Dictionary<string,string> { ["YOUR_KEY_ID"] = "YOUR_PUBLIC_KEY" };
// END LICENTIVO PRODUCT

static string Setting(string name, string fallback) => Environment.GetEnvironmentVariable(name) ?? fallback;

// Call at the business entry point, including shortcuts and alternate menu actions.
static async Task ExportReport(string path)
{
    // Replace this write with your existing, non-metered export operation.
    await File.WriteAllTextAsync(path, "A report generated by the licensed application.\n");
}

try
{
    // In a GUI, read the activation input. Later starts pass an empty key.
    await using var client = await LicentivoClient.OpenProduct(
        ProductId, TrustedKeys, Setting("LICENTIVO_LICENSE_KEY", ""),
        error => Console.Error.WriteLine($"Background verification: {error.Message}"));
    var feature = Setting("LICENTIVO_FEATURE", "export");
    var path = Setting("LICENTIVO_OUTPUT", "licensed-report.txt");
    if (Setting("LICENTIVO_METERED", "") == "1")
        await client.RunMeteredFeature(feature, 1, Setting("LICENTIVO_OPERATION_ID", ""), () => ExportReport(path));
    else
        await client.RunFeature(feature, () => ExportReport(path));
    Console.WriteLine($"License OK: {feature} is available\nExport completed: {path}");
    // Keep client alive in your real app; disposal belongs in app shutdown.
}
catch (Exception error)
{
    Console.Error.WriteLine(error.Message);
    Environment.ExitCode = 2;
}
Windows · PowerShell
$env:LICENTIVO_LICENSE_KEY = 'YOUR_TEST_LICENSE_KEY'
dotnet run
# On later starts, restore the saved device credential:
Remove-Item Env:LICENTIVO_LICENSE_KEY
dotnet run
Linux / macOS · Bash
export LICENTIVO_LICENSE_KEY='YOUR_TEST_LICENSE_KEY'
dotnet run
# On later starts, restore the saved device credential:
unset LICENTIVO_LICENSE_KEY
dotnet run

4. Connetti l'attivazione ed esporta in WinForms

In ogni punto di ingresso dell'esportazione, attendi client.RunFeature("export", ExportReport). Include voci di menu e scorciatoie. Disabilita il pulsante di avvio durante l'esecuzione di un'operazione, rileva gli errori e mostra il rifiuto prima di consentire un altro tentativo.

Mantieni il client attivo mentre la finestra è aperta in modo che SDK heartbeat possano aggiornare l'autorizzazione. Effettua il marshalling dei messaggi di errore in background nel thread dell'interfaccia utente con Invoke o BeginInvoke. Attendere DisposeAsync all'arresto dell'applicazione; lo smaltimento normale mantiene una registrazione legata al dispositivo e tenta di restituire una postazione mobile.

Un esempio desktop separato è disponibile tramite il link alla documentazione qui sotto. WinForms richiede Windows; l'esempio console precedente funziona anche su Linux e macOS.

Windows · new WinForms project
dotnet new winforms --name LicensedWinForms --framework net8.0
cd LicensedWinForms
dotnet add package Licentivo.SDK --version 0.11.6
C# · replace Program.cs
using Licentivo;
namespace LicensedWinForms;
sealed class DemoForm : Form {
    // BEGIN LICENTIVO PRODUCT
    // Console > Products > Signing public keys: paste Product ID and every key ID/public key pair.
    const string ProductId = "YOUR_PRODUCT_ID";
    static readonly Dictionary<string,string> TrustedKeys = new() { ["YOUR_KEY_ID"] = "YOUR_PUBLIC_KEY" };
    // END LICENTIVO PRODUCT
    readonly TextBox key = new() { Width = 380, UseSystemPasswordChar = true };
    readonly Label status = new() { AutoSize = true, MaximumSize = new Size(550, 0), Text = "Enter a key, or leave empty to restore this device." };
    readonly CancellationTokenSource lifetime = new();
    LicentivoClient? client;
    bool busy;
    [STAThread] static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new DemoForm()); }
    DemoForm() {
        Text = "Licentivo · Report export"; ClientSize = new Size(600, 220);
        var panel = new FlowLayoutPanel { Dock = DockStyle.Fill, Padding = new Padding(20), FlowDirection = FlowDirection.TopDown, WrapContents = false, AutoScroll = true };
        Controls.Add(panel); panel.Controls.Add(new Label { Text = "Customer license key", AutoSize = true }); panel.Controls.Add(key);
        Add(panel, "Activate / restore", async () => {
            if (client is not null) { await client.DisposeAsync(); client = null; }
            client = await LicentivoClient.OpenProduct(ProductId, TrustedKeys, key.Text, ct: lifetime.Token);
            key.Clear(); status.Text = client.Status().State;
        });
        var buttons = new FlowLayoutPanel { AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, WrapContents = false }; panel.Controls.Add(buttons);
        Add(buttons, "Export CSV", () => Export("export", "report.csv"));
        Add(buttons, "Pro export", () => Export("pro", "pro-report.csv"));
        Add(buttons, "Refresh license", async () => { await Require().RefreshOnline(lifetime.Token); status.Text = Require().Status().State; });
        panel.Controls.Add(status);
        FormClosed += async (_, _) => { lifetime.Cancel(); if (client is not null) await client.DisposeAsync(); };
    }
    LicentivoClient Require() => client ?? throw new InvalidOperationException("Activate the application first.");
    async Task Export(string feature, string filename) {
        using var save = new SaveFileDialog { FileName = filename, Filter = "CSV report|*.csv" };
        await Require().RunFeature(feature, async () => {
            if (save.ShowDialog(this) != DialogResult.OK) return;
            await File.WriteAllTextAsync(save.FileName, "Item,Quantity,Price\nNotebook,2,12.50\nPen,5,3.00\n");
            status.Text = "Saved: " + save.FileName;
        });
    }
    void Add(Control panel, string title, Func<Task> action) {
        var button = new Button { Text = title, AutoSize = true }; panel.Controls.Add(button);
        button.Click += async (_, _) => {
            if (busy) return; busy = true; status.Text = "Working…";
            try { await action(); } catch (Exception error) { if (!IsDisposed) status.Text = error.Message; }
            finally { busy = false; }
        };
    }
}
Windows · PowerShell
dotnet run

5. Verifica attivazione, riavvio e rifiuto

  1. Esegui con la chiave di prova e conferma Licenza OK ed Esportazione completata, quindi controlla il contenuto del rapporto.
  2. Rimuovere la variabile di ambiente chiave e riavviare con lo stesso utente del sistema operativo. Le credenziali del dispositivo esistente dovrebbero essere ripristinate senza un nuovo dispositivo registrato.
  3. Utilizzare LICENTIVO_FEATURE per selezionare una funzionalità assente dalla licenza e LICENTIVO_OUTPUT per selezionare un nuovo nome file. Confermare un codice di uscita diverso da zero e che questo nuovo file non venga mai creato.
  4. Controlla l'avvio offline solo con una policy che lo consenta e una cache firmata valida. L'avvio mobile e solo online richiede l'approvazione del server.

Risolvere i problemi relativi ai controlli della licenza

Controlla ID prodotto, tutte le coppie ID chiave/chiave pubblica e la licenza del cliente. Le chiavi pubbliche appartengono al prodotto; licenze e credenziali dei dispositivi sono separate. Non distribuire chiavi di test o API Key di gestione.

Una licenza scaduta, un limite del dispositivo o una funzionalità mancante rappresentano un rifiuto di autorizzazione. Mostra l'errore e l'ID richiesta e risolvi la licenza o la policy nella console invece di ignorare RunFeature.

Per i limiti di utilizzo mensile, mantieni un ID lavoro stabile e risultati aziendali durevoli quando chiami RunMeteredFeature. L'arresto normale dell'app e la disattivazione richiesta dal cliente hanno scopi diversi; non rilasciare una registrazione associata al dispositivo ad ogni uscita.