Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>'
like image 311
DJGray Avatar asked Apr 24 '13 20:04

DJGray


2 Answers

You can do that by using Cast:

IDictionary<string, string> dict = ListParams.Cast<string>()
    .ToDictionary(p => p, p => ListParams[p]);
like image 87
mattytommo Avatar answered Oct 13 '22 18:10

mattytommo


You can also "convert" a NameValueCollection to Dictionary<string, string> by going through its AllKeys property:

var dictionary = nameValueCollection.AllKeys
    .ToDictionary(k => k, k => nameValueCollection[k]);
like image 34
Matt Borja Avatar answered Oct 13 '22 18:10

Matt Borja