Using the File and Stream classes can be quite cumbersome if you have to save a complicated data structure with linked objects. You have to save the individual fields to disk, remembering which field belongs to which object and which object instance was linked to another object instance. When restoring the data structure, you have to reconstitute that arrangement of fields and object references. The serialization technology provided by the .NET Framework does this for you. Serialization converts data structures to a byte stream. Deserialization converts the byte stream back to the data structures. Serializing and deserializing can be done on different machines so long as they both host the CLR. Objects can be serialized without writing special code because, as we have seen, the runtime can query the object's metadata to allow it to understand the memory layout of the object. To inform the framework that a class can be serialized, mark the class with the System.Serializable attribute. Any field or property that should not be serialized can be marked with the System.NonSerialized attribute. For example, fields that represent cached values need not be serialized. All you have to do is mark the class with the attribute, and then you do not have to write any other code to be able to serialize the class' fields. The Serialization example shows how to apply serialization to the case study's HotelBroker class in the Hotel assembly. The Serializable attribute has been applied to the HotelBroker class definition. The Serializable attribute has also been applied to all classes that are used by or derived from HotelBroker ( Broker , Hotel , HotelReservation , Reservable , and Reservation ), because in order for HotelBroker to be serializable, those classes have to be serializable as well. If any of those classes were not marked as serializable, a runtime exception would be thrown when the framework tries to serialize an object of that type. <Serializable()> Public Class Hotel Inherits Reservable ... <Serializable()> Public Class HotelReservation Inherits Reservation <Serializable()> Public Class HotelBroker Inherits Broker Implements IHotelInfo, IHotelAdmin, IHotelReservation Private Const MAXDAY As Integer = 366 Private Const MAXUNIT As Integer = 10 <NonSerialized()> Private cities As ArrayList ... <Serializable()> Public MustInherit Class Reservable ... <Serializable()> Public MustInherit Class Reservation ... <Serializable()> Public MustInherit Class Broker ... The cities field of HotelBroker has been marked as NonSerialized , since the hotel's city is saved with the serialized hotels and therefore can be restored, as the modified AddCity method demonstrates . The cities field would be Nothing if the HotelBroker class had been deserialized, because the cities field was not saved. [3] [3] Of course, we could have serialized the cities field and not have to deal with the case where cities could be Nothing , but we wanted to demonstrate the NonSerialized attribute. Private Sub AddCity(ByVal city As String) ' check if city already on list, add if not If cities Is Nothing Then cities = New ArrayList() Dim h As Hotel For Each h In units AddCity(h.City) Next End If If Not cities.Contains(city) Then cities.Add(city) End If End Sub Serialization Objects Although the framework knows how to save an object marked with the Serializable attribute, you still have to specify the format in which the object is saved and the storage medium. To specify the format in which an object is saved, you use an instance of an object that supports the IFormatter interface. [4] [4] How does the runtime know if a class supports the IFormatter interface? Query the metadata! The Framework ships with two such classes, System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and System.Runtime.Serialization.Formatters.Soap.SoapFormatter . The BinaryFormatter uses a binary, compact format for serializing and deserializing on platforms that support the CLR. The SoapFormatter uses the industry-standard SOAP protocol that is discussed in Chapter 15, "Web Services." Since it is an XML-based, and therefore a text-based, protocol, it can be used to communicate with a non-CLR-based platform. The binary format is faster when serializing and deserializing data. You can, of course, implement your own formatter classes. You might do this if you have to talk to a system with its own legacy byte format. The Serialization example has code to demonstrate saving and restoring both binary and SOAP formats using a FileStream . Of course you could use any Stream based class representing some data medium. Private Sub Save(ByVal broker As HotelBroker, _ ByVal formatter As String) Dim s As FileStream If formatter = "b" Then s = New FileStream("hotels.bin", FileMode.Create) Dim b As BinaryFormatter = New BinaryFormatter() b.Serialize(s, broker) Else s = New FileStream("hotels.txt", FileMode.Create) Dim sf As SoapFormatter = New SoapFormatter() sf.Serialize(s, broker) End If s.Close() End Sub Private Sub Load(ByRef broker As HotelBroker, _ ByVal formatter As String) Dim s As FileStream If formatter = "b" Then s = New FileStream("hotels.bin", FileMode.Open) Dim b As BinaryFormatter = New BinaryFormatter() broker = b.Deserialize(s) Else s = New FileStream("hotels.txt", FileMode.Open) Dim sf As SoapFormatter = New SoapFormatter() broker = sf.Deserialize(s) End If s.Close() ShowHotelList(broker.GetHotels()) End Sub Here is some sample output from the Serialization example: First we add a hotel and save it with the SOAP formatter. We then exit the program. Enter command: cities Atlanta Boston Commands: quit, cities, list, add, fetch, save Enter command: list City Name Rooms Rate Atlanta Dixie 100 115 Atlanta Marriott 500 70 Boston Sheraton 250 95 Commands: quit, cities, list, add, fetch, save Enter command: add Hotel City: Philadelphia Hotel Name: Franklin Number Rooms: 100 Room Rate: 200 Commands: quit, cities, list, add, fetch, save Enter command: save Formatter: b(inary), s(oap)s Commands: quit, cities, list, add, fetch, save Enter command: cities Atlanta Boston Philadelphia Commands: quit, cities, list, add, fetch, save Enter command: list City Name Rooms Rate Atlanta Dixie 100 115 Atlanta Marriott 500 70 Boston Sheraton 250 95 Philadelphia Franklin 100 200 Commands: quit, cities, list, add, fetch, save Enter command: quit We then run the program again and restore what we saved [5] in the first run. [5] If you look at the hotels.txt file, you will see a huge file with a lot of "empty" entries. This stems from the simplistic array data structure we used for reservations , which is a very sparse matrix. Enter command: cities Atlanta Boston Commands: quit, cities, list, add, fetch, save Enter command: list City Name Rooms Rate Atlanta Dixie 100 115 Atlanta Marriott 500 70 Boston Sheraton 250 95 Commands: quit, cities, list, add, fetch, save Enter command: fetch Formatter: b(inary), s(oap)s City Name Rooms Rate Atlanta Dixie 100 115 Atlanta Marriott 500 70 Boston Sheraton 250 95 Philadelphia Franklin 100 200 Commands: quit, cities, list, add, fetch, save Enter command: cities Atlanta Boston Philadelphia ISerializable Sometimes the serialization provided by the framework is not satisfactory. You can provide custom serialization for a class by implementing the ISerializable interface and adding a constructor to the class. The ISerializable interface has one member: GetObjectData . This method is used when data is serialized. The ISerializable example demonstrates how this is done. As before, the class has to be marked as Serializable . <Serializable()> Public Class HotelBroker Inherits Broker Implements IHotelInfo, IHotelAdmin, _ IHotelReservation, ISerializable ... The SerializationInfo class is used to store all the data that needs to be saved. The AddValue method is overloaded to handle the saving of various types, including object . [6] When you save the type, you provide a name so that it can be restored later. The StreamingContext class gives you information about the stream being used in the serialization. For example, you can find out if the stream being used is a file or is being remoted to another computer. [6] Some of the AddValue overloads are not CLS-compliant when the types being saved are not CLS-compliant types, such as unsigned integers. Be careful not to use those types where .NET language interoperability is required. You have to watch for this in other places in the .NET Framework, such as the Convert class or the Parse methods of the various CTS types or any other place where data is formatted, converted or read, or written out (such as the TextWriter classes). Public Sub GetObjectData(_ ByVal info As SerializationInfo, _ ByVal context As StreamingContext) _ Implements ISerializable.GetObjectData Dim numberHotels As Long = units.Count info.AddValue("NumberHotels", numberHotels) info.AddValue("Hotels", units) End Sub You also have to implement a special constructor that is used by the framework when the object is deserialized. It has the same arguments as GetObjectData does. Here you use the various Get methods on SerializationInfo to restore the data. Note that since we did not save the cities fieldwe had to manually restore it. The constructor is private because it is only used by the .NET Framework. If you forget to add the constructor, you will get a SerializationException when you try to restore the object. Private Sub New(_ ByVal info As SerializationInfo, _ ByVal context As StreamingContext) MyBase.New(MAXDAY, MAXUNIT) Dim numberHotels As Long = info.GetInt32("NumberHotels") units = info.GetValue(_ "Hotels", Type.GetType("ArrayList")) If numberHotels = units.Count Then Console.WriteLine("All hotels deserialized.") Else Console.WriteLine("Error in deserialization.") End If cities = New ArrayList() Dim h As Hotel For Each h In units AddCity(h.City) Next End Sub In this example we did custom serialization only for the HotelBroker object. For all the other objects, we still relied on the framework's serialization. This example works the same way that the Serialization example did. The sample output would look the same. |