1. Prepare la configuración del producto y una licencia de prueba.
Añade claves de licencia de clientes y permisos de funciones a tu aplicación C#/.NET o WinForms. Esta guía trata del acceso a tu software comercial; elegir una licencia de código abierto para el código es una decisión aparte. Empieza con una licencia vinculada al dispositivo y una exportación sin contador de uso.
La cuota cuenta las activaciones actuales y se recupera al liberarlas. Las licencias normales cuentan sin conexión; las flotantes también liberan cuota al vencer su arrendamiento.
- Copia el ID del producto en Consola > Productos. Abre las claves públicas de firma del mismo producto y pega todos los pares ID de clave/clave pública en el código de inicialización, sustituyendo YOUR_PRODUCT_ID, YOUR_KEY_ID y YOUR_PUBLIC_KEY. La integración rápida puede generar este código. No hace falta un archivo de configuración; el SDK usa https://www.licentivo.com de forma predeterminada.
- Instale .NET 8 SDK o posterior. En Licentivo Integración rápida, cree o seleccione su producto y permita la función de exportación en su política y licencia.
2. Instale el paquete .NET fijado
Instala el SDK 0.11.6 con el siguiente comando en tu proyecto o añade la dependencia de compilación. El gestor de paquetes obtiene el SDK; no necesitas descargar y extraer código fuente ni configurar rutas locales.
dotnet add package Licentivo.SDK --version 0.11.6dotnet new console --name LicensedApp --framework net8.0
cd LicensedApp
dotnet add package Licentivo.SDK --version 0.11.63. Activar y proteger una operación real
Inicializa el SDK al iniciar o activar tu programa. Lee la clave del cliente en el formulario y pasa el ID del producto y las claves de confianza. Mantén el cliente hasta cerrar. Coloca RunFeature en la operación real y sustituye la exportación por tu propia función.
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;
}
$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 runexport LICENTIVO_LICENSE_KEY='YOUR_TEST_LICENSE_KEY'
dotnet run
# On later starts, restore the saved device credential:
unset LICENTIVO_LICENSE_KEY
dotnet run4. Conecte la activación y exporte a WinForms
En cada punto de entrada de exportación, espere client.RunFeature("export", ExportReport). Incluya elementos de menú y accesos directos. Deshabilite el botón de inicio mientras se ejecuta una operación, detecte errores y muestre la denegación antes de permitir otro intento.
Mantenga activo al cliente mientras la ventana está abierta para que SDK latidos puedan actualizar la autorización. Registre los mensajes de error en segundo plano en el hilo de la interfaz de usuario con Invoke o BeginInvoke. Espere DisposeAsync al cerrar la aplicación; La eliminación normal conserva un registro vinculado al dispositivo e intenta devolver un asiento flotante.
Hay un ejemplo de escritorio independiente en el enlace a la documentación de abajo. WinForms requiere Windows; el ejemplo de consola anterior también funciona en Linux y macOS.
dotnet new winforms --name LicensedWinForms --framework net8.0
cd LicensedWinForms
dotnet add package Licentivo.SDK --version 0.11.6using 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; }
};
}
}
dotnet runAdministre el uso simultáneo de software con licencias flotantes
5. Verificar activación, reinicio y denegación.
- Ejecute con su clave de prueba y confirme que la Licencia está bien y la Exportación se completó, luego inspeccione el contenido del informe.
- Elimine la variable de entorno clave y reinicie con el mismo usuario del sistema operativo. La credencial del dispositivo existente debería restaurarse sin un nuevo dispositivo registrado.
- Utilice LICENTIVO_FEATURE para seleccionar una función que no está en la licencia y LICENTIVO_OUTPUT para seleccionar un nombre de archivo nuevo. Confirme un código de salida distinto de cero y que este nuevo archivo nunca se cree.
- Verifique el inicio sin conexión solo con una política que lo permita y un caché firmado válido. El inicio flotante y solo en línea requiere la aprobación del servidor.
Limite las exportaciones de archivos con un contador de uso mensual
Solucionar problemas de comprobaciones de licencia
Comprueba el ID del producto, todos los pares ID de clave/clave pública y la licencia del cliente. Las claves públicas pertenecen al producto; las licencias y credenciales de dispositivo son independientes. No distribuyas claves de prueba ni API Keys de gestión.
Una licencia caducada, un límite de dispositivo o una función faltante constituyen una denegación de autorización. Muestre el error y el ID de la solicitud, y resuelva la licencia o política en la consola en lugar de omitir RunFeature.
Para conocer los límites de uso mensual, mantenga una identificación de trabajo estable y un resultado comercial duradero cuando llame a RunMeteredFeature. El cierre normal de la aplicación y la desactivación solicitada por el cliente tienen propósitos diferentes; no libere un registro vinculado al dispositivo en cada salida.