473,385 Members | 1,973 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,385 software developers and data experts.

Serialization and hashtable

Hello group! :)

I want to create a config/status object, that will contain a Hashtable. This
object I would like to save through Serialization, but im having some
trouble. My hashtable contain some objects, from a class I created myself.

I read that I need to make my own "add" method, which I hopefully did
correct. I hope someone can spot my wrongdoings, and point me in the right
direction. The code is in the bottom of this post:

Thanks :)

---ooo---

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace MyTest
{
/// <summary>
/// Have all configuration options in it
/// </summary>
[Serializable]
public class Config
{
public Groups groups = new Groups();

public Config()
{
Serialize();
Deserialize();
}

private void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
groups.Add(new Groups.Group("test1"));
groups.Add(new Groups.Group("test2"));
groups.Add(new Groups.Group("test3"));

// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream(@"C:\DataFile.dat", FileMode.Create);

// Construct a BinaryFormatter and use it to serialize the data to the
stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, groups);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
private void Deserialize()
{
// Declare the groups reference.
groups = null;

// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream(@"C:\DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
groups = (Groups) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}

// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (DictionaryEntry de in groups)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
}
}

public class Groups : Hashtable
{
public virtual void Add(Group group)
{
//forward our Add method on to the standard hashtable add method
base.Add(group.getKey(),group);
}

//this is the indexer (readonly)
public virtual new Group this[object key]
{
get
{
//return the Group at IList[Index]
return (Group)base[key];
}
}
public class Group
{
string key;

public Group(string arg)
{
key = arg;
}
public string getKey()
{
return key;
}
}
}
}
}
Nov 15 '05 #1
3 3963
If you want to create a config/status object, why you don't use an
XmlDocument?

"Cederstrom" <lasse#Remove#@*This*cederstrom.dk> schrieb im Newsbeitrag
news:%2****************@TK2MSFTNGP10.phx.gbl...
Hello group! :)

I want to create a config/status object, that will contain a Hashtable. This object I would like to save through Serialization, but im having some
trouble. My hashtable contain some objects, from a class I created myself.

I read that I need to make my own "add" method, which I hopefully did
correct. I hope someone can spot my wrongdoings, and point me in the right
direction. The code is in the bottom of this post:

Thanks :)

---ooo---

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace MyTest
{
/// <summary>
/// Have all configuration options in it
/// </summary>
[Serializable]
public class Config
{
public Groups groups = new Groups();

public Config()
{
Serialize();
Deserialize();
}

private void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
groups.Add(new Groups.Group("test1"));
groups.Add(new Groups.Group("test2"));
groups.Add(new Groups.Group("test3"));

// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream(@"C:\DataFile.dat", FileMode.Create);

// Construct a BinaryFormatter and use it to serialize the data to the
stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, groups);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
private void Deserialize()
{
// Declare the groups reference.
groups = null;

// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream(@"C:\DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
groups = (Groups) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}

// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (DictionaryEntry de in groups)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
}
}

public class Groups : Hashtable
{
public virtual void Add(Group group)
{
//forward our Add method on to the standard hashtable add method
base.Add(group.getKey(),group);
}

//this is the indexer (readonly)
public virtual new Group this[object key]
{
get
{
//return the Group at IList[Index]
return (Group)base[key];
}
}
public class Group
{
string key;

public Group(string arg)
{
key = arg;
}
public string getKey()
{
return key;
}
}
}
}
}

Nov 15 '05 #2
> If you want to create a config/status object, why you don't use an
XmlDocument?


Because it would be alot easier to just serialize a hashtable/object, and
deserialize it when I need to load the data.

Unless im missing something about XmlDocument's ?

Nov 15 '05 #3
Config files usually have only string and number, not objects.

We use XmlDocuments as config file to run some applications, it has many
advantages:
-you can edit it with a text editor
-you can add and remove data without problem
-you can build also very complex struct
-very easy to parse, also with complex struct
-XmlDocument has Save and Load methods so that everything become simpler

If I had to save an object with the configuration,
I would save the object in a directory and add the path to the config file

I'm not sure but I think you can also serialize an object to xml,
in that case you can also add it to the xml config file

"Cederstrom" <lasse#Remove#@*This*cederstrom.dk> schrieb im Newsbeitrag
news:%2***************@TK2MSFTNGP11.phx.gbl...
If you want to create a config/status object, why you don't use an
XmlDocument?


Because it would be alot easier to just serialize a hashtable/object, and
deserialize it when I need to load the data.

Unless im missing something about XmlDocument's ?

Nov 15 '05 #4

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

Similar topics

5
by: Arjen | last post by:
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...
3
by: Arjen | last post by:
Hi there, I have tried to run some samples without succes. So I have made a new sample. Maybe someone can fix the serialization? The class "MyProgram" must be saved to an xml file and placed...
1
by: francois | last post by:
Hi, I have a webservice that I am using and I would like it to return an XML serialized version of an object. the class of the object is defined serializable as the following: public...
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...
1
by: oDDskOOL | last post by:
I realized today that the Hashtable.Clone only produces a shallow copy... that makes me go mad that M$ doesn't even provide a deep copy ctor for the Hashtable class ! mighty tech ducks might...
2
by: Brian Keating | last post by:
hi there, has anyone had success in serializing a 2.0 case sensivite hashtable ie. private Hashtable m_itemsById = new Hashtable( new CaseInsensitiveHashCodeProvider(), new...
3
by: Wild Wind | last post by:
Hello, I've been battling over this problem for the better part of a day, so I'd appreciate it if someone could shed some light here. I have a file which is produced by the custom binary...
7
by: Joe | last post by:
I've tracked the performance issue down to a single class. This class derives from CollectionBase and stores a basic value type such as string, int, double, etc... I also store the type itself...
2
by: Ron M. Newman | last post by:
Hi, I have a simple class that has a Hashtable. the hashtable has a couple of key/value pairs where the key is a string and the value is also a strong. I have at the top of that class. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
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
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...
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...

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.