473,396 Members | 1,666 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Serialization of class instance stored in database

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/de...onconcepts.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
Nov 21 '05 #1
4 1433
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" <Ma**@nowhere.com> wrote in message
news:Ob**************@TK2MSFTNGP11.phx.gbl...
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/de...onconcepts.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

Nov 21 '05 #2
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" <Ma**@nowhere.com> wrote in message
news:Ob**************@TK2MSFTNGP11.phx.gbl...
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/de...onconcepts.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

Nov 21 '05 #3
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
Nov 21 '05 #4
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
Nov 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: jamie_m_ | last post by:
I have a custom collection ... clFile that INHERITS from NameObjectCollectionBase the problem is, when I try to create an xmlserializer instance i get an error You must implement a default...
2
by: Wayne Wengert | last post by:
This is my first attempt to re-write an old VB6 application that exported a CSV file to a .NET application that exports an XML file with the equivelent data. I have limited understanding of OO...
2
by: John Wood | last post by:
I'm just considering embarking on writing a class that does a better job than the Serialize attribute. The serialize attribute is no good because it sucks at even the most basic of versioning. So...
3
by: AVL | last post by:
Hi, I'm new to .net. I need some info on serialization. What is serialization? Why do we need it? Why objects need to be serialized if they need to be stored in session or viewstate?
0
by: Mark | last post by:
I'd like to take an instance of a class and store it in a database. I've marked my class as and am using the binary formatting code similar to...
5
by: ns21 | last post by:
Our application is windows desktop application. We are using VS.Net 2003, C#, Framework 1.1, SQL 2000. We use webservices to add/update/select objects. We are using XML Serialization. Following is...
5
by: Henry Jones | last post by:
I read a bit on Serialization and came up with the following definition: The System.Runtime.Serialization namespace contains classes that can be used for serializing and deserializing objects....
0
by: JosAH | last post by:
Introduction Upon hearing the word, "Serialization", the first question which comes to mind is ... "What is Serialization?" We know that we can create resusable objects in Java. But the...
2
by: Nishant Mehta | last post by:
Hi all, I am serialiizing a c# object to an XML file to save some application settings. The idea is to ship this xml file along with the application and deserialize after the application is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.