BabelLicensing

Namespace: Babel.Licensing Assembly: Babel.Licensing.dll

BabelLicensing service class that provides methods for licensing management.

public sealed class BabelLicensing : BabelService, IDisposable

Inheritance

objectBabelServiceBabelLicensing

Implements

IDisposable

Inherited Members

BabelService.Dispose(), BabelService.ShutdownAsync(), BabelService.Configuration, object.GetType(), object.ToString(), object.Equals(object?), object.Equals(object?, object?), object.ReferenceEquals(object?, object?), object.GetHashCode()

Remarks

This class provides methods for configuring the service, requesting and releasing licenses, activating and deactivating licenses, and validating licenses.

Constructors

BabelLicensing()

BabelLicensing class constructor

public BabelLicensing()

BabelLicensing(BabelLicensingConfiguration)

This is the constructor for the BabelLicensing class that takes a configuration object as a parameter. It initializes a new instance of the BabelLicensing class and sets the configuration property to the provided configuration object.

public BabelLicensing(BabelLicensingConfiguration configuration)

Parameters

NameDescription

The configuration object.

Examples

// Create a new configuration object
BabelLicensingConfiguration config = new BabelLicensingConfiguration() {
    // Set the service URL
    ServiceUrl = "http://localhost:5005",

    // Set the public key used to verify the license signature
    // See RSASignature for more information on how to export a public key
    SignatureProvider = RSASignature.FromKeys("public key here"),

    // Set a unique client ID
    ClientId = "my custom client id"
};

// Create the client object used to communicate with the server
BabelLicensing client = new BabelLicensing(config);

Exceptions

NameDescription

configuration is null.

Properties

Configuration

Reporting configuration

public BabelLicensingConfiguration Configuration { get; }

Property Value

BabelLicensingConfiguration

Heartbeat

Gets the heartbeat worker thread.

public Heartbeat Heartbeat { get; }

Property Value

Heartbeat

Methods

ActivateLicenseAsync(string, Type, object, CancellationToken)

Activates a license for the specified user key.

public Task<ActivateLicenseResult> ActivateLicenseAsync(string userKey, Type type = null, object instance = null, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key to activate the license for.

type Type

The type to activate the license for.

instance object

The instance to activate the license for.

cancellationToken CancellationToken

The cancellation token.

Returns

NameDescription

The result of the license activation.

Examples

using Babel.Licensing;

// Create a new configuration object
BabelLicensingConfiguration config = new BabelLicensingConfiguration() {
    // Set the service URL
    ServiceUrl = "http://localhost:5005",

    // Set the public key used to verify the license signature
    SignatureProvider = RSASignature.FromKeys("<public key>"),

    // Set the application name
    // This will identify the application on the and server
    ClientId = "<application name>"
};

// Create the client object used to communicate with the server
BabelLicensing client = new BabelLicensing(config);

// Use BabelServiceLicenseProvider to cache a local copy of the license for offline use
BabelServiceLicenseProvider provider = new BabelServiceLicenseProvider(client) {
    // Refresh the license contacting the server every 5 days
    // If set to TimeSpan.Zero, the license will be validated every time on the server
    LicenseRefreshInterval = TimeSpan.FromDays(5)
};

// Register the license provider with BabelLicenseManager
BabelLicenseManager.RegisterLicenseProvider(typeof(Program), provider);

// Check if the user key is set
if (provider.UserKey == null)
{
    // If the user key is not set, the license has not been activated yet.

    // Ask the user to activate the license
    Console.WriteLine("Please enter your activation license key: ");
    string? userKey = Console.ReadLine();

    try
    {
        var result = await client.ActivateLicenseAsync(userKey, typeof(Program));
        Console.WriteLine($"License {result.License.Id} activated, client ({result.ActiveClientCount}/{result.MaxClientCount})");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Could not activate license: {ex.Message}");
        return;
    }
}

try
{
    // Validate the license
    // This will contact the server to validate the license if the local copy is expired
    // You can customize the validation interval using the LicenseValidationInterval property
    var license = await BabelLicenseManager.ValidateAsync(typeof(Program));

    Console.WriteLine($"License {license.Id} valid.");

    // Ask to deactivate the license
    Console.WriteLine("Do you want to deactivate the license? (y/n)");
    string? answer = Console.ReadLine();

    if (answer?.ToLower() == "y")
    {
        try
        {
            await client.DeactivateLicenseAsync(provider.UserKey);
            Console.WriteLine("License deactivated.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Could not deactivate license: {ex.Message}");
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"License not valid: {ex.Message}");
    return;
}

Exceptions

NameDescription

if userKey is null

Configure(Action<BabelLicensingConfiguration>)

Configures the BabelLicensing service with the provided configuration.

public static void Configure(Action<BabelLicensingConfiguration> configurer)

Parameters

NameDescription

The configuration action to apply.

Examples

BabelLicensing.Configure(config => {
    // Set the service URL
    ServiceUrl = "http://localhost:5005";

    // To extract the public key from a .snk file use the following code
    // var rsa = RSASignature.CreateFromKeyFile(@"Keys.snk");
    // string publicKey = rsa.ExportKeys(true);

    string publicKey = "public key here";
    config.SignatureProvider = RSASignature.FromKeys(publicKey);

    // Set client id to identify this application
    config.ClientId = "my custom client id";
});

CreateDefaultConfiguration()

Creates a default configuration for the Babel Licensing service.

protected override BabelServiceConfiguration CreateDefaultConfiguration()

Returns

NameDescription

A new instance of the BabelLicensingConfiguration class.

DeactivateLicenseAsync(string, CancellationToken)

Deactivates a license for the specified user key.

public Task<DeactivateLicenseResult> DeactivateLicenseAsync(string userKey, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key for which to deactivate the license.

cancellationToken CancellationToken

A cancellation token to cancel the operation.

Returns

NameDescription

A object representing the result of the deactivation operation.

Exceptions

NameDescription

if userKey is null

Dispose(bool)

Dispose method for the BabelLicensing class.

protected override void Dispose(bool disposing)

Parameters

NameDescription

disposing bool

Whether is disposing or finalizing.

GetLicenseInfoAsync(string, CancellationToken)

Retrieves license information for the specified user key.

public Task<LicenseInfoResult> GetLicenseInfoAsync(string userKey, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key to retrieve license information for.

cancellationToken CancellationToken

A cancellation token to cancel the operation.

Returns

NameDescription

A task that represents the asynchronous operation. The task result contains the license information for the specified user key.

Exceptions

NameDescription

if userKey is null

HeartbeatAsync(string, CancellationToken)

Sends a heartbeat signal to the licensing server to indicate that the user is still active.

public Task<HeartbeatResult> HeartbeatAsync(string userKey, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key to send the heartbeat for.

cancellationToken CancellationToken

A cancellation token to cancel the operation.

Returns

NameDescription

A object containing the result of the heartbeat operation.

Exceptions

NameDescription

if userKey is null

OnConfiguring(BabelServiceConfiguration)

Overrides the OnConfiguring method of the base class to configure the BabelServiceConfiguration object.

protected override void OnConfiguring(BabelServiceConfiguration config)

Parameters

NameDescription

The BabelServiceConfiguration object to be configured.

ReleaseFloatingLicenseAsync(string, CancellationToken)

Releases a floating license for the specified user key.

public Task<ReleaseFloatingLicenseResult> ReleaseFloatingLicenseAsync(string userKey, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key associated with the floating license to release.

cancellationToken CancellationToken

A cancellation token to cancel the asynchronous operation.

Returns

NameDescription

A object representing the result of the operation.

Exceptions

NameDescription

if userKey is null

RequestFloatingLicenseAsync(string, Type, object, CancellationToken)

Requests a floating license for the specified user key, type and object instance.

public Task<RequestFloatingLicenseResult> RequestFloatingLicenseAsync(string userKey, Type type = null, object instance = null, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key.

type Type

The type.

instance object

The object instance.

cancellationToken CancellationToken

The cancellation token.

Returns

NameDescription

A object representing the result of the request.

Examples

using Babel.Licensing;

// Create a new configuration object
BabelLicensingConfiguration config = new BabelLicensingConfiguration() {
    // Set the service URL
    ServiceUrl = "http://localhost:5005",

    // Set the public key used to verify the license signature
    SignatureProvider = RSASignature.FromKeys("<public key>"),

    // Set a unique client ID for this application instance
    ClientId = Guid.NewGuid().ToString()
};

// Create the client object used to communicate with the server
BabelLicensing client = new BabelLicensing(config);

// Ask the user to activate the license
Console.WriteLine("Please enter your floating license key: ");
string? userKey = Console.ReadLine();

try
{
    var result = await client.RequestFloatingLicenseAsync(userKey, typeof(Program));
    Console.WriteLine($"License {result.License.Id} requested.");
    Console.WriteLine($"There are {result.ActiveClientCount}/{result.MaxClientCount} clients active.");
}
catch (Exception ex)
{
    Console.WriteLine($"Could not request floating license: {ex.Message}");
    return;
}

try
{
    // Simulate a long task which requires the allocation of a license
    for (int i = 0; i < 10; i++)
    {
        // Validate the license
        // This will contact the server to validate the license
        var result = await client.ValidateLicenseAsync(userKey, typeof(Program));
        Console.WriteLine($"{i}) License {result.License.Id} valid.");

        // Wait 1 second
        await Task.Delay(1000);
    }

    try
    {
        // When the application is done with the license, it can release it
        await client.ReleaseFloatingLicenseAsync(userKey);
        Console.WriteLine("License released.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Could not release license: {ex.Message}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"License not valid: {ex.Message}");
    return;
}

Exceptions

NameDescription

if userKey is null

ShutdownAsync()

Stops the heartbeat and shut down the communication with the service.

public override Task ShutdownAsync()

Returns

NameDescription

ValidateLicenseAsync(string, Type, object, CancellationToken)

Validates a license for a given user key, type and instance.

public Task<ValidateLicenseResult> ValidateLicenseAsync(string userKey, Type type = null, object instance = null, CancellationToken cancellationToken = default)

Parameters

NameDescription

userKey string

The user key to validate the license for.

type Type

The type to validate the license against.

instance object

The instance to validate the license against.

cancellationToken CancellationToken

The cancellation token.

Returns

NameDescription

A task that represents the asynchronous operation. The task result contains the validation result.

Exceptions

NameDescription

if userKey is null

BeforeSendRequest

BeforeSendRequest event

public event EventHandler<BeforeSendRequestEventArgs> BeforeSendRequest

Event Type

EventHandler<BeforeSendRequestEventArgs>

HeartbeatCompleted

HeartbeatCompleted event

public event EventHandler<HeartbeatCompletedEventArgs> HeartbeatCompleted

Event Type

EventHandler<HeartbeatCompletedEventArgs>

LicenseActivated

LicenseActivated event

public event EventHandler<LicenseActivatedEventArgs> LicenseActivated

Event Type

EventHandler<LicenseActivatedEventArgs>

LicenseActivationError

LicenseActivated event

public event EventHandler<LicenseActivationErrorEventArgs> LicenseActivationError

Event Type

EventHandler<LicenseActivationErrorEventArgs>

LicenseDeactivated

LicenseDeactivated event

public event EventHandler<LicenseDeactivatedEventArgs> LicenseDeactivated

Event Type

EventHandler<LicenseDeactivatedEventArgs>

LicenseDeactivationError

LicenseDeactivationError event

public event EventHandler<LicenseDeactivationErrorEventArgs> LicenseDeactivationError

Event Type

EventHandler<LicenseDeactivationErrorEventArgs>

LicenseReleaseError

LicenseReleaseError event

public event EventHandler<LicenseReleaseErrorEventArgs> LicenseReleaseError

Event Type

EventHandler<LicenseReleaseErrorEventArgs>

LicenseReleased

LicenseReleased event

public event EventHandler<LicenseReleasedEventArgs> LicenseReleased

Event Type

EventHandler<LicenseReleasedEventArgs>

LicenseRequestError

LicenseRequestError event

public event EventHandler<LicenseRequestErrorEventArgs> LicenseRequestError

Event Type

EventHandler<LicenseRequestErrorEventArgs>

LicenseRequested

LicenseRequested event

public event EventHandler<LicenseRequestedEventArgs> LicenseRequested

Event Type

EventHandler<LicenseRequestedEventArgs>

LicenseValidated

LicenseValidated event

public event EventHandler<LicenseValidatedEventArgs> LicenseValidated

Event Type

EventHandler<LicenseValidatedEventArgs>

LicenseValidationError

LicenseValidationError event

public event EventHandler<LicenseValidationErrorEventArgs> LicenseValidationError

Event Type

EventHandler<LicenseValidationErrorEventArgs>

Last updated