Tuesday 21 August 2007

Passing NameValueCollection to WebService

There might be a need to pass in a NameValueCollection class object into a webService. Since you can only pass in serialized objects into a web service it is not a straight forward process. One of the ways to do it is to have a Class that stores the name value pair and add it to an arraylist object. Then pass the arraylist.ToArray() object to the webservice. The other way is to use a string array. I have shown the code to do it using a string array below.

This is the method that takes in a NameValueCollection and returns an Array
///
/// This Method converts the NameValueCollection of all the parameters
/// into an arraylist of string arrays
///

///
///
private Array ConvertNameValueCollectionIntoArrayList(NameValueCollection nvcParams)
{
ArrayList aList = new ArrayList();
string[] strNameValue;

IEnumerator paramsEnum = nvcParams.GetEnumerator();

int i = 0;
while (paramsEnum.MoveNext())
{
string name = nvcParams.GetKey(i);
string value = nvcParams[name];

strNameValue = new string[2];
strNameValue[0] = name;
strNameValue[1] = value;

aList.Add(strNameValue);
i++;
}
return aList.ToArray();
}

Now this Array can be passed into the web service and de-decoded as shown below..

------WebService----

//The ArrayListObject below is the array that contains the arraylist
[WebMethod]
[XmlInclude(typeof(string[]))] //This line is very important
public void Initiate(Object[] ArrayListObject, string .....)
{
ArrayList al = new ArrayList(ArrayListObject); ParameterValue[] Params = ConvertNameValueCollectionIntoParams(al);
..
..}

private ParameterValue[] ConvertNameValueCollectionIntoParams(ArrayList nvp)
{
ParameterValue[] parameters = new ParameterValue[nvp.Count];
for (int i = 0; i < nvp.Count; i++)
{
ParameterValue parameter = new ParameterValue();
string[] strNameValuePair = (string[])nvp[i];
parameter.Name = strNameValuePair[0];
parameter.Value = strNameValuePair[1];
parameters[i] = parameter;
}
return parameters;
}

No comments: