Binary De/Serialization of object(s)

kwiksand

New member
Joined
Jun 26, 2006
Messages
3
Programming Experience
5-10
Hi Guys,

I'm writing a web application (ASP.NET) in VB.NET, and as part of the wizard process the client wants to be able to Save the progress of the current quote so it can be resumed later on. I'd rather not have incomplete quote data in my tables, and thought that serializing the object and storing it in a separate table with a date, ID and the UserID of the person who was creating the quote at the time.

I've got this working when simply serializing the objects to a text file, but when I try to write to a memory stream, then to the database, then read it back again, I'm not getting any (or at least, not correct) data.

I've used:

VB.NET:
Dim objStream As New MemoryStream
Dim objFormatter As New Formatters.Binary.BinaryFormatter
 
objFormatter.Serialize(objStream, Me)
Dim BArray() As Byte
BArray = objStream.ToArray()
Dim SqlString As String
Dim SqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("TESTDB_CF").ConnectionString)
SqlConn.Open()
 
SqlString = "INSERT INTO SavedQuotes (quote_date, user_id, quote_hash) VALUES (@date, @user_id, @quote_hash)"
 
Dim SqlComm As New SqlCommand(SqlString, SqlConn)
With SqlComm.Parameters
.Add(New SqlParameter("@quote_hash", BArray))
.Add(New SqlParameter("@date", Date.Now()))
.Add(New SqlParameter("@user_id", UserID))
End With
 
SqlComm.ExecuteNonQuery()
 
SqlConn.Close()

I've definately got binary data in my database table at this point, but I have no way of knowing wether or not its correct :p

Then I'm using, to deserialize back to an object:

VB.NET:
 Dim objFormatter As New Formatters.Binary.BinaryFormatter
 
Dim DR As SqlDataReader
Dim SqlString As String
Dim SqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("TESTDB_CF").ConnectionString)
SqlConn.Open()
 
SqlString = "SELECT * FROM SavedQuotes Where quote_id = @quote_ID"
 
Dim SqlComm As New SqlCommand(SqlString, SqlConn)
SqlComm.Parameters.Add(New SqlParameter("@quote_id", QuoteID))
DR = SqlComm.ExecuteReader()
 
Dim BArray(CInt(DR("quote_hash"))) As Byte
BArray = DR("quote_hash")
DR.GetBytes(1, 0, BArray, 0, CInt(DR("quote_hash")))
Dim objStream As New MemoryStream(BArray)
Dim tempQuote As Quote = CType(objFormatter.Deserialize(objStream), Quote)
Return tempQuote
SqlConn.Close()

Excuse the bad code, this is purely an attempt to get it working at the moment.

Can anyone give any pointers on where I might be going wrong (I believe its in the deserialization stage), or a better way to do it. I think I might be getting the wrong idea with the use of the Byte Array for extraction.

Thanks

kwik
 
Back
Top