< Day Day Up > |
TechniqueSerialization is the term used for the process that creates a snapshot of a current object's state and writes that information to a stream, which in most cases means to a file. The .NET Framework contains three main serialization schemes: binary, XML, and Simple Object Access Protocol (SOAP) serialization. The first step in serializing an object is to apply the Serializable attribute to it, as shown in the following code. Without this attribute, the object cannot be serialized. However, even if the attribute is applied to a class, you might not be able to serialize it if any base classes do not have the attribute applied either. In other words, if you want to serialize a class derived from System.Windows.Forms.Form , the serialization process will throw an exception because the Form class cannot be serialized: [ Serializable ] public class SerializedObject { public string stringVariable = "This is a public string variable"; public int intVariable = 42; private int[] intArray; public SerializedObject() { intArray = new int[]{1,2,3,4,5,6,7,8,9,10}; } public int[] Integers { get { return intArray; } set { intArray = value; } } } The code listing is enough to make an object serializable using any of the serialization techniques available. Later sections build upon this simple example to control the serialization process, but this code will never have to change. Once you create a serializable object, you have to write the code to perform the serialization. Before you do so, you have to add one of three namespaces to your project, depending on the serialization technique you use. Binary serialization, as its name implies, converts an object into a stream of bytes that can then be written to a fixed disk. You use the BinaryFormatter object defined in the System.Runtime.Serialization.Formatters.Binary namespace. The actual act of serialization needs a stream object and the object being serialized. To serialize an object using a BinaryFormatter , call the Serialize method, passing a stream object and the object to serialize, as shown in the following code: private void mnuSaveBinary_Click(object sender, System.EventArgs e) { saveFileDialog1.FilterIndex = 1; if( saveFileDialog1.ShowDialog() != DialogResult.OK ) return; // create the serialization formatter IFormatter formatter = new BinaryFormatter(); // open a file stream Stream stream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); // serialize the object using the formatter formatter.Serialize(stream, mObject); // close the file stream stream.Close(); } The SoapFormatter is similar, with the major difference being the output of the serialization process. In keeping with well-defined naming standards, the SoapFormatter serializes objects using the SOAP format, which you will see more of in Chapter 17, "Web Services." At the most basic level, SOAP is an XML file format. In addition to adding the namespace declaration, System.Runtime.Serialization.Formatters.Soap also must add an assembly reference to the assembly of the same name. To serialize an object using a SoapFormatter , simply change the code shown earlier by creating a SoapFormatter object instead of a BinaryFormatter . XML serialization is one of the most customizable of the all serialization techniques. However, the actual serialization process is virtually identical to the previous two techniques. The main serialization class used for XML serialization is the XmlSerializer class. At a minimum, the constructor for an XmlSerializer object needs a type reference to the object being serialized. You can either use the typeof keyword or call the GetType method on the object being serialized. The other optional constructor parameters give you the ability to map internal variables or properties within the class being serialized into different attribute names as well as the ability to change the root element of the final XML document. Once the XmlSerializer object is created, you once again create a new stream and call the Serialize method to complete serialization: private void mnuSaveXML_Click(object sender, System.EventArgs e) { saveFileDialog1.FilterIndex = 2; if( saveFileDialog1.ShowDialog() != DialogResult.OK ) return; // create the XML serializer. mObject is the object being serialized XmlSerializer formatter = new XmlSerializer( mObject.GetType() ); // open a new file stream Stream stream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); // serialize the object formatter.Serialize( stream, mObject ); // close the file stream stream.Close(); } CommentsSerialization is a powerful tool when used correctly. Once you become familiar with how to create serialized objects within your applications, you'll start to see little areas where the techniques would fit in well. One particular application of this method could be configuration. You could create a class that holds configuration information for your application. As the user changes properties within your application, the configuration object can be serialized to the hard disk. Then, whenever your application loads, the configuration object can be deserialized (explained in the next section) and the user settings are restored. If you compare this method to other configuration methods such as reading XML or INI files, you will see the advantage. In those methods , the process generally entails reading a value from the file, setting a certain member variable, and repeating that process for each member. As new member variables are added, you have to also add the code to read in the configuration settings for that variable. With serialization, however, all you have to worry about is the initial code to enable serialization, and then you add new member variables and properties without having to revisit the configuration code. Serialization wasn't created just so you could save and later restore an object from disk, although that is a pretty handy feature to have. One of the biggest advantages lies within distributed computing. For instance, if one computer has an assembly containing a certain data type and another remote computer does also, you can create an application that utilizes one of the serialization techniques to send an object snapshot to the remote computer so that it can be recreated in its exact state on a different machine. This section looked at two types of serialization, binary and XML. Each method has its distinct advantages and disadvantages, which you should weigh when formulating your application's design. Binary serialization's strongest advantage is the accurate representation of type data. Because binary serialization serializes both public and private members of an object, the state of that object can be faithfully recreated during deserialization. You should not use XML serialization, on the other hand, if you need to save the exact state of an object because only public properties and fields are serialized. Any instance data contained within private fields is lost during the serialization process. However, XML serialization's greatest strength is its portability. Because XML and SOAP are both open standards, any XML-aware application or technology can consume the final output of the serialization process. |
< Day Day Up > |