Export (0) Print
Expand All
Around the World with Visual Basic
Asynchronous Method Execution Using Delegates
Building a Progress Bar that Doesn't Progress
Calling All Operators
Create a Graphical Editor Using RichTextBox and GDI+
Creating A Breadcrumb Control
Creating a Five-Star Rating Control
Creating and Managing Secondary Threads
Data Binding Radio Buttons to a List
Deploying Assemblies
Designing With Custom Attributes
Digital Grandma
Doing Async the Easy Way
Extracting Data from .NET Assemblies
Implementing Callbacks with a Multicast Delegate
Naming and Building Assemblies in Visual Basic .NET
Programming Events of the Framework Class Libraries
Programming I/O with Streams in Visual Basic .NET
Reflection in Visual Basic .NET
Remembering User Information in Visual Basic .NET
Advanced Basics: Revisiting Operator Overloading
Scaling Up: The Very Busy Background Compiler
Synchronizing Multiple Windows Forms
Thread Synchronization
Updating the UI from a Secondary Thread
Using Inheritance in the .NET World
Using the ReaderWriterLock Class
Visual Basic: Simplify Common Tasks by Customizing the My Namespace
What's My IP Address?
Windows Forms Controls: Z-order and Copying Collections
Expand Minimize

Property Bag Changes in Visual Basic .NET

Visual Studio .NET 2003
 

Steve Hoag
Visual Studio Team
Microsoft Corporation

February 2002

Summary: In Visual Basic® 6.0, the PropertyBag object was used to persist an object's data between instances. This paper demonstrates how to duplicate the functionality of a Visual Basic 6.0 property bag in Visual Basic .NET using serialization. (6 printed pages)

Contents

Introduction
Creating the Loan Object
Using Serialization to Persist the Object
Persisting the Object Using SOAP Format
Limitations of Serialization
Conclusion

Introduction

In Visual Basic 6.0, the PropertyBag object was used to persist an object's data between instances, allowing you to store values and retrieve them the next time the object was instantiated. Although you could set an object's properties to a default value at design time, any values entered at run time were lost when the object was destroyed. The PropertyBag object allowed a copy of the object to be persisted in a binary format and retrieved for later reuse. For example, a class used to calculate loans might use a PropertyBag to persist an interest rate between instances rather than entering it each time the class is used.

In Visual Basic .NET, the PropertyBag object no longer exists, but you can still persist an object's data using the System.Runtime.Serialization and System.IO namespaces. In addition to persisting an object in binary format, you can also persist an object in SOAP format.

To persist an object in Visual Basic .NET, you first mark the class as Serializable. When instantiating the object, you use a Stream class and a BinaryFormatter or SoapFormatter class to retrieve the object's data from a file. Before destroying the object, you again use the Stream and formatter classes to write the object's values to the file.

In this article, you will create a simple Loan object and persist its data to a file, then retrieve the data from the file when you recreate the object. You will then modify the code to persist the object in SOAP format.

Creating the Loan Object

The first step is to create a Loan class and a test application that uses the class.

To create the Loan class

  1. In Visual Basic .NET, open a new Class Library project and name it LoanClass.
  2. In the Code Editor, change the name of the class from Class1 to Loan.
  3. Add the following public members to the class:
    Public LoanAmount As Double = 10000.0
    Public InterestRate As Double = 7.5
    Public Term As Integer = 36
    Public Customer As String
    
  4. On the Build menu, choose Build LoanClass.

    The LoanClass project must be built in order to make the class available for use.

You will also need to create a simple application that uses the Loan class.

To create a test application

  1. Add a Windows Application project to your solution and name it LoanApp.
  2. In Solution Explorer, select the LoanApp project.
  3. On the Project menu, choose Set as StartUp Project.
  4. On the Project menu, choose Add Reference.
  5. In the Add Reference dialog box, select the Projects tab and select the LoanClass project.
  6. Click Select, then click OK to close the dialog box.
  7. In the designer, add four TextBox controls to the form.
  8. In the Code Editor, add the following code:
    Private myLoan As New LoanClass.Loan
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
    System.EventArgs) Handles MyBase.Load
        TextBox1.Text = myLoan.LoanAmount.ToString
        TextBox2.Text = myLoan.InterestRate.ToString
        TextBox3.Text = myLoan.Term.ToString
        TextBox4.Text = myLoan.Customer
    End Sub
    

To test the application

  1. Build the application.
  2. Press F5 to run the application.

    Note that the default values from the Loan class appear in the text boxes.

  3. Try changing the interest rate value from 7.5 to 7.1.
  4. Close the application and run it again.

    The value reverts to the default of 7.5.

In the real world, interest rates change periodically, but not necessarily every time the application is run. Rather than making the user update the interest rate each time the application is run, it would be good to preserve the most recent interest rate between instances of the application. In the next step, you will do that by adding serialization to the Loan class.

Using Serialization to Persist the Object

In order to persist the values for the Loan class, you must first mark the class with the Serializable attribute.

To mark a class as serializable

  • Change the class declaration for the Loan class to the following:
    <Serializable()> Public Class Loan
    

The Serializable attribute tells the compiler that everything within the class can be persisted to a file. In this case, you want to persist the InterestRate, LoanAmount, and Period members, but you probably do not want to persist the Customer member. The NonSerialized attribute can be used to mark class members that should not be persisted.

To prevent a member from being serialized

  • Change the declaration for the Customer member to the following:
    <NonSerialized()> Public Customer As String
    

The next step is to add the serialization code to the LoanApp application. In order to serialize the class and write it to a file, you will use the System.IO and System.Runtime.Serialization namespaces. To avoid typing the fully qualified names, you can use the Imports statement.

To add references to namespaces

  • Add the following Imports statements to the top of the Form1 module:
    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary
    

    In this case, you are using a binary formatter to save the object in a binary format. Later in this article you will demonstrate how to modify the code to save the object in SOAP format.

The next step is to add code to deserialize the object from the file when the object is created.

To deserialize an object

  • Modify the code in the Form1_Load event procedure as follows:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
    System.EventArgs) Handles MyBase.Load
        If File.Exists("SavedLoan.bin") Then
            Dim myFileStream As Stream = File.OpenRead("SavedLoan.bin")
            Dim deserializer As New BinaryFormatter()
            myLoan = CType(deserializer.Deserialize(myFileStream), _
    LoanClass.Loan)
            myFileStream.Close
        End If
        TextBox1.Text = myLoan.LoanAmount.ToString
        TextBox2.Text = myLoan.InterestRate.ToString
        TextBox3.Text = myLoan.Term.ToString
        TextBox4.Text = myLoan.Customer
    End Sub
    

    Note that you first need to check for the existence of the file: Because the file does not yet exist the first time you create the object. You then create a Stream class to read the binary file and a BinaryFormatter class to translate the file. The CType method is used to convert from the stream to the Loan object type.

Next you need to add code to save the data entered in the text boxes to the Loan class, and to serialize the class to a file.

To save the data and serialize the class

  • Add the following code to the Form1_Closing event procedure:
    Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As _
    System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        myLoan.LoanAmount = CType(TextBox1.Text, Double)
        myLoan.InterestRate = CType(TextBox2.Text, Double)
        myLoan.Term = CType(TextBox3.Text, Integer)
        myLoan.Customer = TextBox4.Text
    
        Dim myFileStream As Stream = File.Create("SavedLoan.bin")
        Dim serializer As New BinaryFormatter()
        serializer.Serialize(MyFileStream, myLoan)
        myFileStream.Close
    End Sub
    

At this point, you can once again build and run the application. Initially the default values appear in the text boxes. Try changing the values and entering a name in the fourth text box. Close the application and then run it again; note that the new values now appear in the text boxes, except for the customer name which was marked as Nonserialized.

Persisting the Object Using SOAP Format

The example thus far has demonstrated how to persist an object to a text file using a binary format. Although a binary format is fine for most Windows® applications, for Web applications or XML Web services you may want to persist the object to an XML file using SOAP format in order to easily share the object.

In order to persist the object to SOAP format, you must first reference the SoapFormatter class. The SoapFormatter class resides in its own namespace: System.Runtime.Serialization.Formatters.Soap.

To persist the object using SOAP format

  1. In the Solution Explorer, select the LoanApp project.
  2. On the Project menu, choose Add Reference.
  3. In the Add Reference dialog box, select the .NET tab and select the System.Runtime.Serialization.Formatters.Soap component.
  4. Click Select, then click OK to close the dialog box.
  5. In the Code Editor, add an Imports statement to the top of the Form1 module:
    Imports System.Runtime.Serialization.Formatters.Soap
    
  6. In the Form1_Load event procedure, change the Dim statement from Dim deserializer As New BinaryFormatter to Dim deserializer As New SoapFormatter. Change both references to "SavedLoan.bin" to "SavedLoan.xml".
  7. In the Form1_Closing event procedure, do the following:
    1. Change the Dim statement from Dim deserializer As New BinaryFormatter to Dim deserializer As New SoapFormatter.
    2. Change the reference "SavedLoan.bin" to "SavedLoan.xml".

To test the application

  1. Build the application.
  2. Press F5 to run the application.

    When you first run the application, the SavedLoan.xml file will be created.

    Tip   You can view this file by choosing the Show All Files option in the Solution Explorer; it will be in the Bin node for the Windows Application project.

    Note that the three members of the LoanClass are displayed in XML format.

  3. Change the InterestRate value in the XML file.
  4. Save the file and run the application again.

    The new interest rate will appear in the second text box.

Limitations of Serialization

In general, serialization works well for persisting objects, but there are some limitations. Inherited classes can be serialized only if the base class from which they are inherited is attributed as serializable. For example, if you were to create a new HomeLoan class that inherits from our LoanClass and then remove the Serializable attribute from the LoanClass, you would not be able to serialize the HomeLoan class. A run time error will occur because the base class is not serializable.

Likewise, serialization cannot be used for forms because a form is derived from the System.Windows.Forms.Form class, which is not attributed as Serializable. In order to persist the properties of a form, you must use either Dynamic Properties or registry entries.

Conclusion

Although the PropertyBag object no longer exists, it is easy to persist objects using Visual Basic .NET. In addition, using serialization provides greater flexibility, because you can mark individual members as nonserializable, and you can persist the object to an XML file in order to make it available to other applications.

Show:
© 2015 Microsoft