XmlLicenseBuilder

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

Provides a custom constructor and validation for XML licenses. This class cannot be inherited.

public class XmlLicenseBuilder : ILicenseBuilder, ICreateCustomRestriction, ICreateCustomSignatureProvider, IReadableLicenseString

Inheritance

objectXmlLicenseBuilder

Implements

ILicenseBuilder, ICreateCustomRestriction, ICreateCustomSignatureProvider, IReadableLicenseString

Inherited Members

object.GetType(), object.MemberwiseClone(), object.ToString(), object.Equals(object?), object.Equals(object?, object?), object.ReferenceEquals(object?, object?), object.GetHashCode()

Extension Methods

Licenseable.AddLicense<XmlLicenseBuilder>(XmlLicenseBuilder, ILicense), Licenseable.Load(ILicenseBuilder, string), Licenseable.RemoveLicense<XmlLicenseBuilder>(XmlLicenseBuilder, ILicense), Licenseable.Save<XmlLicenseBuilder>(XmlLicenseBuilder, string), Licenseable.SignWith(ILicenseBuilder, ISignatureProvider), Licenseable.SignWithKeys(ILicenseBuilder, string, string), Licenseable.ToReadableString(ILicenseBuilder, string), Licenseable.ValidateSignature(ILicenseBuilder)

Constructors

XmlLicenseBuilder(ISignatureProvider)

Create a new instance of class with the specified signature provider.

public XmlLicenseBuilder(ISignatureProvider signer)

Parameters

NameDescription

The object used to digitally sign the license information.

Exceptions

NameDescription

Thrown when one or more required arguments are null.

XmlLicenseBuilder()

Create a new instance of class.

public XmlLicenseBuilder()

Properties

AddXmlDeclaration

Gets or sets a value indicating whether the add XML declaration.

public bool AddXmlDeclaration { get; set; }

Property Value

bool

Encoding

Gets or sets the character encoding used to save the license.

public Encoding Encoding { get; set; }

Property Value

Encoding

Formatted

Gets or sets a value indicating whether the indent the generated XML.

public bool Formatted { get; set; }

Property Value

bool

HasSignature

Indicates whether the license has a signature.

public bool HasSignature { get; }

Property Value

bool

SignatureProvider

Gets or sets the signature provider. The signature provider is used to sign and verify the integrity of the license data.

public ISignatureProvider SignatureProvider { get; set; }

Property Value

ISignatureProvider

Examples

XmlLicenseBuilder builder = new XmlLicenseBuilder();
builder.SignatureProvider = RSASignature.CreateFromKeyFile("KeyPair.snk");

Methods

AddOrUpdate(ILicense)

Adds a with a given key to the builder if the license does not already exists, or updates the if the key already exists.

public void AddOrUpdate(ILicense license)

Parameters

NameDescription

license ILicense

The object.

Exceptions

NameDescription

Thrown when the license argument is null.

Load(Stream)

Loads the license from the specified stream.

public void Load(Stream stream)

Parameters

NameDescription

stream Stream

Specify the stream where to load the license.

Exceptions

NameDescription

Thrown when the stream argument is null.

Thrown when the stream contains bad data.

Load(string)

Loads the license from the given file.

public void Load(string path)

Parameters

NameDescription

path string

The file name where to save the license.

Exceptions

NameDescription

Thrown when one or more required arguments are null.

LoadXml(string)

Loads the license from the specified XML document.

public void LoadXml(string xml)

Parameters

NameDescription

xml string

The XML license document.

Exceptions

NameDescription

Thrown when the xml argument is null.

Thrown when the xml contains bad license data.

Parse(string)

Parse the specified XML license string.

public void Parse(string license)

Parameters

NameDescription

license string

The XML license string.

Remove(ILicense)

Removes a with a given key from the .

public bool Remove(ILicense license)

Parameters

NameDescription

license ILicense

The object to be removed.

Returns

NameDescription

true if the license is successfully removed, false if it fails to remove the license.

Exceptions

NameDescription

Thrown when the license argument is null.

Save(Stream)

Saves the current license state to the specified stream.

public void Save(Stream stream)

Parameters

NameDescription

stream Stream

The stream where to write the license.

Examples

This sample shows how to generate and save an XML license to a MemoryStream.

XmlLicense license = new XmlLicense();

license.Id = IdGenerator.Create("lic", 5);
license.Product = new Product();
license.Product.Id = IdGenerator.Create("prd", 5);

// Create and sign a license
XmlLicenseBuilder builder = new XmlLicenseBuilder();
builder.SignatureProvider = RSASignature.CreateFromKeyFile("KeyPair.snk");
builder.AddOrUpdate(license);
builder.Sign();

// Save the license 
MemoryStream stream = new MemoryStream();
builder.Save(stream);

Exceptions

NameDescription

Thrown when the stream argument is null.

Save(string)

Saves the current license state to a given file.

public void Save(string path)

Parameters

NameDescription

path string

The file path where to save the license.

Exceptions

NameDescription

Thrown when one or more required arguments are null.

Sign()

Add a signature to the current license object.

public void Sign()

Exceptions

NameDescription

Thrown when the signature cannot be generated.

ToLicenses()

Converts this object to a object.

public IEnumerable<ILicense> ToLicenses()

Returns

NameDescription

This object as a .

ToReadableString(string)

Creates and returns a string representation of the current XML license.

public string ToReadableString(string format)

Parameters

NameDescription

format string

Describes the format to use.

Returns

NameDescription

This XML license as a string.

Remarks

Available formats B: Not formatted XML

ToXml(bool)

Converts this instance to an XML string.

public string ToXml(bool formatted = true)

Parameters

NameDescription

formatted bool

Whether to format the XML output.

Returns

NameDescription

The XML license string.

Validate()

Validates the current license signature. This method doesn't validate license restrictions. Is not meant to be used to validate the license in client applications. To validate the license in client applications use the class.

public bool Validate()

Returns

NameDescription

true if the signature id valid, false if the signature is not present or not valid.

Exceptions

NameDescription

Thrown when the signature cannot be validated.

CreateCustomRestriction

Event queue for all listeners interested in CreateCustomRestriction events.

public event EventHandler<CreateCustomRestrictionEventArgs> CreateCustomRestriction

Event Type

EventHandler<CreateCustomRestrictionEventArgs>

Examples

This code creates an XML license with a custom restriction.

// Create a digital signer
RSASignature signer = RSASignature.CreateFromKeyFile("Keys.snk");

// Minimum hardware requirements
// Total Memory 4 Gb, Two Cpu
int totalMemory = 4096;
int cpuCount = 2;

var license = new XmlLicense()
			  .WithUniqueId()
			  .ForProduct("Product", "1.0.0.0")
			  .LicensedTo("ACME", "devs@acme.com")
			  .WithRestrictions(new MinimumRequirementsRestriction(totalMemory, cpuCount))
			  .SignWith(signer);

license.Save("Product.licenses");

To validate a custom restriction, handle the CreateCustomRestriction event and create the proper restriction object.

XmlLicenseManager manager = new XmlLicenseManager();

manager.CreateCustomRestriction += (s, e) =>
{
	if (e.RestrictionName == "MinimumRequirements")
		e.Restriction = new MinimumRequirementsRestriction();
};

XmlLicense license = manager.Validate(File.ReadAllText("Product.licenses"));

This is the implementation of a custom restriction that is able to validate the machine minimum requirements in terms of available memory and total number of CPU present.

class MinimumRequirementsRestriction : Restriction, IXmlSerializable
{
	private int _processorCount;
	private long _totalMemory;

	public override string Name
	{
		get { return "MinimumRequirements"; }
	}

	public long TotalMemory
	{
		get
		{
			return _totalMemory;
		}
	}

	public int ProcessorCount
	{
		get
		{
			return _processorCount;
		}
	}

	public MinimumRequirementsRestriction()
	{
	}

	public MinimumRequirementsRestriction(long totalMemory, int processorCount)
	{
		_totalMemory = totalMemory;
		_processorCount = processorCount;
	}

	public override ValidationResult Validate(ILicenseContext context, Type type, object instance)
	{
		ISystemInformation sys = (ISystemInformation)context.GetService(typeof(ISystemInformation));

		long totalMem = ToMegabytes(sys.TotalPhysicalMemory);
		if (totalMem < _totalMemory || sys.ProcessorCount < _processorCount)
		{
			// Cannot run on this machine
			return ValidationResult.NotPassed;                
		}            

		return base.Validate(context, type, instance);
	}

	private static long ToMegabytes(long bytes)
	{
		return bytes / 1024 / 1024;
	}

	public System.Xml.Schema.XmlSchema GetSchema()
	{
		return null;
	}

	public void ReadXml(System.Xml.XmlReader reader)
	{
		reader.MoveToContent();

		string totalMemory = reader.GetAttribute("totalMemory");
		if (!string.IsNullOrEmpty(totalMemory))
			_totalMemory = XmlConvert.ToInt64(totalMemory);

		string processorCount = reader.GetAttribute("processorCount");
		if (!string.IsNullOrEmpty(processorCount))
			_processorCount = XmlConvert.ToInt32(processorCount);

		Boolean isEmptyElement = reader.IsEmptyElement;
		reader.ReadStartElement();
		if (!isEmptyElement)
		{
			reader.ReadEndElement();
		}
	}

	public void WriteXml(System.Xml.XmlWriter writer)
	{
		if (TotalMemory > 0)
			writer.WriteAttributeString("totalMemory", XmlConvert.ToString(TotalMemory));

		if (ProcessorCount > 0)
			writer.WriteAttributeString("processorCount", XmlConvert.ToString(ProcessorCount));
	}
}

CreateCustomSignatureProvider

Event queue for all listeners interested in CreateCustomSignatureProvider events.

public event EventHandler<CreateCustomSignatureProviderEventArgs> CreateCustomSignatureProvider

Event Type

EventHandler<CreateCustomSignatureProviderEventArgs>

Last updated