473,403 Members | 2,338 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,403 software developers and data experts.

Serialization not working

I want to serialize a class that I am using to retain some information the
user types into a screen. I have 3 questions.

1) I serialized it as XML to start with. This works, but how do I serialize
the strings so that they are not messed up if they have XML in them, or
control characters? Is there a way to do that in XML, or do I have to use
BinaryFormatters?

2) So I tried using a binary formatter, and it won't serialize/deserialize
the darn thing. It doesn't look like rocket science, but apparently I'm
missing something. Simplified example below.

3) If I use a binary formatter (or an XML one for that matter), what
happens if/when I add a new property to my class? Do I need to account for
that somehow?

I'm posting all of the code with the three test cases (one uses a memory
stream just for grins; it doesn't work either). It's about 130 lines of
code. Hope this isn't too much to post. Hopefully the intendation will come
across right.
//================================================== =================
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.IO;
namespace TestFruitLoopsTiny
{
[Serializable()]
public class BusinessCardData
{

[NonSerialized()]
private string _NameData;
public string NameData
{
get { return _NameData; }
set { _NameData = value; }
}

[NonSerialized()]
private string _CompanyData;
public string CompanyData
{
get { return _CompanyData; }
set { _CompanyData = value; }
}

public BusinessCardData()
{
SetDefaults();
}

public void SetDefaults()
{
this.NameData = string.Empty;
this.CompanyData = string.Empty;
}

public void TestBinary()
{
//Write it
using (FileStream fs
= new FileStream("D:\\test.dat", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter(null,
new StreamingContext(StreamingContextStates.File));
bf.Serialize(fs, this);
OutputData("Original data (binary)", this);
}
//Read it
if (System.IO.File.Exists("D:\\test.dat"))
{
using (FileStream fs
= new FileStream("D:\\test.dat", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter(null,
new StreamingContext(StreamingContextStates.File));
BusinessCardData bcd = (BusinessCardData)bf.Deserialize(fs);
OutputData("After reading it back in (binary) ", bcd);
}
}
}

public void TestXML()
{
XmlSerializer xs = new XmlSerializer(typeof(BusinessCardData));
using (FileStream fs = new FileStream("D:\\test.dat",
FileMode.Create))
{
xs.Serialize(fs, this);
OutputData("Original data (XML)", this);
}
//read it back in
BusinessCardData bcd;
using (FileStream fs = new FileStream("D:\\test.dat", FileMode.Open))
{
bcd = (BusinessCardData)xs.Deserialize(fs);
}
OutputData("After reading it back in (XML)", bcd);
}

public void TestMemory()
{
using (MemoryStream ms = new MemoryStream(200))
{
OutputData("OriginalData (memory)", this);
BinaryFormatter bf = new BinaryFormatter(null,
new StreamingContext(StreamingContextStates.Clone));
bf.Serialize(ms, this);
//read it back in
ms.Seek(0, SeekOrigin.Begin);
BusinessCardData abc = (BusinessCardData)bf.Deserialize(ms);
OutputData("After reading it back in (memory)", abc);
}
}

private static void OutputData(string caption,
BusinessCardData bcd)
{
Console.WriteLine(caption);
Console.WriteLine(" Name = {0}, Company = {1}",
bcd.NameData, bcd.CompanyData);
}

}
}

//================================================== =================
//****TEST ROUTINE***
static void Test()
{
BusinessCardData bcd = new BusinessCardData();
bcd.CompanyData = "Apple";
bcd.NameData = "Robin";
bcd.TestBinary();

bcd.CompanyData = "Apple";
bcd.NameData = "Robin";
bcd.TestXML();

bcd.CompanyData = "Apple";
bcd.NameData = "Robin";
bcd.TestMemory();

Console.ReadLine("Press any key to return");

}
//================================================== =================

I'm sure I'm doing something stupid, or stupidly NOT doing something.

I'd appreciate any help you can provide.

Thanks,
Robin S.
Jul 15 '07 #1
5 4300
RobinS <Ro****@NoSpam.yah.nonewrote:
I want to serialize a class that I am using to retain some information the
user types into a screen. I have 3 questions.

1) I serialized it as XML to start with. This works, but how do I serialize
the strings so that they are not messed up if they have XML in them, or
control characters? Is there a way to do that in XML, or do I have to use
BinaryFormatters?
If they contain XML themselves, that's fine. If they contain control
characters which aren't allowed in XML, serialization will produce an
invalid XML file and deserialization will fail.
2) So I tried using a binary formatter, and it won't serialize/deserialize
the darn thing. It doesn't look like rocket science, but apparently I'm
missing something. Simplified example below.
I *believe* that BinaryFormatter uses fields rather than properties for
serialization. You've specified that the fields shouldn't be
serialized, so you don't get any useful information out.
3) If I use a binary formatter (or an XML one for that matter), what
happens if/when I add a new property to my class? Do I need to account for
that somehow?
With binary formatters, if you add a new field (or remove an old one) I
believe you have to go through significant hoops to get cross-version
serialization to work.

I *believe* the XML formatter will ignore any extra properties it
doesn't understand in the XML it reads for deserialization, and won't
complain if not all the properties are specified.

You may have noticed a large amount of "belief" statements in here -
I'm far from an expert on serialization. These are just my beliefs,
mostly based on experimentation with your test app.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 15 '07 #2
Comments below...

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
RobinS <Ro****@NoSpam.yah.nonewrote:
>I want to serialize a class that I am using to retain some information
the
user types into a screen. I have 3 questions.

1) I serialized it as XML to start with. This works, but how do I
serialize
the strings so that they are not messed up if they have XML in them, or
control characters? Is there a way to do that in XML, or do I have to
use
BinaryFormatters?

If they contain XML themselves, that's fine. If they contain control
characters which aren't allowed in XML, serialization will produce an
invalid XML file and deserialization will fail.
**********************

So what about carriage returns or if they have some kind of tags in them?
Will either of those cases cause me problems? My boss said something about
being able to wrap the strings in some kind of brackets so XML will know
everything inside the brackets is text, even if it's some kind of XML-y
script. I mean, if they put in something like </NameData>, how could it
work?

**********************
>
>2) So I tried using a binary formatter, and it won't
serialize/deserialize
the darn thing. It doesn't look like rocket science, but apparently I'm
missing something. Simplified example below.

I *believe* that BinaryFormatter uses fields rather than properties for
serialization. You've specified that the fields shouldn't be
serialized, so you don't get any useful information out.
**********************
Arggghhhhhh!!!!! You're right. I remove the attributes for not serializing,
and it worked. One of the examples I looked at had all of the private
fields marked with attributes, so I assume they would be serialized (in
XML) if I didn't mark them appropriately.
**********************
>
>3) If I use a binary formatter (or an XML one for that matter), what
happens if/when I add a new property to my class? Do I need to account
for
that somehow?

With binary formatters, if you add a new field (or remove an old one) I
believe you have to go through significant hoops to get cross-version
serialization to work.

I *believe* the XML formatter will ignore any extra properties it
doesn't understand in the XML it reads for deserialization, and won't
complain if not all the properties are specified.
**********************
You're right, the XML formatter does appear to handle extra properties.
I saved the file, added a new property, and read the file back in, and it
works fine. I would be more than happy working with XML if I can figure out
what to do about the carriage-returns and any kind of funky characters
they put into the textboxes.

Also, when I read it back in, it doesn't "display" the carriage-returns
in the textbox, but they are there. I'm taking the entries and writing them
to
a graphics surface using DrawString, and the carriage returns are showing
up in the output. Then later I'm reading the XML back in and putting it
back in the textboxes for the user to edit. The textbox has "AcceptsReturn"
set to true. Do I need to check the string for carriage-returns and split
it into the lines[] property of the textbox?

**********************
>
You may have noticed a large amount of "belief" statements in here -
I'm far from an expert on serialization. These are just my beliefs,
mostly based on experimentation with your test app.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Reminds me "This I Believe", on NPR. "This I believe -- that XML
serialization
is easy if you do it right!"

Thanks for the comments and help, and to anyone else who chimes in.

Robin S.
Jul 16 '07 #3
Re xml characters in the string, they will be escaped according to the
rules of xml - usually as &lt; and &gt; etc. Note that for a high-
density string of xml (lots of small tags) this could cause non-
trivial bloat. Carriage return is legal xml, but note the whitespace
rules in xml. But the serialization authors have considered most of
these things - it should just work.

Re adding fields (BinarySerializer) - look at Version Tolerant
Serlialization: http://msdn2.microsoft.com/en-us/library/ms229752.aspx

Re ading properties (XmlSerializer) - one other thing that might be of
interest is DataContractSerializer; apart from offering more
flexibility than the older XmlSerializer, this also offers simple
forward (and round-trip) compatibility.
http://msdn2.microsoft.com/en-us/lib...erializer.aspx

Marc

Jul 16 '07 #4

"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@n2g2000hse.googlegro ups.com...
Re xml characters in the string, they will be escaped according to the
rules of xml - usually as &lt; and &gt; etc. Note that for a high-
hello Marc
you can avoid &lt; and &gt; by implementing IXmlSerializable and use
WriteRaw and ReadOuterXml functions :

public void WriteXml(XmlWriter writer)
{
...
writer.WriteRaw(myXmlAttr);
...
}
public void ReadXml(XmlReader reader)
{
...
myXmlAttr = reader.ReadOuterXml();
...
}
Didier
Jul 16 '07 #5
Thanks to all who replied. It was a lot of really useful info!

Robin S.
------------------------------
"Didier Bolf" <Di*********@wanadoo.frwrote in message
news:46**********************@news.free.fr...
>
"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@n2g2000hse.googlegro ups.com...
>Re xml characters in the string, they will be escaped according to the
rules of xml - usually as &lt; and &gt; etc. Note that for a high-

hello Marc
you can avoid &lt; and &gt; by implementing IXmlSerializable and use
WriteRaw and ReadOuterXml functions :

public void WriteXml(XmlWriter writer)
{
...
writer.WriteRaw(myXmlAttr);
...
}
public void ReadXml(XmlReader reader)
{
...
myXmlAttr = reader.ReadOuterXml();
...
}
Didier


Jul 24 '07 #6

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

Similar topics

2
by: Dave Veeneman | last post by:
I'm working on a project where I have to persist data to a file, rather than to a database. Basically, I need to save the state of several classes, each of which will have a couple of dozen...
5
by: francois | last post by:
First of all I would to to apologize for resending this post again but I feel like my last post as been spoiled Here I go for my problem: Hi, I have a webservice that I am using and I would...
2
by: ofer | last post by:
Hi, I am working with the beta version of the new .net framework (Whidbey) and I encountered a problem with serialization that did'nt exist in the .net 2003 the situation is like this : I have...
5
by: Tamir Khason | last post by:
Hi, all Two classes Foo1 and Foo2 Foo1 uses Foo2 as reference Both are strong name signed with the same key pair I'm performing Binary Serialization of object inside Foo2 from Foo1 as following:...
8
by: vinay | last post by:
Hi Guys I want to understand Serialization. What is serialization. When do we need to use?? What are advantages and Disadvantages. Also please diret me to some good sites on serialization....
6
by: Larry Serflaten | last post by:
Acording to Bob Powell, serializing an object should be a breeze: http://groups.google.com/groups?hl=en&lr=&safe=off&selm=%23TR3qvCcCHA.2544%40tkmsftngp11 But its not happening, and I can't see...
5
by: Harold Howe | last post by:
I am having a problem deserializing objects from a library when the following conditions exist: 1- The library is strongly named 2- The serialized file was created with version 1.0 of the...
0
by: Michael | last post by:
I have a problem with serialization in my project. Serialization is working fine so far but when I increase the version of the application in the AssemblyInfo.cs I get an exception. So I created a...
0
by: elziko | last post by:
In the past when doing binary serialization I have been able to implement my own serialization for a type by defining a serialization surrogate for this type. I am now working on something...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.