Forum Moderators: open

Message Too Old, No Replies

Store and retrieve session var from database

need help with datatable object .Net

         

tomasz

1:50 pm on Aug 29, 2005 (gmt 0)

10+ Year Member



Hello All,

I need to create a function in .Net to store and retrieve session variable from SQL server. I have datatable I put in session variable and I would like to save it to the database. I know how to do with strings but do not know how to do it with datatable object.
I do not want to create separate sql table it has to be stored in one field.

Can I do it with out using serialization?

thanks for help.

tomasz

1:34 pm on Sep 8, 2005 (gmt 0)

10+ Year Member



I found a solution to my own question and will share with you.
Serialized data can be saved in database and it is perfect for shopping carts or reletional datasets used on your site etc. Trick is to serialiaze it as array byte and you can save it to database using binary field like image, etc

'''''
Imports System.Runtime.Serialization.Formatters.Binary

'''''

Public Function serializeDatatable(ByVal dt As DataTable) As Byte()
Dim objMemoryStream As MemoryStream
Dim objBinaryFormatter As BinaryFormatter

objMemoryStream = New MemoryStream
objBinaryFormatter = New BinaryFormatter

objBinaryFormatter.Serialize(objMemoryStream, dt)
objMemoryStream.Close()
Return objMemoryStream.ToArray
End Function

Public Function deserializeDatatable(ByVal arrByte As Byte()) As DataTable
Dim objMemoryStream As MemoryStream
Dim objBinaryFormatter As BinaryFormatter

objMemoryStream = New MemoryStream(arrByte)
objBinaryFormatter = New BinaryFormatter

Dim dt As DataTable = CType(objBinaryFormatter.Deserialize(objMemoryStream), DataTable)
objMemoryStream.Close()
Return dt
End Function

TheNige

8:24 pm on Sep 8, 2005 (gmt 0)

10+ Year Member



That's one way to do it. You can also just get the string version of the xml and store it also.

Dim data as new datatable
Dim xmlString as string
Dim stream As MemoryStream = New MemoryStream
data.WriteXml(stream)
xmlString = Text.UTF8Encoding.UTF8.GetString(stream.ToArray())