How to use OnSerializing and OnDeserializing attributes?

10,920

OnDeserializing isn't used by the XmlSerializer....to perform custom serialization with the XmlSerializer, derive from it, and handle the IXmlDeserializationCallback interface.

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).

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).

Share:
10,920
rtuner
Author by

rtuner

Enthusiast

Updated on June 27, 2022

Comments

  • rtuner
    rtuner almost 2 years

    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]);
            }
        }
    }