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
Name
Description
The object.
Exceptions
Name
Description
Thrown when the license argument is null.
Load(Stream)
Loads the license from the specified stream.
public void Load(Stream stream)
Parameters
Name
Description
Specify the stream where to load the license.
Exceptions
Name
Description
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
Name
Description
The file name where to save the license.
Exceptions
Name
Description
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
Name
Description
The XML license document.
Exceptions
Name
Description
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
Name
Description
The XML license string.
Remove(ILicense)
Removes a with a given key from the .
public bool Remove(ILicense license)
Parameters
Name
Description
The object to be removed.
Returns
Name
Description
true if the license is successfully removed, false if it fails to remove the license.
Exceptions
Name
Description
Thrown when the license argument is null.
Save(Stream)
Saves the current license state to the specified stream.
public void Save(Stream stream)
Parameters
Name
Description
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
Name
Description
Thrown when the stream argument is null.
Save(string)
Saves the current license state to a given file.
public void Save(string path)
Parameters
Name
Description
The file path where to save the license.
Exceptions
Name
Description
Thrown when one or more required arguments are null.
Sign()
Add a signature to the current license object.
public void Sign()
Exceptions
Name
Description
Thrown when the signature cannot be generated.
ToLicenses()
Converts this object to a object.
public IEnumerable<ILicense> ToLicenses()
Returns
Name
Description
This object as a .
ToReadableString(string)
Creates and returns a string representation of the current XML license.
public string ToReadableString(string format)
Parameters
Name
Description
Describes the format to use.
Returns
Name
Description
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
Name
Description
Whether to format the XML output.
Returns
Name
Description
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
Name
Description
true if the signature id valid, false if the signature is not present or not valid.
Exceptions
Name
Description
Thrown when the signature cannot be validated.
CreateCustomRestriction
Event queue for all listeners interested in CreateCustomRestriction events.
public event EventHandler<CreateCustomRestrictionEventArgs> CreateCustomRestriction
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");
' Create a digital signer
Dim signer As RSASignature = RSASignature.CreateFromKeyFile("Keys.snk")
' Minimum hardware requirements
' Total Memory 4 Gb, Two Cpu
Dim totalMemory As Integer = 4096
Dim cpuCount As Integer = 2
Dim 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"));
Dim manager As New XmlLicenseManager()
AddHandler manager.CreateCustomRestriction, Sub(s, e)
If e.RestrictionName = "MinimumRequirements" Then
e.Restriction = New MinimumRequirementsRestriction()
End If
End Sub
Dim license As XmlLicense = 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));
}
}
Public Class MinimumRequirementsRestriction
Inherits Restriction
Implements IXmlSerializable
Private _totalMemory As Long
Private _processorCount As Int32
Public Overrides ReadOnly Property Name As String
Get
Return "MinimumRequirements"
End Get
End Property
Public ReadOnly Property TotalMemory As Long
Get
Return _totalMemory
End Get
End Property
Public ReadOnly Property ProcessorCount As Long
Get
Return _processorCount
End Get
End Property
Public Sub New()
End Sub
Public Sub New(ByVal totalMemory As Long, ByVal processorCount As Int32)
Me._totalMemory = totalMemory
Me._processorCount = processorCount
End Sub
Public Overrides Function Validate(context As ILicenseContext, type As Type, instance As Object) As ValidationResult
Dim sys = DirectCast(context.GetService(GetType(ISystemInformation)), ISystemInformation)
Dim totalMem = ToMegabytes(sys.TotalPhysicalMemory)
If (totalMem < Me.TotalMemory Or sys.ProcessorCount < Me.ProcessorCount) Then
' Cannot run on this machine
Return ValidationResult.NotPassed
End If
Return MyBase.Validate(context, type, instance)
End Function
Private Shared Function ToMegabytes(ByVal value As Long) As Long
Return value / 1024 / 1024
End Function
Public Function GetSchema() As Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema
Return Nothing
End Function
Public Sub ReadXml(reader As Xml.XmlReader) Implements IXmlSerializable.ReadXml
reader.MoveToContent()
Dim totalMemory = reader.GetAttribute("totalMemory")
If Not String.IsNullOrEmpty(totalMemory) Then
Me._totalMemory = XmlConvert.ToInt64(totalMemory)
End If
Dim processorCount = reader.GetAttribute("processorCount")
If Not String.IsNullOrEmpty(processorCount) Then
Me._processorCount = XmlConvert.ToInt32(processorCount)
End If
Dim isEmptyElement = reader.IsEmptyElement
reader.ReadStartElement()
If Not isEmptyElement Then
reader.ReadEndElement()
End If
End Sub
Public Sub WriteXml(writer As Xml.XmlWriter) Implements IXmlSerializable.WriteXml
If Me.TotalMemory > 0 Then
writer.WriteAttributeString("totalMemory", XmlConvert.ToString(TotalMemory))
End If
If Me.ProcessorCount > 0 Then
writer.WriteAttributeString("processorCount", XmlConvert.ToString(ProcessorCount))
End If
End Sub
End Class
CreateCustomSignatureProvider
Event queue for all listeners interested in CreateCustomSignatureProvider events.
public event EventHandler<CreateCustomSignatureProviderEventArgs> CreateCustomSignatureProvider