Friday, September 02, 2011

That's Generic!

So you are creating a small config file and think "Gee, it would be nice to use the auto-serialization feature of  dot net"

So you wrap the serialization and deserialization routines as shared (static for you c# guys) functions, and throw a  _ in front of your class, and viola!

But, what if you are doing two, three, 48, 72 small serializable objects?  Ah, the power of object orientation!  Yes folks, object orientation makes this cake.  I created an abstract base class which contains the code I need to repeat for each small class.


Imports System.IO
Imports System.Xml.Serialization

Public Class AbstractSerialzationClass(Of t)
    Private Shared _ErrorOccured As Boolean = False
    Private Shared _ErrorText As String = ""
    Shared Function Deserialize(ByRef anObject As t, _
ByVal FileNameString As String) As Boolean

        _ErrorOccured = False
        If File.Exists(FileNameString) Then
            Try
                Dim aStreamReader As New StreamReader(FileNameString)
                Dim x As New XmlSerializer(anObject.GetType)
                anObject = CType(x.Deserialize(aStreamReader), t)
                aStreamReader.Close()
            Catch ex As Exception
                _ErrorOccured = True
                _ErrorText = "Unable to deserialze '" & FileNameString & "'." & ex.Message
            End Try
        Else
            _ErrorOccured = True
            _ErrorText = "XML File -'" & FileNameString & "' was not found"
        End If
        Return _ErrorOccured
    End Function
    Shared Sub Serialize(ByVal FileNameString As String, ByVal InObject As t)
        _ErrorOccured = False
        If File.Exists(FileNameString) Then
            If File.Exists(FileNameString & ".old") Then
                File.Delete(FileNameString & ".old")
            End If
            File.Copy(FileNameString, FileNameString & ".old")
            File.Delete(FileNameString)
        End If
        Try
            Dim aStreamWriter As New StreamWriter(FileNameString)
            Dim x As New XmlSerializer(InObject.GetType)
            x.Serialize(aStreamWriter, InObject)
            aStreamWriter.Close()
        Catch ex As Exception
            _ErrorText = "Unable to Serialze Annotation object to file named '" & FileNameString & "'.  " & ex.ToString
            _ErrorOccured = True
        End Try
    End Sub
    Public ReadOnly Property ErrorOccured() As Boolean
        Get
            Return _ErrorOccured
        End Get
    End Property
    Public ReadOnly Property ErrorText() As String
        Get
            Return _ErrorText
        End Get
    End Property
End Class


Now to use this in a class, all I've got to do is this

 Public Class foo
    Inherits AbstractSerialzationClass(Of foo)
end Class


Much neater!

No comments: