Skip to content

LicenseChain/LicenseChain-CSharp-SDK

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LicenseChain C# SDK

License C# .NET

Official C# SDK for LicenseChain - Secure license management for .NET applications.

πŸš€ Features

  • πŸ” Secure Authentication - User registration, login, and session management
  • πŸ“œ License Management - Create, validate, update, and revoke licenses
  • πŸ›‘οΈ Hardware ID Validation - Prevent license sharing and unauthorized access
  • πŸ”” Webhook Support - Real-time license events and notifications
  • πŸ“Š Analytics Integration - Track license usage and performance metrics
  • ⚑ High Performance - Optimized for production workloads
  • πŸ”„ Async Operations - Non-blocking HTTP requests and data processing
  • πŸ› οΈ Easy Integration - Simple API with comprehensive documentation

πŸ“¦ Installation

Method 1: NuGet Package (Recommended)

# Install via Package Manager Console
Install-Package LicenseChain.SDK

# Or via .NET CLI
dotnet add package LicenseChain.SDK

Method 2: PackageReference

Add to your .csproj:

<PackageReference Include="LicenseChain.SDK" Version="1.0.0" />

Method 3: Manual Installation

  1. Download the latest release from GitHub Releases
  2. Add the DLL reference to your project
  3. Install required dependencies

πŸš€ Quick Start

Basic Setup

using LicenseChain.SDK;

class Program
{
    static async Task Main(string[] args)
    {
        // Initialize the client
        var client = new LicenseChainClient(new LicenseChainConfig
        {
            ApiKey = "your-api-key",
            AppName = "your-app-name",
            Version = "1.0.0"
        });
        
        // Connect to LicenseChain
        try
        {
            await client.ConnectAsync();
            Console.WriteLine("Connected to LicenseChain successfully!");
        }
        catch (LicenseChainException ex)
        {
            Console.WriteLine($"Failed to connect: {ex.Message}");
            return;
        }
    }
}

User Authentication

// Register a new user
try
{
    var user = await client.RegisterAsync("username", "password", "email@example.com");
    Console.WriteLine("User registered successfully!");
    Console.WriteLine($"User ID: {user.Id}");
}
catch (LicenseChainException ex)
{
    Console.WriteLine($"Registration failed: {ex.Message}");
}

// Login existing user
try
{
    var user = await client.LoginAsync("username", "password");
    Console.WriteLine("User logged in successfully!");
    Console.WriteLine($"Session ID: {user.SessionId}");
}
catch (LicenseChainException ex)
{
    Console.WriteLine($"Login failed: {ex.Message}");
}

License Management

// Validate a license
try
{
    var license = await client.ValidateLicenseAsync("LICENSE-KEY-HERE");
    Console.WriteLine("License is valid!");
    Console.WriteLine($"License Key: {license.Key}");
    Console.WriteLine($"Status: {license.Status}");
    Console.WriteLine($"Expires: {license.Expires}");
    Console.WriteLine($"Features: {string.Join(", ", license.Features)}");
    Console.WriteLine($"User: {license.User}");
}
catch (LicenseChainException ex)
{
    Console.WriteLine($"License validation failed: {ex.Message}");
}

// Get user's licenses
try
{
    var licenses = await client.GetUserLicensesAsync();
    Console.WriteLine($"Found {licenses.Count} licenses:");
    for (int i = 0; i < licenses.Count; i++)
    {
        var license = licenses[i];
        Console.WriteLine($"  {i + 1}. {license.Key} - {license.Status} (Expires: {license.Expires})");
    }
}
catch (LicenseChainException ex)
{
    Console.WriteLine($"Failed to get licenses: {ex.Message}");
}

Hardware ID Validation

// Get hardware ID (automatically generated)
var hardwareId = client.GetHardwareId();
Console.WriteLine($"Hardware ID: {hardwareId}");

// Validate hardware ID with license
try
{
    var isValid = await client.ValidateHardwareIdAsync("LICENSE-KEY-HERE", hardwareId);
    if (isValid)
    {
        Console.WriteLine("Hardware ID is valid for this license!");
    }
    else
    {
        Console.WriteLine("Hardware ID is not valid for this license.");
    }
}
catch (LicenseChainException ex)
{
    Console.WriteLine($"Hardware ID validation failed: {ex.Message}");
}

Webhook Integration

// Set up webhook handler
client.SetWebhookHandler(async (eventName, data) =>
{
    Console.WriteLine($"Webhook received: {eventName}");
    
    switch (eventName)
    {
        case "license.created":
            Console.WriteLine($"New license created: {data["licenseKey"]}");
            break;
        case "license.updated":
            Console.WriteLine($"License updated: {data["licenseKey"]}");
            break;
        case "license.revoked":
            Console.WriteLine($"License revoked: {data["licenseKey"]}");
            break;
    }
});

// Start webhook listener
await client.StartWebhookListenerAsync();

πŸ“š API Reference

LicenseChainClient

Constructor

var client = new LicenseChainClient(new LicenseChainConfig
{
    ApiKey = "your-api-key",
    AppName = "your-app-name",
    Version = "1.0.0",
    BaseUrl = "https://api.licensechain.app" // Optional
});

Methods

Connection Management
// Connect to LicenseChain
await client.ConnectAsync();

// Disconnect from LicenseChain
await client.DisconnectAsync();

// Check connection status
bool isConnected = client.IsConnected;
User Authentication
// Register a new user
var user = await client.RegisterAsync(username, password, email);

// Login existing user
var user = await client.LoginAsync(username, password);

// Logout current user
await client.LogoutAsync();

// Get current user info
var user = await client.GetCurrentUserAsync();
License Management
// Validate a license
var license = await client.ValidateLicenseAsync(licenseKey);

// Get user's licenses
var licenses = await client.GetUserLicensesAsync();

// Create a new license
var license = await client.CreateLicenseAsync(userId, features, expires);

// Update a license
var license = await client.UpdateLicenseAsync(licenseKey, updates);

// Revoke a license
await client.RevokeLicenseAsync(licenseKey);

// Extend a license
var license = await client.ExtendLicenseAsync(licenseKey, days);
Hardware ID Management
// Get hardware ID
string hardwareId = client.GetHardwareId();

// Validate hardware ID
bool isValid = await client.ValidateHardwareIdAsync(licenseKey, hardwareId);

// Bind hardware ID to license
await client.BindHardwareIdAsync(licenseKey, hardwareId);
Webhook Management
// Set webhook handler
client.SetWebhookHandler(handler);

// Start webhook listener
await client.StartWebhookListenerAsync();

// Stop webhook listener
await client.StopWebhookListenerAsync();
Analytics
// Track event
await client.TrackEventAsync(eventName, properties);

// Get analytics data
var analytics = await client.GetAnalyticsAsync(timeRange);

πŸ”§ Configuration

App Settings

Add to your appsettings.json:

{
  "LicenseChain": {
    "ApiKey": "your-api-key",
    "AppName": "your-app-name",
    "Version": "1.0.0",
    "BaseUrl": "https://api.licensechain.app",
    "Timeout": 30,
    "Retries": 3,
    "Debug": false
  }
}

Dependency Injection

// In Startup.cs or Program.cs
services.AddLicenseChain(options =>
{
    options.ApiKey = Configuration["LicenseChain:ApiKey"];
    options.AppName = Configuration["LicenseChain:AppName"];
    options.Version = Configuration["LicenseChain:Version"];
});

Environment Variables

Set these in your environment or through your build process:

# Required
export LICENSECHAIN_API_KEY=your-api-key
export LICENSECHAIN_APP_NAME=your-app-name
export LICENSECHAIN_APP_VERSION=1.0.0

# Optional
export LICENSECHAIN_BASE_URL=https://api.licensechain.app
export LICENSECHAIN_DEBUG=true

πŸ›‘οΈ Security Features

Hardware ID Protection

The SDK automatically generates and manages hardware IDs to prevent license sharing:

// Hardware ID is automatically generated and stored
var hardwareId = client.GetHardwareId();

// Validate against license
var isValid = await client.ValidateHardwareIdAsync(licenseKey, hardwareId);

Secure Communication

  • All API requests use HTTPS
  • API keys are securely stored and transmitted
  • Session tokens are automatically managed
  • Webhook signatures are verified

License Validation

  • Real-time license validation
  • Hardware ID binding
  • Expiration checking
  • Feature-based access control

πŸ“Š Analytics and Monitoring

Event Tracking

// Track custom events
await client.TrackEventAsync("app.started", new Dictionary<string, object>
{
    ["level"] = 1,
    ["playerCount"] = 10
});

// Track license events
await client.TrackEventAsync("license.validated", new Dictionary<string, object>
{
    ["licenseKey"] = "LICENSE-KEY",
    ["features"] = "premium,unlimited"
});

Performance Monitoring

// Get performance metrics
var metrics = await client.GetPerformanceMetricsAsync();
Console.WriteLine($"API Response Time: {metrics.AverageResponseTime}ms");
Console.WriteLine($"Success Rate: {metrics.SuccessRate:P}");
Console.WriteLine($"Error Count: {metrics.ErrorCount}");

πŸ”„ Error Handling

Custom Exception Types

try
{
    var license = await client.ValidateLicenseAsync("invalid-key");
}
catch (InvalidLicenseException ex)
{
    Console.WriteLine("License key is invalid");
}
catch (ExpiredLicenseException ex)
{
    Console.WriteLine("License has expired");
}
catch (NetworkException ex)
{
    Console.WriteLine("Network connection failed");
}
catch (LicenseChainException ex)
{
    Console.WriteLine($"LicenseChain error: {ex.Message}");
}

Retry Logic

// Automatic retry for network errors
var client = new LicenseChainClient(new LicenseChainConfig
{
    ApiKey = "your-api-key",
    AppName = "your-app-name",
    Version = "1.0.0",
    Retries = 3, // Retry up to 3 times
    RetryDelay = TimeSpan.FromSeconds(1) // Wait 1 second between retries
});

πŸ§ͺ Testing

Unit Tests

# Run tests
dotnet test

Integration Tests

# Test with real API
dotnet test --filter Category=Integration

πŸ“ Examples

See the examples/ directory for complete examples:

  • basic_usage.cs - Basic SDK usage
  • advanced_features.cs - Advanced features and configuration
  • webhook_integration.cs - Webhook handling

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

  1. Clone the repository
  2. Install .NET 6.0 or later
  3. Build: dotnet build
  4. Test: dotnet test

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

πŸ”— Related Projects


Made with ❀️ for the .NET community

About

Official C# SDK for LicenseChain - Secure license management for .NET applications

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages