473,761 Members | 4,407 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Program.... XML serialization

Hello,

Can somebody help me a little bit?

I can't get it to work.
Please see my code below... I have placed some comments like "// And whats
next?".
I'm sure that I have to code something here. But what?

What do I want?
- Serialize and deserialize ObjectsA and ObjectsB.

Thanks!
Arjen


namespace ProgramMainName {

class ProgramMainName {

public static Hashtable ObjectsA = new Hashtable();
public static Hashtable ObjectsB = new Hashtable();

/// <summary>
/// The main!
/// </summary>
[STAThread]
static void Main(string[] args) {
// To do something, like: XMLSerializatio n.Open()
}
}
}

namespace ProgramMainName {
public class XMLSerializatio n {

public static void Open() {

XmlSerializer x = new XmlSerializer( typeof( ProgramMainName ) );

FileStream fs = null;
try {
fs = new FileStream( "data.xml", FileMode.Open );

XmlReader reader = new XmlTextReader( fs );
ProgramMainName programMainName = (ProgramMainNam e) x.Deserialize(
reader );
// And whats next?
}
catch( FileNotFoundExc eption ) {

}
finally {
if ( fs != null )
fs.Close();
}
}
}

public static void Save() {
// And whats next?
}
}


Nov 15 '05 #1
5 2367
A good idea is to use a serializer, either a binary serializer or soap serilizer.
All objects that you add to the Hashtable must be marked as serilizable:

[Serializable]
class TestClass
{
public int iVal = 8;
public string strVal = "member value";
}

Then, you can perform serialization and deserialization :

Hashtable objA = new Hashtable();
Hashtable objB = new Hashtable();

System.Runtime. Serialization.F ormatters.Soap. SoapFormatter x = new System.Runtime. Serialization.F ormatters.Soap. SoapFormatter ();

TestClass tc = new TestClass ();
tc.iVal = 10;

objA.Add ("key1", "value key1");
objA.Add ("key2", "value key2");
objA.Add ("key3", tc);

FileStream fs = new FileStream ("Store.xml",Fi leMode.OpenOrCr eate ,FileAccess.Wri te );
x.Serialize (fs, objA);
fs.Close ();

fs = new FileStream ("Store.xml" , FileMode.Open, FileAccess.Read );
objB = (Hashtable) x.Deserialize (fs);

IDictionaryEnum erator en = objB.GetEnumera tor ();
while (en.MoveNext ())
{
Debug.WriteLine (string.Format ("{0}: {1}", en.Key, objB [en.Key]));
}
Debug.WriteLine ("val3: " + "iVal: " + ((TestClass)obj B ["key3"]).iVal);

There is a difference between the XML and binary serialization. An exert from tne .net documantation:

Note XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all of an object's fields and properties, both public and private, use the BinaryFormatter instead of XML serialization.

I tried to use XmlSerializer but didn't manage. According to the documentation a collection that implements ICollection or IEnumerable (which both are implemented by Hashtable) should be serializable with XmlSerializer. But while trying to use XmlSerializer with the typeof (Hashtable) I kept on getting the error:

An unhandled exception of type 'System.Invalid OperationExcept ion' occurred in system.xml.dll
Additional information: There was an error reflecting 'System.Collect ions.Hashtable' .
"Arjen" <bo*****@hotmai l.com> wrote in message news:bv******** **@news2.tilbu1 .nb.home.nl...
Hello,

Can somebody help me a little bit?

I can't get it to work.
Please see my code below... I have placed some comments like "// And whats
next?".
I'm sure that I have to code something here. But what?

What do I want?
- Serialize and deserialize ObjectsA and ObjectsB.

Thanks!
Arjen




namespace ProgramMainName {

class ProgramMainName {

public static Hashtable ObjectsA = new Hashtable();
public static Hashtable ObjectsB = new Hashtable();

/// <summary>
/// The main!
/// </summary>
[STAThread]
static void Main(string[] args) {
// To do something, like: XMLSerializatio n.Open()
}
}
}





namespace ProgramMainName {
public class XMLSerializatio n {

public static void Open() {

XmlSerializer x = new XmlSerializer( typeof( ProgramMainName ) );

FileStream fs = null;
try {
fs = new FileStream( "data.xml", FileMode.Open );

XmlReader reader = new XmlTextReader( fs );
ProgramMainName programMainName = (ProgramMainNam e) x.Deserialize(
reader );
// And whats next?
}
catch( FileNotFoundExc eption ) {

}
finally {
if ( fs != null )
fs.Close();
}
}
}

public static void Save() {
// And whats next?
}
}



Nov 15 '05 #2
Cezary Nolewajka,

Thanks for your answer.

I see that you are putting data from objA to objB.
My questions was more how to serialize them both in the same file.
If you do that then you have no root element.

The solotion will be to serialize the class... if tried it but can't get it
to work.

Arjen
"Cezary Nolewajka" <c.************ *********@no-sp-am-eh-mail.com> schreef in
bericht news:uR******** ******@TK2MSFTN GP09.phx.gbl...
A good idea is to use a serializer, either a binary serializer or soap
serilizer.
All objects that you add to the Hashtable must be marked as serilizable:

[Serializable]
class TestClass
{
public int iVal = 8;
public string strVal = "member value";
}

Then, you can perform serialization and deserialization :

Hashtable objA = new Hashtable();
Hashtable objB = new Hashtable();

System.Runtime. Serialization.F ormatters.Soap. SoapFormatter x = new
System.Runtime. Serialization.F ormatters.Soap. SoapFormatter ();

TestClass tc = new TestClass ();
tc.iVal = 10;

objA.Add ("key1", "value key1");
objA.Add ("key2", "value key2");
objA.Add ("key3", tc);

FileStream fs = new FileStream ("Store.xml",Fi leMode.OpenOrCr eate
,FileAccess.Wri te );
x.Serialize (fs, objA);
fs.Close ();

fs = new FileStream ("Store.xml" , FileMode.Open, FileAccess.Read );
objB = (Hashtable) x.Deserialize (fs);

IDictionaryEnum erator en = objB.GetEnumera tor ();
while (en.MoveNext ())
{
Debug.WriteLine (string.Format ("{0}: {1}", en.Key, objB [en.Key]));
}
Debug.WriteLine ("val3: " + "iVal: " + ((TestClass)obj B ["key3"]).iVal);

There is a difference between the XML and binary serialization. An exert
from tne .net documantation:

Note XML serialization does not convert methods, indexers, private
fields, or read-only properties (except read-only collections). To serialize
all of an object's fields and properties, both public and private, use the
BinaryFormatter instead of XML serialization.

I tried to use XmlSerializer but didn't manage. According to the
documentation a collection that implements ICollection or IEnumerable (which
both are implemented by Hashtable) should be serializable with
XmlSerializer. But while trying to use XmlSerializer with the typeof
(Hashtable) I kept on getting the error:

An unhandled exception of type 'System.Invalid OperationExcept ion' occurred
in system.xml.dll
Additional information: There was an error reflecting
'System.Collect ions.Hashtable' .
"Arjen" <bo*****@hotmai l.com> wrote in message
news:bv******** **@news2.tilbu1 .nb.home.nl...
Hello,

Can somebody help me a little bit?

I can't get it to work.
Please see my code below... I have placed some comments like "// And whats
next?".
I'm sure that I have to code something here. But what?

What do I want?
- Serialize and deserialize ObjectsA and ObjectsB.

Thanks!
Arjen


namespace ProgramMainName {

class ProgramMainName {

public static Hashtable ObjectsA = new Hashtable();
public static Hashtable ObjectsB = new Hashtable();

/// <summary>
/// The main!
/// </summary>
[STAThread]
static void Main(string[] args) {
// To do something, like: XMLSerializatio n.Open()
}
}
}

namespace ProgramMainName {
public class XMLSerializatio n {

public static void Open() {

XmlSerializer x = new XmlSerializer( typeof( ProgramMainName ) );

FileStream fs = null;
try {
fs = new FileStream( "data.xml", FileMode.Open );

XmlReader reader = new XmlTextReader( fs );
ProgramMainName programMainName = (ProgramMainNam e) x.Deserialize(
reader );
// And whats next?
}
catch( FileNotFoundExc eption ) {

}
finally {
if ( fs != null )
fs.Close();
}
}
}

public static void Save() {
// And whats next?
}
}

Nov 15 '05 #3
Well, just put both Hashtables into one class, make it serializable and here you go:

[Serializable]
public class TestClass
{
public int iVal = 8;
public string strVal = "member value";
}

[Serializable]
public class ContainerClass
{
public Hashtable objA = new Hashtable();
public Hashtable objB = new Hashtable();
}
System.Runtime. Serialization.F ormatters.Soap. SoapFormatter x = new System.Runtime. Serialization.F ormatters.Soap. SoapFormatter ();

ContainerClass obj = new ContainerClass ();

TestClass tc = new TestClass ();
tc.iVal = 10;

obj.objA.Add ("key1", "value key1");
obj.objA.Add ("key2", "value key2");
obj.objA.Add ("key3", tc);

obj.objB.Add ("key4", "value key4");
obj.objB.Add ("key5", "value key5");
obj.objB.Add ("key6", tc);

FileStream fs = new FileStream ("Store.xml",Fi leMode.OpenOrCr eate ,FileAccess.Wri te );
x.Serialize (fs, obj);
fs.Close ();

fs = new FileStream ("Store.xml" , FileMode.Open, FileAccess.Read );
obj = (ContainerClass ) x.Deserialize (fs);

IDictionaryEnum erator en = obj.objA.GetEnu merator ();
while (en.MoveNext ())
{
Debug.WriteLine (string.Format ("{0}: {1}", en.Key, obj.objA [en.Key]));
}
Debug.WriteLine ("val3: " + "iVal: " + ((TestClass)obj .objA ["key3"]).iVal);

en = obj.objB.GetEnu merator ();
while (en.MoveNext ())
{
Debug.WriteLine (string.Format ("{0}: {1}", en.Key, obj.objB [en.Key]));
}
Debug.WriteLine ("val6: " + "iVal: " + ((TestClass)obj .objB ["key6"]).iVal);
"Arjen" <bo*****@hotmai l.com> wrote in message news:bv******** **@news3.tilbu1 .nb.home.nl...
Cezary Nolewajka,

Thanks for your answer.

I see that you are putting data from objA to objB.
My questions was more how to serialize them both in the same file.
If you do that then you have no root element.

The solotion will be to serialize the class... if tried it but can't get it
to work.

Arjen


"Cezary Nolewajka" <c.************ *********@no-sp-am-eh-mail.com> schreef in
bericht news:uR******** ******@TK2MSFTN GP09.phx.gbl...
A good idea is to use a serializer, either a binary serializer or soap
serilizer.
All objects that you add to the Hashtable must be marked as serilizable:

[Serializable]
class TestClass
{
public int iVal = 8;
public string strVal = "member value";
}

Then, you can perform serialization and deserialization :

Hashtable objA = new Hashtable();
Hashtable objB = new Hashtable();

System.Runtime. Serialization.F ormatters.Soap. SoapFormatter x = new
System.Runtime. Serialization.F ormatters.Soap. SoapFormatter ();

TestClass tc = new TestClass ();
tc.iVal = 10;

objA.Add ("key1", "value key1");
objA.Add ("key2", "value key2");
objA.Add ("key3", tc);

FileStream fs = new FileStream ("Store.xml",Fi leMode.OpenOrCr eate
,FileAccess.Wri te );
x.Serialize (fs, objA);
fs.Close ();

fs = new FileStream ("Store.xml" , FileMode.Open, FileAccess.Read );
objB = (Hashtable) x.Deserialize (fs);

IDictionaryEnum erator en = objB.GetEnumera tor ();
while (en.MoveNext ())
{
Debug.WriteLine (string.Format ("{0}: {1}", en.Key, objB [en.Key]));
}
Debug.WriteLine ("val3: " + "iVal: " + ((TestClass)obj B ["key3"]).iVal);

There is a difference between the XML and binary serialization. An exert
from tne .net documantation:

Note XML serialization does not convert methods, indexers, private
fields, or read-only properties (except read-only collections). To serialize
all of an object's fields and properties, both public and private, use the
BinaryFormatter instead of XML serialization.

I tried to use XmlSerializer but didn't manage. According to the
documentation a collection that implements ICollection or IEnumerable (which
both are implemented by Hashtable) should be serializable with
XmlSerializer. But while trying to use XmlSerializer with the typeof
(Hashtable) I kept on getting the error:

An unhandled exception of type 'System.Invalid OperationExcept ion' occurred
in system.xml.dll
Additional information: There was an error reflecting
'System.Collect ions.Hashtable' .
"Arjen" <bo*****@hotmai l.com> wrote in message
news:bv******** **@news2.tilbu1 .nb.home.nl...
Hello,

Can somebody help me a little bit?

I can't get it to work.
Please see my code below... I have placed some comments like "// And whats
next?".
I'm sure that I have to code something here. But what?

What do I want?
- Serialize and deserialize ObjectsA and ObjectsB.

Thanks!
Arjen


namespace ProgramMainName {

class ProgramMainName {

public static Hashtable ObjectsA = new Hashtable();
public static Hashtable ObjectsB = new Hashtable();

/// <summary>
/// The main!
/// </summary>
[STAThread]
static void Main(string[] args) {
// To do something, like: XMLSerializatio n.Open()
}
}
}

namespace ProgramMainName {
public class XMLSerializatio n {

public static void Open() {

XmlSerializer x = new XmlSerializer( typeof( ProgramMainName ) );

FileStream fs = null;
try {
fs = new FileStream( "data.xml", FileMode.Open );

XmlReader reader = new XmlTextReader( fs );
ProgramMainName programMainName = (ProgramMainNam e) x.Deserialize(
reader );
// And whats next?
}
catch( FileNotFoundExc eption ) {

}
finally {
if ( fs != null )
fs.Close();
}
}
}

public static void Save() {
// And whats next?
}
}


Nov 15 '05 #4
Hi there,

I have tried to run your sample without succes.
So I have made a new sample. Maybe you can fix the serialization?

The class "MyProgram" must be saved to an xml file and placed back in the
program with the "open" call.

Hope you can do something for me.
Thanks,
Arjen
// -------------------------------------------------------------------------
-----------
using System;
using System.Collecti ons;

namespace MyProgram {

class MyProgram {

public static Hashtable Persons = new Hashtable();

[STAThread]
static void Main(string[] args) {
Open();

DoSomeThing();

Save();
}

static public void DoSomeThing() {

// New object
Person person = new Person("James", 12);

// Add to the hashtable
Persons.Add( person.GetHashC ode(), person);
}
static void Open() {
// Read the serialization

}

static void Save() {
// Save the serialization

}
}

class Person {
string _name;
int _age;

public Person( string name, int age) {
_name = name;
_age = age;
}
}
}

Nov 15 '05 #5
Please, feel free to dowload my full working project at:

http://klub.chip.pl/nolewajk/work/sa...ialization.zip

--
Cezary Nolewajka
mailto:c.****** *************** @no-sp-am-eh-mail.com
remove all "no-sp-am-eh"s to reply

"Arjen" <bo*****@hotmai l.com> wrote in message news:bv******** **@news1.tilbu1 .nb.home.nl...
Hi there,

I have tried to run your sample without succes.
So I have made a new sample. Maybe you can fix the serialization?

[...]

Nov 15 '05 #6

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

Similar topics

0
1619
by: HakonB | last post by:
Hi all I get an exception when trying to deserialize a simple configuration file using XML Serialization. The very long stacktrace can be seen at the bottom of this message. I've see other messages related a similar error but none of the solutions suggested are valid in case :/ I have tracked the problem down to the compilation of the temporary DLL that handles the actual serialization. The following commandline (that is one single...
6
2717
by: Uttam | last post by:
Hello, We are at a very crucial decision making stage to select between .Net and Java. Our requirement is to download a class at runtime on the client computer and execute it using remoting or rmi. Just to keep my question short I am posting trimmed version of my code. //file: Serializable.cs
4
5611
by: AndrewDotHay | last post by:
Periodically, we see an ASPX page fail with this appearing in the logs. Any ideas? It happens about every 3 to 4 hours, requiring a restart of the application domain to resolve it. Is this a COM Interop memory leak of the serialization code? It works great for a while and then crashes. Only thing close to this document thus far is KB #306158, but my issue is just an ASPX page calling some biz logic that uses the Xml.Serialization namespaces....
2
2540
by: Luck | last post by:
Hi, I really need some expert help... please! Basically, I need to serialize a data structure object to a file using SOAP and then load and de-serialize that file in ANOTHER program. When I serialize / deserialize the object in the SAME application, it works fine but when I simply copy the identical code to another application and try deserialization from that second application, I get the error: An unhandled exception of type...
3
15100
by: Paulo Morgado [MVP] | last post by:
Hi all ..NET Framework 1.1 I have created several types that are serailized to XML as strings. Someting like this: public struct MyInt32 : IXmlSerializable { int value;
5
6030
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 assembly 3- I am trying to deserialize from an EXE that references version 2.0 of the assembly 4- Both version 1.0 and 2.0 of the assembly reside in the GAC (no policy redirects exist).
0
1203
by: nobin01 | last post by:
Dear sir; I want ur Help in serialization.I know serialization.I Know binary,soap and xmlserialization also.But i want ur help in following topics.pls help me as soon as possible.I have search in site but only basics serialization is there. Topics: 1) serialize a nested object in mutiple files by maintaining the relation on parent level. ie, let say object1 containts object2 and object2 contains object3 , while serializing the object1,...
5
6117
by: Nikola Skoric | last post by:
I ran in Mono a program developed on .NET Framework 2.0 and it ran OK until I tried to desirialize a object. There the program died abruptly dumping this: System.ArgumentOutOfRangeException: Value -8590321990885400808 is outside the valid range . Parameter name: ticks at System.DateTime..ctor (Int64 ticks) at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadPrimitiv
9
1255
by: =?Utf-8?B?SmVzcGVyLCBEZW5tYXJr?= | last post by:
Hi, Just before I invent my own solution... :-) I'm developing a program where I use binary serialization of the data the program holds. Know and then the serialized objecst will be modified, e.g. with a new field, or perhaps the removal of a field. Depending on the changes, the program will not be able to deserialize the stored data. Is there any technique I can read about somewhere dealing with this issue.
2
1978
by: Mufasa | last post by:
I have a .Net 1.1 program that works fine that plays flash files. I am converting it to .Net 2.0 and am getting all kinds of compilation errors about not finding files or assemblies. Here's the error message in the design view of the window. Could not load file or assembly 'Interop.WMPLib, Version=1.0.0.0,
0
9345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10115
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9905
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
9775
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
8780
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
6609
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
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3881
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

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.