views:

36

answers:

2

Hi, I am trying to serialize a hash table using the link

XML serialization of hash table(C#3.0)

But I am receiving the error as

Type 'WpfApplication3.MyHashtable' with data contract name 'AllMyHashtable:http://schemas.datacontract.org/2004/07/WpfApplication3' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

My program is as under

namespace WpfApplication3
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MyHashtable ht = new MyHashtable();

            DateTime dt = DateTime.Now;
            for (int i = 0; i < 10; i++)
                ht.Add(dt.AddDays(i), i);
            SerializeToXmlAsFile(typeof(Hashtable), ht); 
        }

        private void SerializeToXmlAsFile(Type targetType, Object targetObject)
        {
            try
            {
                string fileName = @"C:\output.xml";
                DataContractSerializer s = new DataContractSerializer(targetType);
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.IndentChars = ("    ");
                using (XmlWriter w = XmlWriter.Create(fileName, settings))
                {
                    s.WriteObject(w, targetObject);
                    w.Flush();
                }
            }
            catch (Exception ex) { throw ex; }
        }
    }

    [CollectionDataContract(Name = "AllMyHashtable", ItemName = "MyEntry",
                         KeyName = "MyDate", ValueName = "MyValue")] 

    public class MyHashtable : Dictionary<DateTime, int> { }


}

What wrong is hapenning ..please help.

Thanks

A: 

I have not tried to run the code my selft, but it looks like an error in the original post:

       SerializeToXmlAsFile(typeof(Hashtable), ht);  

How can the above line work? ht is of type MyHashtable.

Shiraz Bhaiji
+2  A: 

The reason why you are getting the error you getting is because in the line:

SerializeToXmlAsFile(typeof(Hashtable), ht); 

in your button1_Click method you are passing the type Hashtable. The DataContractSerializer constructor initializes itself to serialize an object of the Type you indicated, in this case Hashtable. Consequently when you pass it an object of type MyHashtable when you call

s.WriteObject(w, targetObject);

it doesn't know how to process it. All that you need to do to make this work is change the line to:

SerializeToXmlAsFile(typeof(MyHashtable), ht);
Steve Ellinger