How to use OnSerializing and OnDeserializing attributes?
.net, c#, serialization, xml
Solution
`OnDeserializing` isn't used by the `XmlSerializer`....to perform custom serialization with the `XmlSerializer`, derive from it, and handle the `IXmlDeserializationCallback` interface.
- How do you find out when you've been loaded via XML Serialization?
Here is one suggested workaround (basically you would create a "Twin" class that returned encrypted data in it's gets, and did unecryption in its sets...you wouldn't only use the "Twin" during your serialization task...copy across from User into your User2).
- http://codethatworks.wordpress.com/2009/11/15/xmlserializer-and-using-onserializing-ondeserialized-attributes/
Or you might be able to use the DataContractSerializer instead (but it is restrictive in that it doesn't support XML Attributes, only Elements in the serialized stream).
- XML Serialisation - When To Use DataContractSerializer / Binary / XMLSerialiser
Problem
I have tried to implement auto encryption and decryption in my xml, but it doesn't just work, i.e. The data is not encrypted. What could be the reason? My code is shown below. I'm using the `XmlSerializer` class. Thanks ``` [Serializable] public class User { public string _username; public string _password; public string[] _roles; [XmlIgnore] public string Username { get { return _username; } set { _username = value; } } [XmlIgnore] public string Password { get { return _password; } set { _password = value; } } [XmlIgnore] public string[] Roles { get { return _roles; } set { _roles = value; } } [OnDeserializingAttribute] internal void DecryptPersonalData(StreamingContext context) { _username = Crypto.Decrypt(_username); _password = Crypto.Decrypt(_password); for (int i = 0; i < _roles.Length; i++) { _roles[i] = Crypto.Decrypt(_roles[i]); } } [OnSerializingAttribute] internal void EncryptPersonalData(StreamingContext context) { _username = Crypto.Encrypt(_username); _password = Crypto.Encrypt(_password); for (int i = 0; i < _roles.Length; i++) { _roles[i] = Crypto.Encrypt(_roles[i]); } } } ```