Postdata formatting - c#

I have a quick question about the formatting of postData in c#. Below is what I believe to be the post data extracted from google chrome. The data is related to creating an email. If anyone has any advice or spots any errors that would be really helpful. Thanks in advance
The Post Data
/reg_json?GivenName=findmeeasy&FamilyName=notebook&AccountID=#yahoo.com&PartnerName=yahoo_default&ApiName=ValidateFields&RequestVersion=1&intl=us&u=r333.member.bf1.yahoo.com56a54898077dc5.76327249&t=omaWrw2j1XMYYqsuNAvhoksAu08PTvyAF.VLF5WV3CEDJjE1oXISM8YYtNCMH4jqCmeEiFNVFSEj9MUCaEI4XkBtmeyboO6R4H0SI2tgb1vIz0gsI_3fMFByGY9uDyBssJxV0IHFuNAH4vDMGF0aJrn9AOLwjvxvEjBnGAdd0a_O1K4EyNP6xBkP59d9htdyrvTfsWsjfxNOSEJ1Cz4I0ynjBX7jBtorMVaPeGNxPxOhkNhIeaRR1M7pwIqaN9JxS8Sz4dhVccpdLlwvct.a6PGX1fEWZnvPowfODogHPIdJ1wq3dcwa4r4uK7K.QMHdzJobys_bJwGdKBXjQx7VL6WA_0Xoe9wk3xXZ13hIaR0zaCnDvWINPyX4.40.cw59.W5So13znpBXX.B4ZiD89OByV7c_cc1gzmjPVSOOcBQVAFljk72gPqq5GNA_iWAMAgYSH0lMacvUQSOpc6XnVjshMJRqRwQncoYn7j83WmOximNzdAoOOH.C8yeF6v3uxJVhOS111OCd2N37WucRBTdMWDOSTzDCx53a7E9fCNn9p_4PUGKr07WPRj5.9svMxv.PrKg_bJdLnJI-~B&1453672621368 HTTP/1.1
My Attempt at formatting
StringBuilder postData = new StringBuilder();
postData.Append("/reg_json?GivenName=findmeeasy");
postData.Append("&FamilyName=notebook");
postData.Append("&AccountID=#yahoo.com");
postData.Append("&PartnerName=yahoo_default");
postData.Append("&ApiName=ValidateFields");
postData.Append("&RequestVersion=1");
postData.Append("&intl=us");
postData.Append("&u=r333.member.bf1.yahoo.com56a54898077dc5.76327249");
postData.Append("&t=omaWrw2j1XMYYqsuNAvhoksA.....");

You have to make sure that both the variable name and the data value are url escaped - which they look to be. But that may be a co-incidence.
I'd do something like this
using System;
private static string MakeData(string name, string value)
{
return Uri.Escape(name) + "=" + Uri.Escape(value);
}
...
postData.Append("/reg_json?" + MakeData("GivenName", "findmeeasy"));
postData.Append("&" + MakeData("FamilyName", "notebook"));
/// etc.

Related

HTTP POST read response as regular string

I am currently doing a API HTTP POST project.
I should be getting
"[{\"ID\":\"311d1977-4772-435a-92aa-028791c53154\",\"ParentID\":\"187a064e-ffea-45a2-9264-9acecff911e1\",\"Type\":\"txt\",\"OwnerID\":\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\",\"Name\":\"Davinshi.txt\",\"CreatedBy\":\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\",\"CreatedDate\":\"2015-06-05T04:11:33.187\",\"Status\":0,\"Mark\":null},{\"ID\":\"25c80f4e-679c-4093-ade9-0b99da480153\",\"ParentID\":\"187a064e-ffea-45a2-9264-9acecff911e1\",\"Type\":\"jpg\",\"OwnerID\":\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\",\"Name\":\"leonid afremov.jpg\",\"CreatedBy\":\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\",\"CreatedDate\":\"2015-06-05T04:11:46.61\",\"Status\":0,\"Mark\":null}
However with the follow code I am getting a weird output
using (var client = new WebClient())
{
var val = new NameValueCollection();
foreach (var item in values)
{
val.Add(item.Key, item.Value);
}
var response = client.UploadValues(url, val);
return Encoding.Default.GetString(response);
}
This is the output
\"[{\\\"ID\\\":\\\"311d1977-4772-435a-92aa-028791c53154\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Davinshi.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:33.187\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"25c80f4e-679c-4093-ade9-0b99da480153\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"leonid afremov.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:46.61\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"5648cc67-1408-4935-a656-0f9b5116db8d\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"misty mood leonid.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:49.437\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"7402e7b8-1ec4-4bf8-9042-142a69cecbcd\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"winter sparkle.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:12:03.26\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"7159e926-1601-41d6-8dce-20e5daab90a6\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"gentle rain beata sasik.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:40.6\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"e61f7bc4-bebf-403b-a478-22b36856a6df\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"MoonLight.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:50.797\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"e46e6250-655b-4105-a888-2574750f2944\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"blue fire.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:27.037\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"bfca703b-1720-4a67-b0a4-2f6146c820aa\\\",\\\"ParentID\\\":null,\\\"Type\\\":\\\"folder\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"School\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:17.96\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"5c1bf9ca-b368-46c8-9804-3254eda00806\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Woman.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:12:06.607\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"8ad07f3c-7a57-4add-92c0-329aca372c8b\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"intimacy worship.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:40.727\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"ac5384c4-66ca-45cd-99f0-437c0789a26a\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Under the Rain.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:12:01.007\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"aa731f04-cc4e-4349-9268-4476ff04b473\\\",\\\"ParentID\\\":\\\"bfca703b-1720-4a67-b0a4-2f6146c820aa\\\",\\\"Type\\\":\\\"folder\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Marsiling Secondary School\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:20.983\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"af650810-0538-432e-8bf3-47429eb17d27\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"finger paintings.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:35.65\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"ddac31de-2b67-4f56-aefd-508a8f49926f\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"My Love.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:56.55\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"f2454474-d834-4bd1-992e-548cdc2734c1\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"boat.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:28.813\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"e1f5be01-29c7-4ca9-ae6f-5ddf8638cc67\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Davinshi.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:34.687\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"ff3a7365-7b4e-4a46-b545-6a2f889ff898\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"landscape paintings.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:44.48\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"327bf043-1e88-4265-ba5e-6de8394a0d84\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"lord rama.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:47.753\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"1d8a01de-da06-466d-8b7d-6e0bb8478d5e\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"intimacy worship.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:41.617\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"f23103ec-0d8c-407b-9f20-719f0577c274\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Coast of Sicily.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:32.187\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"374779d5-16e9-417f-808f-87fcf85035b0\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"misty mood leonid.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:54.203\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"f0bb2dc7-eac3-407d-a85a-886aaf161fc2\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"boat.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:28.907\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"607ee7b8-7287-4f3f-9867-8a8069562d3c\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"jpg\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Ballet.jpg\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:24.167\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"246b349e-ab32-407a-90ff-8df18bbabc68\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"Ballet.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:23.917\\\",\\\"Status\\\":0,\\\"Mark\\\":null},{\\\"ID\\\":\\\"457d722f-a675-4523-bd83-8f309dcd254e\\\",\\\"ParentID\\\":\\\"187a064e-ffea-45a2-9264-9acecff911e1\\\",\\\"Type\\\":\\\"txt\\\",\\\"OwnerID\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"Name\\\":\\\"finger paintings.txt\\\",\\\"CreatedBy\\\":\\\"5bd087f0-070d-48bd-98b4-10ffa4b3b792\\\",\\\"CreatedDate\\\":\\\"2015-06-05T04:11:39.017\\\",\\\"Status\\\":0,\\\
Which I think the HTTP POST Response is reading the string as a verbatim string.
Any idea how can i fix it ?
Thanks !
When I run your code, the output of Encoding.Default.GetString(response) is exactly the string you posted at the top of your question.
The excessively backslash-escaped string appears in the Visual Studio debugging window simply because VS escapes special characters when displaying a string, but if you try to save this string into a file or use it in any other way in your code, you will see that only the double quote marks are escaped, like the string at the top of your question.
I found out that the API will automatically convert the object to json format.
The problem occur when I try to serialize the object before sending trough the API.Hence, like what Denis Yarkovoy said. It's double serialized.

Value cannot be null. Parameter name: String

Please take a look at the following code. It's in handler.asxh.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
new RequestManagementFacade().PinRequest(Int32.Parse(context.Request.QueryString["requestId"]), (Boolean.Parse(context.Request.QueryString["isPinned"])));
}
This is showing the following error:
Value cannot be null. Parameter name: String
There is value being passed as I have checked the context request query string, however, the code breaks at this stage.
This handler will connect to the business logic layer.
There is value being passed as i have checke dthe context request query string
I strongly suspect your diagnostics are incorrect then. Values don't magically go missing - you need to question your assumptions. This is easy to debug through though. I would suggest changing your code to:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
string requestId = context.Request.QueryString["requestId"];
string isPinned = context.Request.QueryString["isPinned"];
var facade = new RequestManagementFacade();
facade.PinRequest(Int32.Parse(requestId), Boolean.Parse(isPinned));
}
It's then really simple to step through and find out what's going on.
It is likely that either context.Request.QueryString["requestId"] or context.Request.QueryString["isPinned"] is not returning a valid string value. Check that both values are passed in the query string with the proper IDs, those being of course requestId and isPinned.
Okay solved when passing the values to the handler i inserted it as
"PinRequest.ashx?="+requestId+isPinned"
Which gave me the result 2True
So i realised the hiccup was with not including the string names
"PinRequest.ashx?requestId=" + this._requestId + "&isPinned=" + this._isPinned
Thanks for you help guys
LeviBotelho Thank you made me check something i was missing out when checking as its javascript
experienced the error while using Int32.Parse(myString) to convert string to int and afterwards assign the value to an object's attribute. Using another method for converting(Convert.ToInt32(myString)) string to int worked for me.

Using Webclient to POST/select all the option Values of a Multiselect

I am trying to write an application to automate router configuration. Unfortunately with the router we are using, telnet is not an option.
So I have had to interface with the Cisco web interface using C# WebClient class.
Up until now I had been able to set everything I needed using NameValueCollection and WebClient.UploadValues.
I would take all the input elements on the form, then just upload the name value Collection corresponding to the input types on the form, setting the values of each to the desired setting.
But now I have run into a problem.
With one of the forms, it is using a multiselect control to handle an array of input data, not an input type.
I am at a total loss for how to set this.
The html for the multiselect is as follows
<select multiple class="MultiSelect" name="PortRangeList" size="12" onChange="showList(this.form.PortRangeList);" style="width: 100%">
<option value="All Traffic{[(*-*-*)]}1;0;1;65535;0}">All Traffic [TCP&UDP/1~65535]</option>
<option value="DNS{[(*-*-*)]}2;17;53;53;0}">DNS [UDP/53~53]</option>
<option value="FTP{[(*-*-*)]}3;6;21;21;0}">FTP [TCP/21~21]</option>
...
</select>
When I was using the input types, I would simply do the following
NameValueCollection formNetworkData = new NameValueCollection();
formNetworkData["ipAddr"] = "192.168.1.2";
formNetworkData["lanMask"] = "255.255.255.0";
downloadedData = _routerWebClient.UploadValues(_routerIP + NETWORK, formNetworkData);
But looking at the code for this new form, it appears right before it submits, it selects all the options in the multiselect.
I realize I have probably asked this question poorely, but any assistance would be greatly appreciated.
Using Chrome debugger PortRangeList is exactly as you said.
There are 5 input types
submitStatus, upnpOpen (etc...)
For those my code looks like this
NameValueCollection formData = new NameValueCollection();
formData["submitStatus"]="1";
formData["upnpOpen"]="0";
downloadedData = _routerWebClient.UploadValues(SERVICE0, formData);
But in order to submit the PortRangeList data, I can't use the NameValueCollection because it does not allow a name to have muliple values.
how could submit that?
WebClient.UploadData, WebClient.UploadFile or WebClient.UploadString maybe?
Use Fiddler or Wireshark to compare what goes over the wire when it works ("normal" browser) and when it doesn't work (your code)... once you know the differences you can change your code accordingly...
You have to pass in the selected options by passing in the "PortRangeList" parameter multiple times, once for each option:
PortRangeList=All Traffic{[(*-*-*)]}1;0;1;65535;0}&PortRangeList=DNS{[(*-*-*)]}2;17;53;53;0}&PortRangeList=FTP{[(*-*-*)]}3;6;21;21;0}
That's how browsers do it. Since you're using the WebClient, try this:
PortRangeList=All Traffic{[(*-*-*)]}1;0;1;65535;0},DNS{[(*-*-*)]}2;17;53;53;0},FTP{[(*-*-*)]}3;6;21;21;0}
Obviously, everything has to be properly URL-escaped.
Thought I would post the final answer.
In the end I used the exact solution shown here.
http://anhonga.wordpress.com/2010/05/06/using-webclient-with-uploadvalues-and-uploadstring-to-simulate-post/
This is with his code, but I did essentially the exact same thing (without using global variables)
StringBuilder _strBld = new StringBuilder();
int _intItemCount = 0;
protected void btnSubmit_Click(object sender, EventArgs e)
{
System.Net.WebClient myWebClient = new System.Net.WebClient();
myWebClient.Headers.Add("Charset", "text/html; charset=UTF-8");
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); // ◄ This line is essential
// Perform server-side validations (same as before)
if (this.F_Name.Text.Length == 0 || this.L_Name.Text.Length == 0)
{ AppendError("First and Last name must be provided"); }
…
// Add the user-provided name values
AppendUploadString("last_name", this.L_Name.Text);
AppendUploadString ("first_name", this.F_Name.Text);
AppendUploadString ("address", this.Address.Text);
// Add the Toppings
foreach (ListItem item in this.ToppingsChkBoxList.Items)
{
if (item.Selected)
{
AppendUploadString("Toppings", item.Value.ToString());
}
}
myWebClient.UploadString("https http://www.Destination.com/...?encoding=UTF-8", "POST", _strBld.ToString());
}
private void AppendUploadString(string strName, string strValue)
{
_intItemCount++;
_strBld.Append((intItemCount == 1 ? "" : "&") + strName + "=" + System.Web.HttpUtility.UrlEncode(strValue));
// Update: Use UrlEncode to ensure that the special characters are included in the submission
}

remove html tags or script tags in c# string and also in client using javascript

I need to do a user input validation, and I want it validated both in the client side and in the server side.
I have ang textbox that the user can write his comment on the product, now what I wanted to do is to validate if his comment doesn't have any injections like html or javascripts. So what I wanted to do, after the user clicks on submit
1.) Client Side: How will I execute a validation like if the user inputs this kinds of string
abcd // I will accept only abcd and remove the anchor tag but the abcd should appear as a link
<script type="text/javascript">alert(123);</script> // I will accept only alert(123);as the valid string
<b>abcd</b> // I will display abcd but it must appear bold
2.) Server side: Same situation with the client side, I will remove the tags of the injected script and html tags.
I am using sharepoint 2007, I'm not sure if there is a built-in function to do this kind of validation in sharepoint api or c# for the server side validation.
Note: I don't want to use RegEx for this or any third party software. I know many experts here can help me with this. Thank you so much!
While RegEx is probably your best bet, you can use this and modify to your liking:
public static string StripHtml(this string source)
{
string[] removeElements = new string[] { "a", "script" };
string _newString = source;
foreach (string removeElement in removeElements)
{
while (_newString.ToLower().Contains("<" + removeElement.ToLower()))
{
_newString = _newString.Substring(0, _newString.ToLower().IndexOf("<" + removeElement.ToLower())) + _newString.Substring(_newString.ToLower().IndexOf("</" + removeElement.ToLower() + ">") + removeElement.Length + 3);
}
}
return _newString;
}
You'll use string clean = txtInput.Text.StripHtml();
I am not sure about creating an validation for this. But you can programtically remove the tags using this function.
Use this function to remove the Html tage from the textbox value that user has input
public static string StripHtml(string html, bool allowHarmlessTags)
{
if (html == null || html == string.Empty)
return string.Empty;
if (allowHarmlessTags)
return System.Text.RegularExpressions.Regex.Replace(html, "", string.Empty);
return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty);
}
If you want prevent javascript injection attacks just encode user input Server.HtmlEncode(message).
But if you need to clean some tags then Omar Al Zabir wrote good article Convert HTML to XHTML and Clean Unnecessary Tags and Attributes
// Encode the string input
StringBuilder sb = new StringBuilder(
HttpUtility.HtmlEncode(htmlInputTxt.Text));
// Selectively allow <b> and <i>
sb.Replace("<b>", "<b>");
sb.Replace("</b>", "");
sb.Replace("<i>", "<i>");
sb.Replace("</i>", "");
Response.Write(sb.ToString());
I also would like to recomand you check AntiSamy.NET project but I didn't try it by myself.

ASP.NET Payment Form Submission Need Guidance

Guys, I apologize me if the question is less organized and less clear. I am in hurry :(
My web app has payment form that need to be submitted to another ASP.NET page (lets call it http://vendor.com/getpay.aspx)
residing on another server.
That page will do some mumbo-jumbo works and then redirects it to the acutal
payment gateway site.
when i post my payment form to getpay.aspx via simple HTML form, it works and redirects fine.
if i change the form and its hidden inputs to server side controls, it doesn't work. their page is throwing viewstate exception.
I need the form hidden inputs to be server controls so that i can bind some values generated by my code behind.(i think i can do this like the classic asp way using <%= %>, but it is like going back in standard!)
I tried HttpWebRequest in the code behind, it posts the form but the browser doesn't redirect to Payment Gateway page.
I am posting the payment info over non https, how can i prevent the user tampering with the posted data?.
I want to validate the payment form in the backend then post it, i couldn't trust the user input data.
Also the result was returned to my redirect page with query strings appended. It is also happening over the non https.
how much i can trust this redirect data?
Thx much
Generate your form by clearing the Response and rewriting the html HTTP form out into the cleared response. When I get home I will trawl through my old code and provide an example.
EDIT:
OK here is my code, I had to recreate because I am still at work but it goes a little like this:
Create an intermediate page to capture your variables from the ASPX page and then use this to send as a 'simple' form:
protected void Page_Load(object sender, EventArgs e)
{
// Capture the post to this page
IDictionary<string, string> variables = new Dictionary<string, string>();
variables.Add("test", Request.Form["test"]); // collect all variables after checking they exist
RewriteContent(variable);
}
public void RewriteContent(IDictionary<string, string> variables)
{
string formContent = #"
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action='' method=''>";
foreach (KeyValuePair<string, string> keyVal in variables)
{
formContent += #"<input type='" + keyVal.Key + "' value='" + keyVal.Value + "' />";
}
formContent += #"
</form>
</body>
</html>"; // Add either an auto post in a javascript or an explicit submit button
Response.Clear();
Response.Write(formContent);
Response.Flush();
Response.End();
}
EDIT 2:
Sorry I just realised I have not answered the other questions.
Q3/Q4/Q5. If you are not using https you cannot really stop tampering or be sure the response is correct but you can restrict the chance it is bogus. This can be achieved by hashing the values with a secret that is shared at your end and the destination, and then when you get the response you should hash the values and compare to the hash that is sent back to you before you accept that it is valid.
Most payment mechanisms are verified in this manner usually with an MD5 or SHA1 hash you can find more info on the following links:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx
http://www.developerfusion.com/code/4601/create-hashes-md5-sha1-sha256-sha384-sha512/
http://snippets.dzone.com/posts/show/5816
EDIT 3:
Doing some encryption now and thought I would share some code with you (because I am nice like that). Might give you an idea of what to do and you can probably code better than me so just tidy up my mess a bit :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using log4net;
namespace MyCompany.Cipher
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string GenerateSha1HashForString(string valueToHash, EncodeStyle encodeStyle)
{
string hashedString = string.Empty;
try
{
hashedString = SHA1HashEncode(Encoding.UTF8.GetBytes(valueToHash), encodeStyle);
}
catch (Exception ex)
{
if (log.IsErrorEnabled) { log.Error(string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace)); }
throw new Exception("Error trying to hash a string; information can be found in the error log", ex);
}
return hashedString;
}
private string ByteArrayToString(byte[] bytes, EncodeStyle encodeStyle)
{
StringBuilder output = new StringBuilder(bytes.Length);
if (EncodeStyle.Base64 == encodeStyle)
{
return Convert.ToBase64String(bytes);
}
for (int i = 0; i < bytes.Length; i++)
{
switch (encodeStyle)
{
case EncodeStyle.Dig:
//encode to decimal with 3 digits so 7 will be 007 (as range of 8 bit is 127 to -128)
output.Append(bytes[i].ToString("D3"));
break;
case EncodeStyle.Hex:
output.Append(bytes[i].ToString("X2"));
break;
}
}
return output.ToString();
}
private string SHA1HashEncode(byte[] valueToHash, EncodeStyle encode)
{
SHA1 a = new SHA1CryptoServiceProvider();
byte[] arr = new byte[60];
string hash = string.Empty;
arr = a.ComputeHash(valueToHash);
hash = ByteArrayToString(arr, encode);
return hash;
}
}
Put it in a class some where that your project can see and it can generate an SHA1 hash based on a string value by calling the public method.

Categories

Resources