Export (0) Print
Expand All
1 out of 2 rated this helpful - Rate this topic

Walkthrough: Persisting an Object in Visual Basic .NET

Visual Studio .NET 2003

Although you can set an object's properties to default values at design time, any values entered at run time are lost when the object is destroyed. In Visual Basic .NET, serialization can be used to persist an object's data between instances, allowing you to store values and retrieve them the next time the object is instantiated.

In this walkthrough, 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 a SOAP format.

Security Note   This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create permission for the folder. Permissions are set using access control lists. If the file already exists, the application needs only Write permission, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read privileges to a single file (rather than Create privileges for a folder). Also, it is more secure to write data to user folders than to the root folder or the Program Files folder.
Security Note   This example stores data in a binary or SOAP format file. Sensitive data (such as passwords or credit card information) should not be stored in a file.
Note   The Class Library template is not available in the Standard Edition of Visual Basic .NET. For more information, see Visual Basic Standard Edition Features.

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. Create 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, click Set as StartUp Project.
  4. On the Project menu, click 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
    

At this point, you can build and run the application. Note that the default values from the Loan class appear in the text boxes. Try changing the interest rate value from 7.5 to 7.1, then 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 nice to preserve the most recent interest rate between instances of the application. In the next step, you will do just 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 as follows:
    <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 as follows:
    <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 walkthrough you will modify the code to save the object in a 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 that the file exists. If it exists, 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 that was marked as Nonserialized.

Persisting the Object Using a SOAP Format

The example so far has demonstrated how to persist an object to a text file using a binary format. 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 a SOAP format, which makes the object easy to share.

In order to persist the object to a 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 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
    
  7. Change both references from "SavedLoan.bin" to "SavedLoan.xml".
  8. In the Form1_Closing event procedure, do the following:
    1. Change the Dim statement from

      Dim serializer As New BinaryFormatter

      to

      Dim serializer As New SoapFormatter. 
      
    2. Change the reference from "SavedLoan.bin" to "SavedLoan.xml".

At this point, you can build and test the application. When you first run the application, the SavedLoan.xml file will be created. You can view this file by choosing the Show All Files option in Solution Explorer; it will be in the Bin node for the Windows Application project.

Note   If you are already in Show All Files mode, you will need to refresh the view by choosing Refresh from the View menu in order to see the file.

Note that the three members of the LoanClass are displayed in XML format. Try changing the InterestRate value in the XML file, then save it and run the application again. The new interest rate will appear in the second text box.

See Also

PropertyBag Changes in Visual Basic .NET | Saving the Properties of Components

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.