Simplest Example: Basic Serialization


As I always do when learning a new piece of software, I wrote the simplest example I could think of to demonstrate XML serialization, as shown in Figure 7-3. The program contains a class named Point, having two member variables named X and Y, as shown in Listing 7-2. The user enters two integers, the x and y coordinates of a point. The program then creates a Point object containing these values and serializes the object into an XML document. The user can also open an XML document containing a serialized Point object, and the program will deserialize the Point object and display its values.

A simple example starts here.


Figure 7-3: Simplest serialization sample program.

Listing 7-2: Point class for simplest serialization example.

start example
Public Class Point Public X As Integer Public Y As Integer End Class
end example

The code for serializing a Point object into an XML document is shown in Listing 7-3. When the user clicks Serialize, the program pops up a dialog box asking for the name of the file to write the document into and creates an empty file with the name that the user enters. Next the program creates a new object of the Point class and sets its member variables X and Y to the values that the user entered. We then create the serializer object, of class System.Xml.Serialization.XmlSerializer, passing in its constructor the type of object that we want it to serialize, in this case a Point. Finally, we tell the serializer object to serialize its data into the file by calling its Serialize method. The resulting XML document is shown in Listing 7-4. It doesn’t get much easier than this, does it?

Listing 7-3: Code for serializing a point.

start example
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click ’ Pop up dialog box asking user for file name to ’ serialize Point object into. Dim dlg As New System.Windows.Forms.SaveFileDialog() If (dlg.ShowDialog = DialogResult.OK) Then ’ Create XML document named by the user Dim xmlstream As New _ System.IO.FileStream(dlg.FileName, _ System.IO.FileAccess.ReadWrite) ’ Make a new object of class Point containing X ’ and Y values specified by user. Dim here As New Point() here.X = TextBox1.Text here.Y = TextBox2.Text ’ Make a new serializer for the Point class Dim serializer As New _ Xml.Serialization.XmlSerializer(GetType(Point)) ’ Write (serialize) the Point into the XML document serializer.Serialize(xmlstream, here) ’ Close the file xmlstream.Close() End If End Sub
end example

Listing 7-4: XML document produced by serialization.

start example
<Point> <X>5</X> <Y>3</Y> </Point>
end example

When I want to deserialize the object, the process is quite similar and it uses the same serializer class. The code is shown in Listing 7-5. The sample program pops up a dialog box allowing the user to select the file containing her serialized point and opens that file for reading. Next we create an object of the same class that did the original serialization, passing it the type of the object we want it to read, again a Point. The function Deserialize reads the XML document, creates the object of the specified class, sets its public data fields to the values specified in the XML document, and returns it to the caller. The sample program reads the values of the new object and puts them into text boxes for you to look at. Again, this is about as easy as anything ever gets in this business.

Listing 7-5: Deserializing the XML document into a .NET object.

start example
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button2.Click ’ Pop up dialog box asking user which XML ’ file contains the serialized Point object Dim dlg As New System.Windows.Forms.OpenFileDialog() If (dlg.ShowDialog = DialogResult.OK) Then ’ Open the XML document selected by the user Dim xmlstream As New _ System.IO.FileStream(dlg.FileName, _ System.IO.FileMode.Open, _ System.IO.FileAccess.Read) ’ Make a serializer for the Point class Dim serializer As New _ Xml.Serialization.XmlSerializer(GetType(Point)) ’ Read (deserialize) the document into the Point object Dim here As Point here = serializer.Deserialize(xmlstream) ’ Place desired items into text boxes TextBox1.Text = here.X TextBox2.Text = here.Y ’ Close the file xmlstream.Close() End If End Sub 
end example

When you run the sample, you’ll see that the serialization process takes a few seconds. If you explore further, you’ll find that creating the serializer takes most of this time and actually serializing the object takes very little. When you create the serializer, it reads through the metadata of the class that you have passed it to find the names and types of the objects and variables it must write to or read from an XML document. This process uses the .NET Reflection API, which I discuss in Chapter 11. It is somewhat complex, hence the time it takes. You can imagine that because creating a serializer takes a noticeable amount of time for a tiny, stupid object like Point, creating a serializer for a larger object will take much more time, and in fact it does. Fortunately, you can reuse the serializer for other operations on the same type of object; you don’t need a separate one for each instance. This means that when your program starts up, you will probably want to precreate all the serializers you will require and keep them around throughout your program’s execution. ASP.NET applications may find this a good use of the Application object. I didn’t use this technique in the sample because I wanted each operation’s code listing to stand alone, and you can see the performance price that I paid for it.

Creating serializers is somewhat slow, so you probably want to reuse them as often as possible.

start sidebar
Tips from the Trenches

My clients report that they often like to use XML files for application configuration, as Microsoft does throughout .NET. The XML serialization mechanism that I’ve just described makes trivial the task of defining your own configuration object and storing it in an XML configuration file, which an administrator can easily edit. Combining XML serialization with Windows Forms (Chapter 5) lets you quickly throw together a handy editing tool, making life much easier for administrators and support people. (Don’t get me started on the contempt that the ASP.NET developers display for their customers by refusing to supply such a tool when the rest of .NET does.) Your application can use the class System.IO.FileSystemWatcher to be notified when an administrator changes the configuration file, thereby allowing you to respond to those changes without shutting down your program.

end sidebar




Introducing Microsoft. NET
Introducing Microsoft .NET (Pro-Developer)
ISBN: 0735619182
EAN: 2147483647
Year: 2003
Pages: 110

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