Xtreme Visual Basic Talk

Xtreme Visual Basic Talk (http://www.xtremevbtalk.com/)
-   Tutors' Corner (http://www.xtremevbtalk.com/tutors-corner/)
-   -   Saving using Serialization (http://www.xtremevbtalk.com/tutors-corner/211266-saving-using-serialization.html)

wayneph 02-14-2005 08:30 AM

Saving using Serialization
 
1 Attachment(s)
  • Have you ever wondered how programs create those "unreadable" files that you can't just modify with Notepad?
  • Have you ever had a list of Strings that you've had to loop through to save in or read individually from a file?
  • Have you ever wanted to save all the properties of an object so you can use it again later, and had 20 (or more) print statements just for the saving the properties?

Now VB programmers have an easy way to solve all of these common saving problems that's quick and simple. It's built into the .NET Framework and called Serialization.

The Basics
Serialization takes objects and creates a snapshot that you can refer back to at any time. Many of the built in .NET classes already support this process. Some of the main objects that don't support it maintain connections to databases or sockets, that can't be saved in the snapshot. Any of your custom classes can be set up to support serialization just by adding the <Serializable()> attribute or by implementing the ISerializable interface. In addition to saving to files, serialization can be used to save objects anywhere that you can write to with a stream. Objects can be saved into a Database or sent to a Message Queue and received on another system.

This example uses a BinaryFormatter to do the serialization. It takes a picture of all Public and Private properties and variables. Another option is to use the SOAPFormatter which wraps an object into a SOAP envelop that can easily be transmitted using a Web Service. Both of these classes provide similar functionality with just a small change in the way they are stored. The XML class also supports a "light" Serialization method that only saves the Public properties of a class.

Creating a Serializable Object
To create an object that can be serialized you only need to add a single attribute to your class definition. This attribute will tell the Serialization classes that this class can be saved. Any members that are part of the Class must also be serializable. For example, if you can't have a Database Connection as a member of a class that will be serialized.

Code:
<Serializable()> Public Class Car Private mMake As String Public Property Make() As String Get Return mMake End Get Set(ByVal Value As String) mMake = Value End Set End Property End Class

In this example if you had another "Tire" class it could only be serialized as part of this class if you also created the Tire Class as Serializable.

Saving an Object
As mentioned above you can save a file to any stream object. The sample will write the object to a file that is saved on the hard drive.

With these simple steps, you have saved an entire object to a file. Obviously with just a Make in your Car object you could have just as easily saved the one value. But what if you had a Year, Model and Color, or an ArrayList with more than one car?

Code:
'BinaryFormatter comes from the System.Runtime.Serialization.Formatters.Binary 'Namespace and is Imported at the top of my Form. Dim myCar as New Car() myCar.Make = "Chevrolet" Dim fs as IO.FileStream("C:\mycar.car", IO.FileMode.Create) Dim bf as New BinaryFormatter bf.Serilaize(fs, myCar) fs.Close() fs = Nothing bf = Nothing myCar = Nothing

Retrieving an Object
Saving a file is all fine and dandy, but it doesn't do you a whole lot of good unless you can actually get it back into your object. The steps to open a file are just as easy as the ones to save it.

The one thing you need to know here is that you need to Cast the Deserialized object to the same type it was serialized from. You should wrap the method in a Try Catch block to trap any errors if the format can not be read. I've left that out here for simplicity, but any production system should include it.

If you make any changes to your Class in between the time you save the file and try to open it, you will get an error because the Types don't match. You can write a program that contains both of your objects (the new and old) to open the file, transfer the properties and reserialize the object to "upgrade" your files.

Code:
'BinaryFormatter comes from the System.Runtime.Serialization.Formatters.Binary 'Namespace and is Imported at the top of my Form. Dim myCar as Car Dim fs as New IO.FileStream("C:\mycar.car", IO.FileMode.Open, IO.FileAccess.Read) Dim bf as New BinaryFormatter myCar = DirectCast(bf.Deserialize(fs), Car) fs = Nothing bf = Nothing MessageBox.Show(myCar.Make)

Additional Resources
The Sample
This sample contains a Car Class that you can create properties for and add into an ArrayList. The Open and Save buttons will allow you to save your list of cars to a file and then open them up again for display in a DataGrid. The project file is from VS .NET 2003, but you should be able to take the class files and use them in 2002 as well. It's not hard, but it's not automatic either.


All times are GMT -6. The time now is 04:33 PM.

Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Search Engine Optimisation provided by DragonByte SEO v2.0.15 (Lite) - vBulletin Mods & Addons Copyright © 2017 DragonByte Technologies Ltd.
All site content is protected by the Digital Millenium Act of 1998. Copyright©2001-2011 MAS Media Inc. and Extreme Visual Basic Forum. All rights reserved.
You may not copy or reproduce any portion of this site without written consent.