DJGray DJGray - 6 days ago 6
ASP.NET (C#) Question

ASP.Net/C# convert NameValueCollection to IDictionary?

I’m trying to help my son upgrade a web site I built for him last year. He wants to implement Amazon Simple Pay. I’m SO close to getting it, but have an error that I don’t know how to address. It’s an ASP.Net site done in C#. I am an untrained (self-taught) developer, so speak in simple terms, please. ;-)

In ASP.Net, it is not legal to have a Form within a Form, and I need to do a Form POST. There is a pretty slick tutorial online that shows how to make this happen. The URL is http://weblogs.asp.net/hajan/archive/2011/04/20/amazon-simple-pay-in-asp-net.aspx if you’re interested in seeing it.

The transaction has to be “signed” and Amazon provides a SignatureUtils class to accomplish this. In that class, I’m calling this:

public static string signParameters(IDictionary<String, String> parameters, String key, String HttpMethod, String Host, String RequestURI, String algorithm)


What’s killing me is the IDictionary parameter. What I have to pass it is this ListParams NameValueCollection that I built with:

public System.Collections.Specialized.NameValueCollection ListParams = new System.Collections.Specialized.NameValueCollection();


It’s giving me the error below, because it can’t convert the NameValueCollection to an IDictionary. I tried explicitly converting it, but no joy. How can I solve this?

Error: Argument 1: cannot convert from 'System.Collections.Specialized.NameValueCollection' to 'System.Collections.Generic.IDictionary<string,string>'

Answer

Shazzam!! Got it! The solution was to change the sample code presented by Hajan to implement a Dictionary rather than a NameValueCollection. Then I needed to change is while loop in the PaymentGatewayPost to a foreach loop as follows:

foreach (KeyValuePair<string, string> pair in ListParams)
{
    System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">",
    pair.Key,
    pair.Value));
}

Voila!! It builds without error.

Thanks everyone for your help. Hopefully this will help others who are struggling with the Amazon Simple Pay.