Serializing/Deserializing to Database

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a class, "MySavableClass." The class has one string property named
"MyID" and then a bunch of other properties.

Ideally, what I'd like to do is write a "Save()" and a "Restore()" method -
or probably static methods for this object that would work as follows:

private MySavableClass MyC = new MySavableClass();
MyC.MyID = "Class1";
MyC.SomeOtherProperty = 1234;

//The next line will cause the class "MyC" to be serialized and then written
//to a two column database tabe. Column 1 will be the ID column which,
//in this case, will be "Class1", and column 2 will be a Text/Memo column
//which will take the entire serialized object.
Success = MySavableClass.Save(MyC);

//Later, I should be able to do this...

private MySavableClass MyCRestored;
MyCRestored = MySavableClass.Restore("Class1");
if(MyCRestored == null)
//Restoration failed!
else
Writeln("MyCRestored.SomeOtherProperty = " +
MyCRestored.SomeOtherProperty.ToString());

etc., etc.

All of this doesn't seem that hard but I have a few questions:

1. Do I have to set up any meta-tagging on my calss to make it serializable
(it's a pretty simple class.

2. Which serialization method should I use if I want to save the data as
text to a database column?

Any other guidance you can provide will be much appreciated.

Alex
 
1) It should be tagged as Serializable
2) You could either use binary or XML serialization.

If you use binary use Convert.ToBase64 before inserting it to your database
and COnvert.FromBase64 when you have read the object. This step is not
required with XML

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung
 
Thanks for this. Can youhelp me with the specific syntax for marking the
class "Serializable"?

Alex
 
One more little thing: I'm a little confused about how I get my hands on the
string that represents that serialized class so that I can pass it along to
write to the database.

If I do...
Stream stream = File.Open("data.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();

formatter.Serialize(stream, obj);

I can wite it to a file. But how do I just get it into a string instead?

Alex
 
Greg -

Forgive me for asking you to spoon-feed me this way but this thing is really
breaking my head---

So far, to serialize my object, I'm doing the following...

BinaryFormatter formatter = new BinaryFormatter();
MemoryStream MemStream = new MemoryStream();
formatter.Serialize(MemStream, MyObj);

.... but here's where I get stuck because

1. I don't know how to do the Convert.ToBase64() on this MemoryStream and
2. Don't I have to turn this MemoryStream object into a String before I can
use it to fill the parameter of a SQL query (OleDbParam)? If so, how?

Thanks so much for your help!

Alex




Greg Young said:
Use a MemoryStream
http://www.dotgnu.org/pnetlib-doc/System/IO/MemoryStream.html instead of a
FileStream it has a getbytes() method that will give you the relevant bytes.

For the serializable attribute .. it is just [Serializable]

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung


Alex Maghen said:
One more little thing: I'm a little confused about how I get my hands on
the
string that represents that serialized class so that I can pass it along
to
write to the database.

If I do...
Stream stream = File.Open("data.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();

formatter.Serialize(stream, obj);

I can wite it to a file. But how do I just get it into a string instead?

Alex
 
MemStream.ToArray will create you a byte array that you can pass to the
COnvert.TOBase64 method
http://msdn.microsoft.com/library/d...rlrfSystemIOMemoryStreamClassToArrayTopic.asp

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung
Alex Maghen said:
Greg -

Forgive me for asking you to spoon-feed me this way but this thing is
really
breaking my head---

So far, to serialize my object, I'm doing the following...

BinaryFormatter formatter = new BinaryFormatter();
MemoryStream MemStream = new MemoryStream();
formatter.Serialize(MemStream, MyObj);

... but here's where I get stuck because

1. I don't know how to do the Convert.ToBase64() on this MemoryStream and
2. Don't I have to turn this MemoryStream object into a String before I
can
use it to fill the parameter of a SQL query (OleDbParam)? If so, how?

Thanks so much for your help!

Alex




Greg Young said:
Use a MemoryStream
http://www.dotgnu.org/pnetlib-doc/System/IO/MemoryStream.html instead of
a
FileStream it has a getbytes() method that will give you the relevant
bytes.

For the serializable attribute .. it is just [Serializable]

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung


Alex Maghen said:
One more little thing: I'm a little confused about how I get my hands
on
the
string that represents that serialized class so that I can pass it
along
to
write to the database.

If I do...
Stream stream = File.Open("data.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();

formatter.Serialize(stream, obj);

I can wite it to a file. But how do I just get it into a string
instead?

Alex



:

Thanks for this. Can youhelp me with the specific syntax for marking
the
class "Serializable"?

Alex

:

1) It should be tagged as Serializable
2) You could either use binary or XML serialization.

If you use binary use Convert.ToBase64 before inserting it to your
database
and COnvert.FromBase64 when you have read the object. This step is
not
required with XML

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung
I have a class, "MySavableClass." The class has one string property
named
"MyID" and then a bunch of other properties.

Ideally, what I'd like to do is write a "Save()" and a "Restore()"
method -
or probably static methods for this object that would work as
follows:

private MySavableClass MyC = new MySavableClass();
MyC.MyID = "Class1";
MyC.SomeOtherProperty = 1234;

//The next line will cause the class "MyC" to be serialized and
then
written
//to a two column database tabe. Column 1 will be the ID column
which,
//in this case, will be "Class1", and column 2 will be a Text/Memo
column
//which will take the entire serialized object.
Success = MySavableClass.Save(MyC);

//Later, I should be able to do this...

private MySavableClass MyCRestored;
MyCRestored = MySavableClass.Restore("Class1");
if(MyCRestored == null)
//Restoration failed!
else
Writeln("MyCRestored.SomeOtherProperty = " +
MyCRestored.SomeOtherProperty.ToString());

etc., etc.

All of this doesn't seem that hard but I have a few questions:

1. Do I have to set up any meta-tagging on my calss to make it
serializable
(it's a pretty simple class.

2. Which serialization method should I use if I want to save the
data
as
text to a database column?

Any other guidance you can provide will be much appreciated.

Alex
 
Hi Alex,

For serializing and derializing .net class object so as to persist them as
text in database, you can consider both XmlSerialization(pure xml string
based) or BinarySerialization(need to convert the serialized binary data
into string, such as base64 convertion). Here are some simple code snippet
demostrating on using both binary and XML serialization to persist and
restore the class instance:


=========binary serialize============

//serialize the class instance and store the result into a TextBox
private void btnSerialize_Click(object sender, EventArgs e)
{
MySavableClass msc = new MySavableClass();

msc.MyID = "id1";
msc.Title = "default title";
msc.Length = 100;

BinaryFormatter bf = new BinaryFormatter();

MemoryStream ms = new MemoryStream();

bf.Serialize(ms, msc);


byte[] bytes = ms.ToArray();

string base64data = Convert.ToBase64String(bytes);

textBox1.Text = base64data;

ms.Close();


}

//Deserialize the class instance from the text in the textbox
private void btnDeserialize_Click(object sender, EventArgs e)
{
byte[] bytes = Convert.FromBase64String(textBox1.Text);

MemoryStream ms = new MemoryStream(bytes);

ms.Position = 0;

BinaryFormatter bf = new BinaryFormatter();

object obj = bf.Deserialize(ms);

ms.Close();

MySavableClass msc = obj as MySavableClass;

if (msc != null)
{
MessageBox.Show(
string.Format("MyID: {0}\r\nTitle: {1}\r\nLength: {2}",
msc.MyID,msc.Title,msc.Length)
);

}

}

=============Xml serialization===============
private void btnXmlSerialize_Click(object sender, EventArgs e)
{
MySavableClass msc = new MySavableClass();

msc.MyID = "id1";
msc.Title = "default title";
msc.Length = 100;

XmlSerializer serializer = new
XmlSerializer(typeof(MySavableClass));


StringWriter sw = new StringWriter();


serializer.Serialize(sw, msc);


textBox1.Text = sw.ToString();

sw.Close();

}

private void btnXmlDeserialize_Click(object sender, EventArgs e)
{

XmlSerializer serializer = new
XmlSerializer(typeof(MySavableClass));


StringReader sr = new StringReader(textBox1.Text);

object obj = serializer.Deserialize(sr);

sr.Close();

MySavableClass msc = obj as MySavableClass;

if (msc != null)
{
MessageBox.Show(
string.Format("MyID: {0}\r\nTitle: {1}\r\nLength: {2}",
msc.MyID, msc.Title, msc.Length)
);

}
}
=======================================

=======test class==========
[Serializable]
public class MySavableClass
{
private string _myid;
private string _title;
private int _length;

public MySavableClass()
{

}

public string MyID
{
get { return _myid; }
set { _myid = value; }
}

public string Title
{
get { return _title; }
set { _title = value; }
}

public int Length
{
get { return _length; }
set { _length = value; }
}
}
========================

In addition, you can have a look at the MSDN document about .net
serialization for further reference:

#XML and SOAP Serialization
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconserialization.asp?
frame=true

#Binary Serialization
http://msdn.microsoft.com/library/en-us/cpguide/html/cpconbinaryserializatio
n.asp?frame=true

Hope this helps.

Regards,

Steven Cheng
Microsoft Online Community Support


==================================================

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

==================================================


This posting is provided "AS IS" with no warranties, and confers no rights.



Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
Hey Alex,

How are you doing on this issue or does my suggestion in the last reply
helps you some? If there is still anything we can help, please feel free to
post here.

Regards,

Steven Cheng
Microsoft Online Community Support


==================================================

When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.

==================================================


This posting is provided "AS IS" with no warranties, and confers no rights.



Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
Back
Top