Object Persistence


Object persistence is the ability to persist an object's state to some sort of storage medium. This enables an object to save itself in a particular format, to be either persisted or transported and restored at a convenient point in time.

The .NET Framework enables you to persist objects to disk, memory, or other storage mediums through serialization. It also provides you with some default serializers to accomplish this task. The .NET Framework provides two basic forms of serialization: binary and XML. Although there are more differences, as described in Table 7.2, the basic difference is that XML is a readable and open standard, whereas binary is not.

Table 7.2. Binary and XML Serialization

Serialization Form

Description

Binary

Binary serialization serializes all fields and properties of a class. It provides type fidelity and is used by Remoting to transfer objects to another computer by value.

XML

XML serialization serializes only the public fields and properties in a class. It does not preserve type fidelity.


In the following sections, you will learn how to serialize (store) objects to disk and then deserialize (restore) them.

Serializing Objects

To serialize an object, it is necessary to make that object serializable. To do this you can either mark the object as serializable by using the Serializable attribute or by implementing the ISerializable interface in your object and serializing the desired fields yourself.

Marking the object as serializable by using the Serializable attribute is by far the easier of the two approaches to implement. The following code snippet demonstrates how to do this:

 [Serializable] class SomeObject {  ... } 

Using the ISerializable interface takes a little more effort. It will be described in the next section, "Extending Standard Serialization."

Listing 7.9 demonstrates how to use a BinaryFormatter to serialize and deserialize an object from disk.

Listing 7.9. SerializationDeSerializationExample
 using System; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.IO; using System.Collections; namespace SAMS.VisualCSharpUnleashed.Chapter7 {   public enum serialize { Binary, XML };   [Serializable]   public class CustomAddress   {     protected string m_id;     protected string m_city;     protected string m_country;     protected string m_postalCode;     protected string m_state;     protected string m_streetAddress1;     protected string m_streetAddress2;     protected string m_suite;     public void Copy(CustomAddress address)     {       if(null != address)       {         m_id                                             = address.m_id;         m_city                                           = address.m_city;         m_country                                        = address.m_country;         m_postalCode                                     = address.m_postalCode;         m_state                                          = address.m_state;         m_streetAddress1                                 = address.m_streetAddress1;         m_streetAddress2                                 = address.m_streetAddress2;       }     }     public CustomAddress()     {     }   }   /// <summary>   /// Address:   /// </summary>   [Serializable]   public class Address : CustomAddress   {     public Address() : base()     {     }     public Address(string address, string city, string state, string zip) : base()     {       StreetAddress1  = address;       City            = city;       State           = state;       PostalCode      = zip;     }     public string Country {get { return m_country; } set { m_country = value; } }     public string Id { get { return m_id; } set { m_id = value; } }     public string PostalCode       { get { return m_postalCode; } set { m_postalCode = value; } }     public string State { get { return m_state; } set { m_state = value; } }     public string City { get { return m_city; } set { m_city = value; } }     public string StreetAddress1      { get { return m_streetAddress1; } set { m_streetAddress1= value; } }     public string StreetAddress2      { get { return m_streetAddress2; } set { m_streetAddress2= value; } }   }   [Serializable]   public class User : Address   {     protected string m_userName;     public User() : base()     {     }     public User(string userName, string address,       string city, string state, string zip) : base(address, city, state, zip)     {       m_userName = userName;     }     public string UserName { get {return m_userName; } set { m_userName = value; } }   }   // Generic class to serialize objects using the XML serializer.   public class GenericXMLSerializer   {     protected GenericXMLSerializer()     {     }     public static void SerializeObject(string filename, object value, Type type)     {       System.Xml.XmlTextWriter xmlWriter =         new XmlTextWriter(         new System.IO.StreamWriter(           System.IO.File.Open( filename, System.IO.FileMode.Create ) ) );       try       {         System.Xml.Serialization.XmlSerializer serializer =           new System.Xml.Serialization.XmlSerializer( type );         xmlWriter.Formatting = Formatting.Indented;         serializer.Serialize(xmlWriter, value);       }       finally       {         xmlWriter.Close();       }     }     public static object DeserializeObject(string filename, Type type)     {       object result = null;       XmlTextReader reader = new XmlTextReader(filename);       try       {         System.Xml.Serialization.XmlSerializer serializer =           new System.Xml.Serialization.XmlSerializer(type);         result = serializer.Deserialize(reader);       }       finally       {         reader.Close();       }       return result;     }   }   // Generic class to serialize objects using the Binary Formatter.   public class GenericBinarySerializer   {     protected GenericBinarySerializer()     {     }     public static void SerializeObject(string filename, object value)     {       BinaryFormatter binaryWriter = new BinaryFormatter();       using(FileStream fs =         new System.IO.FileStream(filename, System.IO.FileMode.Create))       {         binaryWriter.Serialize(fs, value);       }     }     public static object DeserializeObject(string filename)     {       object result = null;       BinaryFormatter binaryWriter = new BinaryFormatter();       using(FileStream fs =         new System.IO.FileStream(filename, System.IO.FileMode.Open))       {         result = binaryWriter.Deserialize(fs);       }       return result;     }   }   class SerializationDeserializationExample         {     public static void SerializeObject(       string filename, object value, Type type, serialize serializationType)     {       switch(serializationType)       {         case serialize.Binary:           GenericBinarySerializer.SerializeObject(filename, value);           break;         case serialize.XML:           GenericXMLSerializer.SerializeObject(filename, value, type);           break;       }     }     public static object DeserializeObject(string filename,       Type type, serialize serializationType)     {       object result = null;       switch(serializationType)       {         case serialize.Binary:           result = GenericBinarySerializer.DeserializeObject(filename);           break;         case serialize.XML:           result = GenericXMLSerializer.DeserializeObject(filename, type);           break;       }       return result;     }     [STAThread]     static void Main(string[] args)     {       string filePath      = @"c:\user.object";       // To change the storage mechanism, simply change the       // following variable to the desired method.       // Note:  If you change the storage mechanism,       // you will have to manually delete the file (If it exists).       serialize serializationType = serialize.Binary;       if(!File.Exists(filePath))       {         User newUser =           new User("Lonny",  "123 Nowhere Street",             "Raleigh",    "NC", "27615");         SerializeObject(filePath, newUser, typeof(User), serializationType);       }       User user =        (User) DeserializeObject(filePath, typeof(User), serializationType);       System.Console.WriteLine("{0} lives at {1} in {2}, {3} {4}",         user.UserName, user.StreetAddress1,         user.City, user.State, user.PostalCode);       System.Console.ReadLine();     }         } } 

Extending Standard Serialization

To do this, you must first realize the interface and then implement the ISerializable.GetObjectData method. The following code snippet demonstrates the minimum information required to implement this method:

 void ISerializable.GetObjectData(SerializationInfo info,   StreamingContext context) {   info.SetType(typeof(int));   context = m_value; } 

In the following example, Listing 7.10, you will see how to take a class that is normally serializable and limit the fields that are actually persisted to disk. This listing is a good example of how to extend the standard serialization that is provide with the .NET Framework.

Listing 7.10. ExtendingSerialization Example
 using System; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.IO; namespace SAMS.VisualCSharpUnleashed.Chapter7 {   [Serializable()]   public class UselessInformation : ISerializable   {     private string m_doNotStoreThis = string.Empty;     private string m_storeThis      = string.Empty;     public UselessInformation()     {     }     private UselessInformation(SerializationInfo info, StreamingContext context)     {       m_storeThis = (string) info.GetValue("StoreThis Here", m_storeThis.GetType());     }     public string DoNotStore     {       get { return m_doNotStoreThis; }       set { m_doNotStoreThis  = value; }     }     public string StoreThis     {       get { return m_storeThis; }       set { m_storeThis  = value; }     }     public void GetObjectData(SerializationInfo info, StreamingContext context)     {       info.AddValue("StoreThis Here", m_storeThis);     }   }     // Generic class to serialize objects using the Binary Formatter.   public class GenericBinarySerializer   {     protected GenericBinarySerializer()     {     }     public static void SerializeObject(string filename, object value)     {       BinaryFormatter binaryWriter = new BinaryFormatter();       using(FileStream fs =         new System.IO.FileStream(filename, System.IO.FileMode.Create))       {         binaryWriter.Serialize(fs, value);       }     }     public static object DeserializeObject(string filename)     {       object result = null;       BinaryFormatter binaryWriter = new BinaryFormatter();       using(FileStream fs =         new System.IO.FileStream(filename, System.IO.FileMode.Open))       {         result = binaryWriter.Deserialize(fs);       }       return result;     }   }   class ExtedingSerializationExample   {     [STAThread]     static void Main(string[] args)     {       string filePath      = @"c:\user.object";       File.Delete(filePath);       if(!File.Exists(filePath))       {         UselessInformation info = new UselessInformation();         info.DoNotStore = "Should not be stored.";         info.StoreThis  = "Needs to be stored.";         GenericBinarySerializer.SerializeObject(filePath, info);       }       UselessInformation info2 =        (UselessInformation) GenericBinarySerializer.DeserializeObject(filePath);       string doNotStoreResult =        ((info2.DoNotStore == string.Empty) ? "** NO VALUE **" : "Something is broke");       System.Console.WriteLine(        "Value stored in 'StoreThis': {0} \r\nValue Stored in DoNotStoreThis: {1}",        info2.StoreThis, doNotStoreResult);       System.Console.ReadLine();     }   } } 



    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net