473,848 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

serializing an object to a string

Hi,

I need to serialize an object into a string representation to store it
into a database. So the SOAPFormatter seems to be the right formatter
for this purpose. Now I have the problem that this formatter writes into
a stream. And I am not used enough to C# to convert this to a string.
I tried the following code:

MemoryStream stream= new MemoryStream() ;
IFormatter formatter = new SoapFormatter() ;
formatter.Seria lize(stream, o);
byte[] buffer= stream.GetBuffe r();
stream.Close();
UTF8Encoding encoding = new UTF8Encoding( );
string s= encoding.GetStr ing(buffer);

stream= new MemoryStream();
encoding= new UTF8Encoding();
buffer= encoding.GetByt es(s);
stream.Write(bu ffer, 0, buffer.Length);
formatter = new SoapFormatter() ;
object o2= formatter.Deser ialize(stream);
stream.Close();

That should serialize and deserialize the object. But I get the
exception "XmlExcepti on: The root element is missing." on
formatter.Deser ialize(stream). Now I do not know what the problem here
is. When writing the string to a file it seems that there are
non-character bytes at the end of the string. I do not know whether this
really is the problem here, so I hope someone can point me to the right
direction.

Another problem is: Is UTF8 Encoding the correct one? Would be another
encoding more appropriate?

Regards
Marco
Nov 16 '05 #1
6 13364
Marco Herrn wrote:
formatter.Deser ialize(stream). Now I do not know what the problem here
is. When writing the string to a file it seems that there are
non-character bytes at the end of the string. I do not know whether this
really is the problem here, so I hope someone can point me to the right
direction.
GetBuffer can return a byte[] that is longer than what you have written.
Another problem is: Is UTF8 Encoding the correct one? Would be another
encoding more appropriate?


There is probably no reason to even set the encoding.

You code should probably not construct a new memory-stream and write the
nuffer to it. you can use the MemoryStream.Me moryStream(byte[] buf, int
index, int count) to create a "view" of a buffer, so you don't have to
copy the content.

I seem to recall that SoapFormatter may be leaky. For the test, it's
fine to create a new one for each serialization, but you may wish to
consider sharing the IFormatter between invocations for the real code.

I would try code roughly like:

void testSerializer( object o) {
byte[] bytes;
int length = 0;
// Write
using ( MemoryStream ws = new MemoryStream() ) {
new Soapformatter() .Serialize(ws,o );
length = ws.length;
bytes = ws.GetBuffer();
}
// Read
using ( MemoryStream rs = new MemoryStream(by tes, 0, length) )
object o2 = new SoapFormatter() .Deserialize(rs );
System.Diagnost ics.Debug.Asser t(o.Equals(o2),
"Deserializatio n gave non-equal object");
}
Nov 16 '05 #2
Hi Helge,

Helge Jensen wrote:
Marco Herrn wrote:
Another problem is: Is UTF8 Encoding the correct one? Would be another
encoding more appropriate?


There is probably no reason to even set the encoding.


But when converting the byte Array to a string I need to use a Encoding.
Or is there a different way of this conversion?

Thanks for your code example. It works. But still lacks the conversion
to a string. How can I convert the buffer _without_ converting the extra
bytes at the end?

Regards
Marco
Nov 16 '05 #3
Marco Herrn wrote:
Hi Helge,
Hi.
Helge Jensen wrote:
Marco Herrn wrote:
Another problem is: Is UTF8 Encoding the correct one? Would be
another encoding more appropriate?

I don't think any *particular* encoding is appropriate.

A good choice would be the one the SoapFormatter uses, but it's really
not required.
There is probably no reason to even set the encoding. But when converting the byte Array to a string I need to use a Encoding.
Or is there a different way of this conversion?


Can't you store the serialized object without conversion? You are
introducing an interpretation.

Try thinking what about what would happen if you chose Base64
en/de-coding for the conversion between byte[] and string. It would
work, since the encoding of the xml-document is independent of the
string<->byte conversion.

You could look into the serialized byte[] and choose an encoding based
on the xml encondig-declaration (it would be the identity encoding), but
it's really better if you could just skip the conversion byte[] <-> string.
Thanks for your code example. It works. But still lacks the conversion
to a string. How can I convert the buffer _without_ converting the extra
bytes at the end?


I think you should go out of your way, not to do that conversion.
--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 16 '05 #4
FYI SoapFormatter is going to become obsolete in the next version of .Net
--
HTH

Ollie Riches
http://www.phoneanalyser.net

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a programmer
helping programmers.

"Marco Herrn" <no************ ****@sourcepark .org> wrote in message
news:42******** **************@ newsread2.arcor-online.net...
Hi,

I need to serialize an object into a string representation to store it
into a database. So the SOAPFormatter seems to be the right formatter
for this purpose. Now I have the problem that this formatter writes into
a stream. And I am not used enough to C# to convert this to a string.
I tried the following code:

MemoryStream stream= new MemoryStream() ;
IFormatter formatter = new SoapFormatter() ;
formatter.Seria lize(stream, o);
byte[] buffer= stream.GetBuffe r();
stream.Close();
UTF8Encoding encoding = new UTF8Encoding( );
string s= encoding.GetStr ing(buffer);

stream= new MemoryStream();
encoding= new UTF8Encoding();
buffer= encoding.GetByt es(s);
stream.Write(bu ffer, 0, buffer.Length);
formatter = new SoapFormatter() ;
object o2= formatter.Deser ialize(stream);
stream.Close();

That should serialize and deserialize the object. But I get the
exception "XmlExcepti on: The root element is missing." on
formatter.Deser ialize(stream). Now I do not know what the problem here
is. When writing the string to a file it seems that there are
non-character bytes at the end of the string. I do not know whether this
really is the problem here, so I hope someone can point me to the right
direction.

Another problem is: Is UTF8 Encoding the correct one? Would be another
encoding more appropriate?

Regards
Marco

Nov 16 '05 #5
Hi,

Helge Jensen wrote:
Can't you store the serialized object without conversion? You are
introducing an interpretation.
The reason I am trying to do this is to store the serialized object in a
database. Therefore I want it in string form. Maybe there are better
solutions to do this. Do you have any idea how to achieve this?
Try thinking what about what would happen if you chose Base64
en/de-coding for the conversion between byte[] and string. It would
work, since the encoding of the xml-document is independent of the
string<->byte conversion.


Hmm, sounds good. Do you think base64-encoding it, would be a solution
to my problem? I still would have to generate a second byte[] that omits
the trailing bytes. Otherwise I would have to store the length of the
actual object too to be able to deserialize it.

Regards
Marco
Nov 16 '05 #6
Marco Herrn wrote:
The reason I am trying to do this is to store the serialized object in a
database. Therefore I want it in string form. Maybe there are better
solutions to do this. Do you have any idea how to achieve this?
BLOB, it stores chunks of bytes in most databases.
Hmm, sounds good. Do you think base64-encoding it, would be a solution
to my problem? I still would have to generate a second byte[] that omits
the trailing bytes. Otherwise I would have to store the length of the
actual object too to be able to deserialize it.


I don't understand why you would need the length separatly. You
serialize (via MemoryStream) to byte[] and encode that as base64, store
in DB.

To read back read entire string, decode from base64 to byte[], create
new MemoryStream(de coded, 0, decoded.Length) , and run the deserializer
on that.

Beware, the strings are probably gonna be pretty big.

An alternative way is to store the objects on disk (which nicely removes
need for MemoryStream, that is likely to spend mem on the
large-object-heap when serializing) in files, and just let the DB
contain items (paths) identifying the files.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 16 '05 #7

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

Similar topics

0
1333
by: Ante Smolcic | last post by:
Hi all, I have an ArrayList that contains items of type A. I declared the XmlArrayItem atribute for that type. Now I have an derived type B (from A) also contained in the ArrayList but I get an error when serializing. Can this be made without redeclaring the ArrayList special attributes? The problem is that the class B is in different namespace!
1
2091
by: Ivo Bronsveld | last post by:
All, I have quite a challenging task ahead of me. I need to write an object model (for code access) based on a schema, which cannot be made into a dataset because of it's complexity. So I created a couple of objects and serializing it into XML based upon the schema works perfectly. The XML / Schema looks something like this:
2
3527
by: Tobias Zimmergren | last post by:
Hi, just wondering what serializing really is, and howto use it? Thanks. Tobias __________________________________________________________________ Tobias ICQ#: 55986339 Current ICQ status: + More ways to contact me __________________________________________________________________
0
1406
by: Kenneth Baltrinic | last post by:
Is the following code correct for serializing a quasi-single class, that is a class that has a descreet (though more than one, so not a true singleton) number of static instances and no dynamically creatable instances? Please forgive my use of terms. Quasi-signleton is a term I made up and static instances is a little bogus too but I don't know the correct terms for what I mean if there are any. However, I think the code below should be...
0
1633
by: JackRazz | last post by:
I'm trying to serialize a collection to a file stream by serializing each object individually. The code below works fine with the BinaryFormatter, but the SoapFormatter reads the first object and just goes to the end of the file. After reading the first object, the fStream.Position is pointed to the end of the file. The collection serializes/deserilizes fine when I just serialize the hashtable vs. each object in the hashtable. Does...
3
3578
by: Tom | last post by:
I am having trouble serializing a color property. Basically, it is not serializing the value. For instance, in the following: <Serializable()> _ Public Class TestColor Private _MyColor As System.Drawing.Color = System.Drawing.Color.Red Public Property MyColor() As System.Drawing.Color Get Return _MyColor
2
331
by: Charles Law | last post by:
I have a complex object that I am serializing, and I would like to omit elements that have a default value. For example, if I have a class as follows Public Class Test Private m_Name As String = "George" Private m_Active As Boolean = False Private m_Address As String
0
3290
by: | last post by:
Hi I'm currently having trouble serializing an object to Xml, in the format I need. Below is the object definition. ------------------------------- public class Folders {
0
1250
by: dph5010 | last post by:
I'm trying to make an object that will reflect the response from isbndb.com's API so I can serialize the results into my code. Right now I have code that works, however, the structure isn't quite the same as what isbndb.com uses. My problem, is serializing the array of BookData objects and putting attributes into the array wrapper tag <BookList>. Right now, I'm just using a custom object called BookList to add attributes to the element, but...
0
9893
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10664
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10722
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10348
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9500
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7069
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5919
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4544
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4137
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.