Storing objects in a flat file using VB.NET
Serialization/ Retrieving object data from file using Vb.NET Deserialization
In the following example, let us look at a way by which we can make user-defined classes Serializable. The first step is to have
Now the objects that are derived from the classes can be serialized
Imports System
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Implements IDeserializationCallback
Public VID As Integer
Public VName As String
Public VQty As Integer
Public VPrice As Decimal
Public Sub New(ByVal _VID As Integer, ByVal _VName As String, ByVal _Vqty As Integer, ByVal _vPrice As Decimal)
MyBase.New()
VID = _VID
VName = _VName
VQty = _Vqty
VPrice = _vPrice
VTotal = VPrice * VQty
End Sub
Sub IDeserializationCallback_Deserialize(ByVal sender As Object) Implements IDeserializationCallback.OnDeserialization
' Calculate the total after Deserialization
VTotal = VPrice * VQty
End Sub
End Class
makes the objects of the class serializable. The above example has an Variable ‘VTotal’ which can be generated dynamically. Hence we need not serialize this object; can be calculated during deserialization (Disable Serialization of Class Members - VTotal). This can be done by using IDeserializationCallback interface
Implements IDeserializationCallback
And implement IDeserializationCallback.OnDeserialization
Sub IDeserializationCallback_Deserialize(ByVal sender As Object) Implements IDeserializationCallback.OnDeserialization
' Calculate the total after Deserialization
VTotal = VPrice * VQty
End Sub
This will calculate VTotal when deserialized as shown in the following example:
Sub Rent_A_DVD()
' Example of using a custom class which is serializable
' --------------------------------------------
' Hold Operation
' Store the data Temporarily in Text File
' --------------------------------------------
Dim FS As FileStream = New FileStream("c:\VBADUD\VCDExmpleSerialized.txt", FileMode.Create)
Dim oItem As CVideoLibraryOrder
Dim BFmt As New BinaryFormatter
oItem = New CVideoLibraryOrder(132, "Day of Jackal", 2, 4.5)
BFmt.Serialize(FS, oItem)
FS.Flush()
FS.Close()
' Some Other Operations - Different Bill etc
Dim oRestoredItem As CVideoLibraryOrder
FS = New FileStream("c:\VBADUD\VCDExmpleSerialized.txt", FileMode.Open)
oRestoredItem = CType(BFmt.Deserialize(FS), CVideoLibraryOrder)
FS = Nothing
oRestoredItem = Nothing
BFmt = Nothing
End Sub
End Class
No comments:
Post a Comment