Persisten Objects

  • Thread starter Thread starter Ale K.
  • Start date Start date
A

Ale K.

Hi, i'm designing an 3 tier application, and i got the following question,
let's say that on my bussines layer i have an object Box that has inside an
object ItemCollection , that can store many Item objects, now let's say i'm
adding items to my box and suddenly my machine hangs up, making me lose my
box and all the items inside of it, there is any way that i can make my
objects to be persistent so if my system goes down i can reload that data??,
i was using a Dataset that i gave the same shape that my object logic, and
saving it to XML every time that an item was added, that make the trick, but
every time a added a property i had to add a lot of code, what can i do??

Thanks.
Alex.
 
Hi Ale,

Here's a simple example that uses serialization. For this to work the class
must be serializable. The class I save in this example is at the end. I
hope this helps.

Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary


Public Class Form1
Inherits System.Windows.Forms.Form

Private Sub ButtonSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ButtonSave.Click
Dim Test As New Sample("Craig", 33, 27.99D)
MsgBox(Test.Tax.ToString())

' Opens a file and serializes the object into it in binary format.
Dim ObjectWriter As Stream = File.Open(Me.Filename, FileMode.Create)
Dim Formatter As New BinaryFormatter()

Formatter.Serialize(ObjectWriter, Test)
ObjectWriter.Close()

End Sub

Private Sub ButtonRead_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ButtonRead.Click

' Opens file "data.xml" and deserializes the object from it.
Dim ObjectWriter As Stream = File.Open(Me.Filename, FileMode.Open)
Dim Formatter As New BinaryFormatter()

formatter = New BinaryFormatter()

Dim Test As Sample = CType(Formatter.Deserialize(ObjectWriter),
Sample)
ObjectWriter.Close()

MsgBox(test.Tax.ToString())
End Sub

Option Strict On
Option Explicit On

<Serializable()> _
Public Class Sample

Public Sub New(ByVal Name As String, ByVal ID As Integer, ByVal Value
As Decimal)
m_Name = Name
m_ID = ID
m_Value = Value
End Sub

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Public Property ID() As Integer
Get
Return m_ID
End Get
Set(ByVal Value As Integer)
m_ID = Value
End Set
End Property

Public Property Value() As Decimal
Get
Return m_Value
End Get
Set(ByVal Value As Decimal)
m_Value = Value
End Set
End Property

Public ReadOnly Property Tax() As Decimal
Get
Return 0.085D * Value
End Get
End Property

Private m_Name As String
Private m_ID As Integer
Private m_Value As Decimal

End Class

Craig, VB.Net Team
This posting is provided "AS IS" with no warranties, and confers no rights.
--------------------
 
Back
Top