Friday, April 10, 2009

Using Hashtable in WCF

Scenario:
I wanted to store some key value pair information in my DataMember. I thought of using Hashtable as DataMember, so far so good but when adding the service reference from my client application, I noticed that Hashtable got converted to Dictionary and while compiling I got the following error

Cannot implicitly convert type 'System.Collections.Generic.Dictionary' to 'System.Collections.Hashtable'

Workaround:
The representation of a Hashtable in the wire is equivalent to the representation of a dictionary. So it will just work if you use the Dictionary at the client side

Solution:
Right click the Service reference > Configure Service Reference > Select 'System.Collection.Hashtable' from Dictionary collection type drop down menu.

But i wanted to still use Hashtable, so this is how i did it.
Here's the code.

IService1.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

using System.Collections;

namespace TestWCF
{
[ServiceContract]
public interface IService1
{
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}

[DataContract]
public class CompositeType
{
private Hashtable doc;
[DataMember]
public Hashtable Doc
{
get { return doc; }
set { doc = value; }
}
}
}
Service1.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TestWCF
{
public class Service1 : IService1
{
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
composite.Doc = new Hashtable();
composite.Doc.Add("A","B");

return composite;
}
}
}
I created a Windows Form application to test the WCF service.
Form1.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestWCFClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
ServiceReference1.CompositeType composite = new ServiceReference1.CompositeType() ;
ServiceReference1.CompositeType composite2 = new ServiceReference1.CompositeType() ;

ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();
composite2 = sc.GetDataUsingDataContract(composite);
MessageBox.Show(composite2.Doc["A"].ToString());
}
}
}

1 comments:

Manuel Alejandro Garza EnrĂ­quez August 27, 2012 at 5:35 PM  

Thank you very much. My WCF function execute a Stored Procedure, I will like to add a HashTable for parameter(StoredProcedure Parameters) it's is very helpful.