Serialization of class instance stored in database

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

I'd like to take an instance of a class and store it in a database. I've
marked my class as [Serializable] and am using the binary formatting code
similar to
http://msdn.microsoft.com/library/d...s/cpguide/html/cpconserializationconcepts.asp,
although I'd be happy to use something else. What method should be used to
store this serialized class in a SQL Server database? Likewise, what method
should be used to recreate this instance from the datbase?

Thanks in advance.

mark
 
Just found the email below from the google archives of the C# group... I
believe this answers my question:

**************************************

Here is something I've been playing with. It serializes an object to
a database after first pulling out a byte array from a MemStream. To
pull the object out of the database I extract the byte[] array put in
back in a MemStream and then deserialize.

Hope this helps.


using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Data.SqlClient;
using System.Data;


namespace t


{
namespace r
{
/// <summary>
/// Summary description for Serialize.
/// </summary>
public class CSerialize
{
/// <summary>
/// Returns by ref a byte array containing the
serialized object "obj".
/// </summary>
/// <param name="obj">Object to be serialize (the
object must have the attribute Serializable set).</param>

/// <param name="buffer"></param>
static public void SerializeToArray(object obj, ref
byte[] buffer)
{
MemoryStream ms = null;

try
{
ms = new MemoryStream();
BinaryFormatter f = new
BinaryFormatter();


f.Serialize(ms, obj);


buffer = ms.ToArray();
}
catch(Exception e)
{
TSError.LogError("",
"CSerialize.SerializeToArray", 1, e);
throw e;
}
finally
{
if( ms != null)
ms.Close();
}
}


/// <summary>
/// Deserializes object out of the given byte array.
/// </summary>


/// <param name="oMsg"></param>
/// <param name="buffer"></param>
/// <returns></returns>
static public bool DeserializeObject(ref object
oMsg, byte[] buffer)
{
MemoryStream ms = null;
bool bResult = true; // default

try
{
ms = new MemoryStream(buffer);


BinaryFormatter f = new
BinaryFormatter();


oMsg = f.Deserialize(ms);
}
catch(Exception e)
{
TSError.LogError("",
"CSerialize.SerializeToArray", 1, e);
throw e;
}
finally
{
if( ms != null )
ms.Close();
}


return bResult;
}


static public bool DebugWriteBlobToDatabase(byte[]
buffer)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();


try
{
conn.ConnectionString = "Data
Source=dssql;InitialCatalog=smr;User ID=sa;Password=;";
conn.Open();

cmd.CommandType =
System.Data.CommandType.StoredProcedure;
cmd.CommandText = "zzClarkBlobTest";
cmd.Connection = conn; //
connection is already opened.
SqlParameter parmPKID =
cmd.Parameters.Add("@DataBlob", SqlDbType.Image);


parmPKID.Value = buffer;
if(cmd.ExecuteNonQuery() != 1)
throw new Exception("Failed
to insert blob");


}
catch(Exception e)
{
string s = e.Message;
s = s + "";
}
finally
{


if(conn != null && conn.State !=
System.Data.ConnectionState.Closed )
conn.Close();
}

return true;
}


static public bool DebugReadBlobFromDatabase(ref
byte[] buffer)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataSet ds = null;
string sJunk;


object obj = null;
try
{
conn.ConnectionString = "Data
Source=dssql;InitialCatalog=serviceqmaster;User ID=sa;Password=;";
conn.Open();

SqlDataAdapter adapter = new
SqlDataAdapter();
adapter.SelectCommand = new
SqlCommand("Select * from zzTestTable", conn);


ds = new DataSet();
// Get rows from CS_event table.
adapter.Fill(ds);



//sJunk =
ds.Tables[0].Rows[0][0].GetType().ToString();
//obj =
(byte[])ds.Tables[0].Rows[0][1];
buffer =
(byte[])ds.Tables[0].Rows[0][1];
}
catch(Exception e)
{
string s = e.Message;
s = s + "";
}
finally
{


if(conn != null && conn.State !=
System.Data.ConnectionState.Closed )
conn.Close();
}

return true;
}
}
}



Mark said:
I'd like to take an instance of a class and store it in a database. I've
marked my class as [Serializable] and am using the binary formatting code
similar to
http://msdn.microsoft.com/library/d...s/cpguide/html/cpconserializationconcepts.asp,
although I'd be happy to use something else. What method should be used to
store this serialized class in a SQL Server database? Likewise, what method
should be used to recreate this instance from the datbase?

Thanks in advance.

mark
 
Mark,

This one as once provided by Tom Shelton to this newsgroup is for me the
nicest I have seen.

\\\
Private Function SerializeFontObject(ByVal fnt As Font) As String
Dim bf As New BinaryFormatter
Dim mem As New MemoryStream
Try
bf.Serialize(mem, fnt)
Return Convert.ToBase64String(mem.ToArray())
Catch
Return String.Empty
Finally
mem.Close()
End Try
End Function
////
\\\\
Private Function DeserializeFontObject(ByVal fnt As String) As Font
Dim bf As New BinaryFormatter
Dim mem As New MemoryStream(Convert.FromBase64String(fnt))
Try
Return DirectCast(bf.Deserialize(mem), Font)
Finally
If Not mem Is Nothing Then
mem.Close()
End If
End Try
End Function
////

It is a font however you can use it for every object telling the type.

I hope this helps a little bit?

Cor
 
Back
Top