Sunday, March 25, 2012

Binary Serialization

Hello,

I am trying to serialize (binary) a class and save it in a database. I followed a few examples I found in internet and this is what I came up with:

1' Rows2<Serializable()> _3Public Class Rows4Implements ISerializable56Private _RowsAs New Generic.List(Of Row)7Public Property Rows()As Generic.List(Of Row)8Get9 Return _Rows10End Get11 Set(ByVal valueAs Generic.List(Of Row))12 _Rows = value13End Set14 End Property' Rows1516 ' New17Public Sub New()18End Sub' New1920 ' New21Public Sub New(ByVal siRowsAs SerializationInfo,ByVal scRowsAs StreamingContext)22End Sub' New2324 ' GetObjectData25Public Sub GetObjectData(ByVal siRowsAs SerializationInfo,ByVal scRowsAs StreamingContext)Implements ISerializable.GetObjectData2627 siRows.AddValue("Rows",Me.Rows)2829End Sub' GetObjectData3031Public Sub Serialize(ByVal filenameAs String)3233Dim sRowsAs Stream = Stream.Null34Try35 sRows = File.Open(filename, FileMode.Create, FileAccess.ReadWrite)36Dim bfRowsAs New BinaryFormatter37 bfRows.Serialize(sRows,Me)38Finally39 sRows.Close()40End Try4142 End Sub' Serialize4344Public Shared Function Deserialize(ByVal filenameAs String)As Rows4546Dim sRowsAs Stream = Stream.Null47Try48 sRows = File.Open(filename, FileMode.Open, FileAccess.Read)49Dim bfRowsAs New BinaryFormatter50Return CType(bfRows.Deserialize(sRows), Rows)51Finally52 sRows.Close()53End Try5455 End Function' Deserialize5657End Class' Rows

After serializing the class I need to save it in an a SQL 2005 database.
But all the examples I followed use the filename ...
Anyway, do I need to do something to save this into an SQL 2005 database or can I use it as follows? And how can I use this?
This is the first time I do something like this so I am a little bit confused.
Thanks,
Miguel 


well all u have to do is add "srows" which is the binary serialize stream to ur table, of course u must have a field in atable that is of type image.

Just include a simple insert as ur inserting regular Data to ur table, and here's the code to get the byte array to insert into the image field

byte

[] data;

srows.Read(data,0,

int.MaxValue);

like this just add data to ur image field in ur tabel.

and to read it back again, do the opposite

srows.Write(data, 0, data.Length); //ull have ur binary wrote back to the stream which is SRows

Hope this helps

No comments:

Post a Comment