-
Dec 6th, 2009, 10:57 PM
#1
Thread Starter
Frenzied Member
Lazy Save
Thought I'd throw this out for further development. This is certainly simple...maybe too simple. If you feel like it make improvements.
The purpose of this code is to allow to save an object, via serialization, with a minimal amount of coding. It's usefulness is to be determined.
Usually, we serialize an object (or object graph) by choosing to save a specific type to a specific file name. However, as the title of the post implies (well maybe not)
this code allows any serializable object to be saved without knowing the object type or the name of the file. So it's both a code saver and "lazy" code
at the same time. The code was inspired because I had a project that saves to 12 or so files. Each save required specific serialization/deserialization code.
I must state that currently, in actual use, the file name is passed in to the generic serialize and deserialize sub/function. Then...I got even more "lazy"...I decided as an experiment to not even name the file that must be saved to. I thought it worthy to throw this out for possible improvement.
This will take any serializable object of any type.
Lists, or complete object graphs, can best be handled by composition internally.
Seems to hold some promise of actual use.
Code:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Public Class Form1
#Region "Lazy Save"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The following three lines are all that is required
'to serialize and deserialize an object or object graph.
Dim p As New Person
SerializeToFile(Of Person)(p)
Dim p2 As Person = DeserializeFromFile(Of Person)()
End Sub
#End Region
#Region "Serialize To File"
Friend Shared Sub SerializeToFile(Of T)(ByVal obj As T)
Dim path As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData, obj.GetType.Name)
Dim fs As FileStream = Nothing
Dim bf As BinaryFormatter = Nothing
Try
fs = New FileStream(path, FileMode.Create)
bf = New BinaryFormatter
bf.Serialize(fs, obj)
Catch ex As Runtime.Serialization.SerializationException
MessageBox.Show("Reason: " & ex.Message, "Failed To Save")
Finally
If Not fs Is Nothing Then
fs.Close()
End If
End Try
End Sub
#End Region
#Region "Deserialize From File"
Friend Shared Function DeserializeFromFile(Of T)() As T
Dim fs As FileStream = Nothing
Try
fs = New FileStream(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData, GetType(T).Name), FileMode.Open)
Dim formatter As New BinaryFormatter
formatter.Binder = New PreviousVersionDeserializeBinder
Return DirectCast(formatter.Deserialize(fs), T)
Catch ex As Runtime.Serialization.SerializationException
MessageBox.Show("Failed To Open File. The file is not of the correct file type.", "File Contents", MessageBoxButtons.OK)
Catch ex As System.Reflection.TargetException
MessageBox.Show("Target Exception")
Catch ex As System.Reflection.AmbiguousMatchException
MessageBox.Show("Ambiguous Match Error")
Catch ex As System.Reflection.CustomAttributeFormatException
MessageBox.Show("Custom Attribute Format Error")
Catch ex As System.Reflection.InvalidFilterCriteriaException
MessageBox.Show("Invalid Filter Criteria Exception")
Catch ex As System.Reflection.ReflectionTypeLoadException
MessageBox.Show("Reflection Type Load Exception")
Catch ex As System.Reflection.TargetInvocationException
MessageBox.Show("Target Parameter Count Exception.", "Type Definition Error:", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As System.Reflection.TargetParameterCountException
Catch ex As FileNotFoundException
MessageBox.Show(ex.Message, "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As IO.DirectoryNotFoundException
MessageBox.Show(ex.Message, "Folder Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As IO.DriveNotFoundException
MessageBox.Show(ex.Message, "Drive Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As IO.IOException
MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If Not fs Is Nothing Then
fs.Close()
End If
End Try
End Function
#End Region
End Class
<Serializable()> _
Public Class Person
Public Sub New()
mAge = 20
End Sub
Private mAge As Short
Public Property Age() As Short
Get
Return mAge
End Get
Set(ByVal value As Short)
mAge = value
End Set
End Property
End Class
Last edited by FourBlades; Dec 9th, 2009 at 06:32 PM.
Reason: Added Explanation
-
Dec 7th, 2009, 04:56 AM
#2
Re: Lazy Save
Think this should be in the CodeBank rather than here
-
Dec 7th, 2009, 06:45 AM
#3
Re: Lazy Save
Originally Posted by chris128
Think this should be in the CodeBank rather than here
Agree...Moved To The CodeBank
What does this code do?
-
Dec 7th, 2009, 11:43 AM
#4
Thread Starter
Frenzied Member
Re: Lazy Save
Explanation of code is now found, as an update, in the original post.
-
Jan 9th, 2010, 03:06 PM
#5
Registered User
Re: Lazy Save
I love this piece of code. I'm making a general DLL for my projects that contain all kinds of functions to make programming easier for me, and I'll certainly add your code to the library! Thanks!
(yes I am lazy )
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|