Click here to Skip to main content
15,892,161 members
Articles / Desktop Programming / Windows Forms

MVP-VM (Model View Presenter - ViewModel) with Data Binding and BackgroundWorker in Windows Forms applications

Rate me:
Please Sign up or sign in to vote.
4.98/5 (29 votes)
17 Jun 2010CPOL19 min read 136.3K   4.9K   99  
This article explains a way to create a Windows Forms app with the thinnest possible Form.cs files.
Imports System.Globalization
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Security
Imports System.Xml

Public Class Persistence(Of T)
    Public Sub New(ByVal fileName As String)
        Me.FileName = fileName
    End Sub

    Public Property FileName As String

    Public Function ReadObject() As T
        Try
            Return DoReadObject()
        Catch ex As ArgumentException
            Dim s = String.Format(
                    CultureInfo.CurrentCulture,
                    "Specified file name is blank, contains only white space, or contains one or more invalid characters - {0}",
                    Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As NotSupportedException
            Dim s = String.Format(
                 CultureInfo.CurrentCulture,
                 "Specified file name refers to a non-file device, such as 'con:', 'com1:', 'lpt1:', etc. in a non-NTFS environment - {0}",
                 Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As SecurityException
            Throw New OperationFailedException("Caller does not have the required permission.", ex)
        Catch ex As DirectoryNotFoundException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "The specified path - {0} is invalid, such as being on an unmapped drive.",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As PathTooLongException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "The specified path - {0}, file name, or both exceed the system-defined maximum length. Paths must be less than 248 characters, and file names must be less than 260 characters.",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As IOException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "IO error occurs when trying to open the specified file - {0}",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As SerializationException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "IO error occurs when trying to read the specified file - {0}",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        End Try
    End Function

    Public Sub WriteObject(ByVal target As T)
        Try
            DoWriteObject(target)
        Catch ex As ArgumentException
            Dim s = String.Format(
                    CultureInfo.CurrentCulture,
                    "Specified file name is blank, contains only white space, or contains one or more invalid characters - {0}",
                    Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As NotSupportedException
            Dim s = String.Format(
                 CultureInfo.CurrentCulture,
                 "Specified file name refers to a non-file device, such as 'con:', 'com1:', 'lpt1:', etc. in a non-NTFS environment - {0}",
                 Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As SecurityException
            Throw New OperationFailedException("Caller does not have the required permission.", ex)
        Catch ex As DirectoryNotFoundException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "The specified path - {0} is invalid, such as being on an unmapped drive.",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As PathTooLongException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "The specified path - {0}, file name, or both exceed the system-defined maximum length. Paths must be less than 248 characters, and file names must be less than 260 characters.",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As IOException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "IO error occurs when trying to open the specified file - {0}",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        Catch ex As SerializationException
            Dim s = String.Format(
                CultureInfo.CurrentCulture,
                "IO error occurs when trying to write the specified file - {0}",
                Me.FileName)
            Throw New OperationFailedException(s, ex)
        End Try
    End Sub

    Private Function DoReadObject() As T
        Using fs As New FileStream(Me.FileName, FileMode.Open)
            Using reader As XmlReader = XmlReader.Create(fs)
                Dim s As New DataContractSerializer(GetType(T))
                Return DirectCast(s.ReadObject(reader), T)
            End Using
        End Using
    End Function

    Private Sub DoWriteObject(ByVal target As T)
        Using fs As New FileStream(Me.FileName, FileMode.Create)
            Using writer As XmlWriter = XmlWriter.Create(fs, New XmlWriterSettings With {.Indent = True})
                Dim s As New DataContractSerializer(GetType(T))
                If writer IsNot Nothing Then
                    s.WriteObject(writer, target)
                End If
            End Using
        End Using
    End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Japan Japan
He started his career as a PDP-11 assembly language programmer in downtown Tokyo, learning what "patience" in real life means by punching a 110 baud ASR-33 Teletype frantically. He used to be able to put in the absolute loader sequence through the switch panel without consulting the DEC programming card.

Since then, his computer language experiences include 8051 assembly, FOCAL, BASIC, FORTRAN-IV, Turbo/MS C, VB. VB.NET, and C#.

Now, he lives with his wife, two grown-up kids (get out of my place!), and two cats in Westerville, Ohio.

Comments and Discussions