Friday, June 01, 2007

The type System.Collections.Hashtable is not supported because it implements IDictionary.

When you will work with webservices and want to
1. Send an object that implements IDirectory Interface
2. Receive an object that Implement IDirectory Interface

most commonly used object from this category is HashTable.

so if a hashtable is passed to or returned froma a webmethod, we get a very specific error.
"The type System.Collections.Hashtable is not supported because it implements IDictionary."

this is because "IDictionary cannot be serialized via XML".

here is very interesting fact from MS guy (Dare Obasanjo,Microsoft Corporation,January 23, 2003)

Q: Why can't I serialize hashtables?
A: The XmlSerializer cannot process classes implementing the IDictionary interface.
This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a
counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not
implement the IDictionary interface.
(http://msdn2.microsoft.com/en-us/library/ms950721.aspx)

there are many possible solutions out of them here are two :

1. Convert this object into Jagged Arrays.
2. Implement a custom object which behave like wrapper to this hashtable (remember it must not expose this hashtable publicily).


1. Jagged arrrays :-
A Jagged arrray is nothing but arrays of arrays (any type) OR
A jagged array is a single dimensional array of arrays. The elements of a jagged array can be of different dimensions and sizes. It’s better to use jagged arrays instead of multidimensional arrays to benefit from MSIL performance optimizations. MSIL has specific instructions that target single dimensional zero-based arrays and even access to this type of array is optimized

EX. int[][] intJagged;
Or object [][]objHashTable
Or T[][] CustomTypeArray

There are two possibilites,
if your data contains one level of information means value field of hashtable contains premitive datatype values you can use
any of premitive type of jagged array.
object [][]objHashTable

and if it of custom type them use
T [][] objCustom
Note : this schenerio is not tested please verify it before use.

2. Custom object :-
In my case this hashtable was containing DataObject of a type which was subtype of for another DataObject means there was one to many relation
so i implemented it like this

subTypeDO
{
attributes ;
}

superTypeDO
{
attributes;
List objSubTypeDO;
}

remember in this case subTypeDO is a fat Data object (other wise jagged arrays are perfect)

Another use of collections in .net .


Try which one works for you, may be u`ll find some other way, second one worked for me.

Thanks

1 comment:

Apurva Kunkulol said...

I created an object Like "{'DocID':'123'}" (in JS) but still this error was thrown.