I try to serialize and deserialize the class License.
The serialization work well but when I try to deserialize the file I get the error message above.
This is the base class:
[Serializable]
public abstract class LicenseBase
{
/// <summary>
/// Initializes a new instance of the <see cref="LicenseBase"/> class.
/// </summary>
protected LicenseBase()
{
ApplicationName = string.Empty;
UniqueId = string.Empty;
}
/// <summary>
/// Application name this license is used for
/// </summary>
[Browsable(false)]
public string ApplicationName { get; set; }
/// <summary>
/// Unique hardware id this license will work on
/// </summary>
[Browsable(false)]
public string UniqueId { get; set; }
}
And this the derived:
public class License : LicenseBase
{
[Browsable(false)]
public bool Test { get; set; }
}
This is the method to serialize the class:
public void WriteLicense<T>(T license) where T : LicenseBase
{
if (license is null)
{
throw new ArgumentNullException(nameof(license));
}
//Serialize license object into XML
XmlDocument licenseObject = new XmlDocument();
using (StringWriter writer = new StringWriter())
{
XmlSerializer serializer = new XmlSerializer(typeof(LicenseBase), new[]
{
license.GetType(), typeof(License)
});
serializer.Serialize(writer, license);
licenseObject.LoadXml(writer.ToString());
}
//Sign the XML
SignXml(licenseObject);
//Convert the signed XML into BASE64 string
string writeToFile = Convert.ToBase64String(Encoding.UTF8.GetBytes(licenseObject.OuterXml));
File.WriteAllText(LICENSE_FILENAME, writeToFile);
}
This is the code to read the class:
public T ReadLicense<T>() where T : LicenseBase
{
T license;
if (!File.Exists(LICENSE_FILENAME))
{
alarmManager.ReportAlarm(licenseFileMissingAlarm, true, true);
return null;
}
string licenseFileData = File.ReadAllText(LICENSE_FILENAME);
XmlDocument xmlDoc = new XmlDocument { PreserveWhitespace = true };
xmlDoc.LoadXml(Encoding.UTF8.GetString(Convert.FromBase64String(licenseFileData)));
// Verify the signature of the signed XML.
if (VerifyXml(xmlDoc, PrivateKey))
{
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");
if (xmlDoc.DocumentElement != null)
{
_ = xmlDoc.DocumentElement.RemoveChild(nodeList[0]);
}
string licenseContent = xmlDoc.OuterXml;
//Deserialize license
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(licenseContent))
{
license = (T)serializer.Deserialize(reader);
}
}
else
{
license = null;
}
return license;
}
The content of licenseContent is
<?xml version="1.0" encoding="UTF-8"?>
<LicenseBase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="License">
<ApplicationName>Test</ApplicationName>
<UniqueId>c4aed5a8-8d22-47b0-bda4-700ac906bfd5</UniqueId>
<Test>true</Test>
</LicenseBase>