This project is read-only.

Advanced Customization

Advanced customization involves creating a custom TypeSerializer class. This can either be accomplished by creating a class that implements ITypeSerializer or much easier by inheriting from TypeSerializerBase. If you inherit from TypeSerializerBase you can accomplish some standard customizations by simply overriding some of the virtual methods provided. Let's assume we have a custom class called LegalDocument that inherits from the Document class.
public class Document
{
   public string Author { get; set; }
   public DateTime PublishedAt { get; set; }
   public string Title { get; set; }
   public string Body { get; set; }
}
public class LegalDocument : Document
{
}
Now let us assume that the contents of any LegalDocument is sensitive and so we wish to encrypt the serialized output of the body while it is being stored. This can easily be accomplished by creating a custom serializer.
public class LegalDocumentSerializer : TypeSerializerBase<LegalDocument>
{
   public string Key { get; set; }

   public LegalDocumentSerializer(
      Settings settings, 
      ITypeSerializerFactory factory, 
      ITypeInspector inspector, 
      IReferenceManager refManager, 
      string key)
      : base(settings, factory, inspector, refManager)
   {
      Key = key;
   }

   protected override object GetEntityValue(object entity, TypeMemberInfo memberInfo)
   {
      var protectedContent = (memberInfo.Name == "Body");
      var result = base.GetEntityValue(entity, memberInfo);
      return protectedContent ? Encrypt(result.ToString(), Key) : result;
   }
   
   protected override string GetNodeContents(XmlReader reader)
   {
      var protectedContent = (reader.Name == "Body");
      var result = base.GetNodeContents(reader);
      return protectedContent ? Decrypt(result, Key) : result;
   }

   protected string Decrypt(string content, string key)
   {
      // Implement some decryption code here
   }

   protected string Encrypt(string content, string key)
   {
      // Implement some encryption code here
   }
}
Now, all that is left is to register your custom type serializer with the core serializer instance and from that point forward the content in the Body property of your LegalDocument instances will be encrypted. An example of this usage follows.
string encryptionKey = "this is my sad encryption key";
Serializer.Instance
  .RegisterType<LegalDocument>()
  .ToTypeSerializer<LegalDocumentSerializer>()
  .WithConstructorArgument("key", encryptionKey);
Serializer.SerializeToFile("C:\Document.xml", legalDocumentInstance);

Last edited Mar 9, 2015 at 1:39 AM by WiredWiz, version 17