I have made a post request with comma separated values. But my form contents changes and "," replace with "%2C". So request does not receive at server side.
I just want to replace "%2C" with ",".
I tried with different codes but that code are for string.
//Uri.EscapeDataString(formContent).Replace("%2C", ",");
Above line is for string but I need same for FormContent.
Here is my Code.
Windows.Web.Http.HttpClient clientOb = new Windows.Web.Http.HttpClient();
Uri connectionUrl = new Uri("http://www.helloworld.com/istar/fileupload/Lip?");
string framURL = UTCdatetime + "," + lng + "," + lat + "," + speed + alt + "," + "," + battery_level + "," + accuracy;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("name", Image_file_name);
pairs.Add("frame", framURL);
//Here is My Content Form.
Windows.Web.Http.HttpFormUrlEncodedContent formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
I'm getting FormContent encoded. like
{name=WP_20160224_002.jpg&frame=927858b101b71083f37549517819d6ac%2C20160225125928%2C%2C%2C%2C%2C%2C%2C100%2C%2C2%2C%2C%2C0}
I need to send request with Comma's so I want to remove "%2C". Please help out in this problem.
I Required above contentform like this...
{name=WP_20160224_002.jpg&frame=927858b101b71083f37549517819d6ac,20160225092908,74.253794,31.471193,-1,-1,0,,100,103,2,-1,0}
Here I send post request.
Windows.Web.Http.HttpResponseMessage response = await clientOb.PostAsync(connectionUrl, formContent);
You're confusing form encoding with URL encoding. Given your example, there's little need to encode this query string. Forms and query strings have a similar key=value syntax, but there are differences in format.
You're right to use the Uri class - but you can wait until the very end to construct it from a string, as this will ensure the given string is fully sanitized - see the remarks section of MSDN documentation of Uri class.
Here's an untested example:
string framURL = UTCdatetime + "," + lng + "," + lat + "," + speed + alt + "," + "," + battery_level + "," + accuracy;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("name", Image_file_name);
pairs.Add("frame", framURL);
var queryString = String.Join("&", pairs.Select(kvp => kvp.Key + "=" + kvp.Value));
Uri connectionUrl = new Uri("http://www.helloworld.com/istar/fileupload/Lip?" + queryString);
Let me know how you get on!
Related
I'm writing a weather app in Xamarin.Form. I am using the Yahoo API. I have no problem getting the weather by the city name parameter. However, when I change the code to use longitude and latitude, the weather does not appear.
To download the weather I use the example from the page: https://developer.yahoo.com/weather/documentation.html#oauth-csharp
I processed it in the following way:
lSign = string.Format(
"format={0}&" +
"lat={1}&" +
"lon={2}&" +
"oauth_consumer_key={3}&" +
"oauth_nonce={4}&" +
"oauth_signature_method={5}&" +
"oauth_timestamp={6}&" +
"oauth_version={7}&" +
"u={8}",
cFormat,
szerokosc,
dlugosc,
cConsumerKey,
lNonce,
cOAuthSignMethod,
lTimes,
cOAuthVersion,
jednostka.ToString().ToLower()
(...)
url = cURL + "?lat=" + szerokosc + "&lon=" + dlugosc + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
According to the documentation, lSign is used for authentication. It should not be changed, remove these "lat={1}&" + "lon={2}&" from that strings.
It says Please don't simply change value of any parameter without
re-sorting.
The location information should be involved in the request url and the authorization information is added in the header.
// Add Authorization
lClt.Headers.Add ( "Authorization", _get_auth () );
// The request URL
lURL = cURL + "?" + "lat=" + szerokosc + "&lon=" + dlugosc + "&format=" + cFormat;
Unfortunately, the simple removal of " lat = {1} & " + " lon = {2} & " from variable lSign does not solve the problem.
For example, to get weather data by the city name I use:
lSign = string.Format(
"format={0}&" +
"location={1}&" +
"oauth_consumer_key={2}&" +
"oauth_nonce={3}&" +
"oauth_signature_method={4}&" +
"oauth_timestamp={5}&" +
"oauth_version={6}&" +
"u={7}",
cFormat,
miasto,
cConsumerKey,
lNonce,
cOAuthSignMethod,
lTimes,
cOAuthVersion,
jednostka.ToString().ToLower()
and
url = cURL + "?location=" + Uri.EscapeDataString(miasto) + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
and
string headerString = _get_auth();
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/" + cFormat;
webClient.Headers[HttpRequestHeader.Authorization] = headerString;
webClient.Headers.Add("X-Yahoo-App-Id", cAppID);
byte[] reponse = webClient.DownloadData(url);
string lOut = Encoding.ASCII.GetString(reponse);
I have created an application. This app contains the five textboxes id, name, surname, age and score.
When a user clicks the "okay button", these values are stores in an sql database.
Additionally, I want to store all of these information in an QR code. And when I decode it, the information should be shown in the textboxes respectively.
These are the references I am using so far.
using AForge.Video.DirectShow;
using Zen.Barcode;
using ZXing.QrCode;
using ZXing;
I can encode an ID number into a picture box, like so:
CodeQrBarcodeDraw qrcode = BarcodeDrawFactory.CodeQr;
pictureBox1.Image = qrcode.Draw(textBox1.Text, 50);
But I want all of the values in the textboxes to be storee in this QR code.
How can i do that?
The essence of the solution is, that you have to combine all the values from the textboxes into one string. To seperate them after decoding the QR code, you have to add a special character between the data values, that does not exist insinde the user input. After decoding the QR code, you can seperate the values by splitting the string at each occurance of the special character.
This is the quick and dirty way of doing that. If you want the QR code to be conformant to any specific format (like vcard), you have to reserach what it takes to compose the data for this format.
I expect your users cannot enter more than one line into the textboxes, so the newline character can be used as seperator character.
Encode all the information into one QR code.
var qrText = textBox1.Text + "\n" +
textBox2.Text + "\n" +
textBox3.Text + "\n" +
textBox4.Text + "\n" +
textBox5.Text;
pictureBox1.Image = qrcode.Draw(qrText, 50);
You can decode the QR code and assigning the data to the different textboxes again.
var bitmap = new Bitmap(pictureBox1.Image);
var lumianceSsource = new BitmapLuminanceSource(bitmap);
var binBitmap = new BinaryBitmap(new HybridBinarizer(source));
var reader = new MultiFormatReader();
Result result = null;
try
{
result = reader.Decode(binBitmap);
}
catch (Exception err)
{
// Handle the exceptions, in a way that fits to your application.
}
var resultDataArray = result.Text.Split(new char[] {'\n'});
// Only if there were 5 linebreaks to split the result string, it was a valid QR code.
if (resultDataArray.length == 5)
{
textBox1.Text = resultDataArray[0];
textBox2.Text = resultDataArray[1];
textBox3.Text = resultDataArray[2];
textBox4.Text = resultDataArray[3];
textBox5.Text = resultDataArray[4];
}
You can get this done by implementing below code :
"{" + '"' + "name" + '"' + ":" + '"' + txtName.Text + '"' + "," + '"' + "lname" + '"' + ":" + '"' + txtLname.Text + '"' + "," + '"' + "Roll" + '"' + ":" + '"' + txtRoll.Text + '"' + '"' + "class" + '"' + ":" + '"' + txtClass.Text + '"' + "}"
Result will be:
{"name":"Diljit","lname":"Dosanjh","Roll","2071","class":"BCA"}
Such that your QR scanner will recognize the data belong to its specific filed.
i have a problem with a Web Post Form.
I have download the page, I extrapolated the two required values (form_build_id and form_token), but once sent the POST the server does not receive anything in POST.
Excluded errors:
Wrong link (can download the page).
Incorrect extrapolated data (verified).
Wrong string myParameters (verified).
I have tested the Form manually and it work fine.
Some idea? There I slam my head for two days!
using (WebClientEx wc = new WebClientEx())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HTMLPage = wc.DownloadString(CREAT_TICKET_URL);
string form_build_id = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_build_id\"", "value=\"", "\" />");
string form_token = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_token\"", "value=\"", "\" />");
string myParameters = "macchina=" + cmacExtID + "&utente=" + custExtID + "&oggetto=" + Title + "&body=" + Note + "&op=Conferma&form_build_id=" + form_build_id + "&form_token=" + form_token + "&form_id=app_form_new_ticket";
string HtmlResult = wc.UploadString(CREAT_TICKET_URL, myParameters);
}
Note: WebClientEx class inherits WebClient. I used this approach to other forms such as login and work.
The final question is: if this approach is wrong, what is the best way to do this sequence of operations "download the page, extract the values from the HTML, send post form"?
The problem was the header!
The header should be set for each call, while I thought it was enough to set only the first time.
using (WebClientEx wc = new WebClientEx())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HTMLPage = wc.DownloadString(CREAT_TICKET_URL);
string form_build_id = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_build_id\"", "value=\"", "\" />");
string form_token = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_token\"", "value=\"", "\" />");
string myParameters = "macchina=" + cmacExtID + "&utente=" + custExtID + "&oggetto=" + Title + "&body=" + Note + "&op=Conferma&form_build_id=" + form_build_id + "&form_token=" + form_token + "&form_id=app_form_new_ticket";
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(CREAT_TICKET_URL, myParameters);
}
I am trying to replace a hash char in a string but the following is not working the
string address = "Blk 344, Jurong West, Street 11, #02-111";
address.Replace("#","%23");
Any ideas guys been driving me crazy
Query String full
http://localhost:54965/SKATEZ/thankyou.aspx?firstname=Fiora&lastname=Ray&address=Blk%20344,%20Jurong%20West,%20Street%2011,%20#02-111&total=22&nirc=S6799954H&country=Singapore&orderid=85&postalcode=746112
I construct the url as follows
string url = "thankyou.aspx?firstname=" + firstname + "&" + "lastname=" + lastname + "&" + "address=" + HttpUtility.EscapeDataString(address) + "&" + "total=" + total + "&" + "nirc=" + tbID.Text + "&" + "country=" + ddlCountry.SelectedValue + "&" + "orderid=" + orderid + "&" + "postalcode=" + tbPostalCode.Text;
Response.Redirect(url);
Try
address = address.Replace("#","%23");
Strings in C# are immutable:
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.
Using System.Uri.EscapeDataString(string) should fix your issue:
var urlbuilder = new StringBuilder();
urlbuilder.AppendFormat("thankyou.aspx?firstname={0}", firstname);
urlbuilder.AppendFormat("&lastname={0}", lastname);
urlbuilder.AppendFormat("&address={0}", System.Uri.EscapeDataString(address));
urlbuilder.AppendFormat("&total={0}", total);
urlbuilder.AppendFormat("&nirc={0}", tbID.Text);
urlbuilder.AppendFormat("&country={0}", ddlCountry.SelectedValue);
urlbuilder.AppendFormat("&orderid={0}", orderid);
urlbuilder.AppendFormat("&postalcode={0}", tbPostalCode.Text);
Response.Redirect(urlbuilder.ToString());
(using System.Text.StringBuilder to compose your url makes the code a little more readable)
I am trying to consume stripe.com api with restsharp, using the charge command
https://stripe.com/docs/api/php#create_charge
there's an opportunity to pass metadata as key value pairs but I don't seem to succeed
const string baseUrl = "https://api.stripe.com/";
const string endPoint = "v1/charges";
var apiKey = this.SecretKey;
var client = new RestClient(baseUrl) { Authenticator = new HttpBasicAuthenticator(apiKey, "") };
var request = new RestRequest(endPoint, Method.POST);
request.AddParameter("card", token);
request.AddParameter("amount", wc.totalToPayForStripe);
request.AddParameter("currency", "eur");
request.AddParameter("description", wc.crt.cartid + " - " + wc.co.oid);
request.AddParameter("metadata", "{cartid: " + wc.crt.cartid + ", oid: " + wc.co.oid + "}");
request.AddParameter("statement_description", "# " + wc.crt.cartid);
request.AddParameter("description", wc.crt.cartid + " - " + wc.co.oid);
Always getting the following error:
Invalid metadata: metadata must be a set of key-value pairs
Clearly I don't pass the key value pair the way I should but I can't find any restsharp documentation on that.
Anyone can help?
Try this:
const string baseUrl = "https://api.stripe.com/";
const string endPoint = "v1/charges";
var apiKey = this.SecretKey;
var client = new RestClient(baseUrl) { Authenticator = new HttpBasicAuthenticator(apiKey, "") };
var request = new RestRequest(endPoint, Method.POST);
request.AddParameter("card", token);
request.AddParameter("amount", wc.totalToPayForStripe);
request.AddParameter("currency", "eur");
request.AddParameter("description", wc.crt.cartid + " - " + wc.co.oid);
request.AddParameter("metadata[cartid]", wc.crt.cartid);
request.AddParameter("metadata[oid]", wc.co.oid);
request.AddParameter("statement_description", "# " + wc.crt.cartid);
request.AddParameter("description", wc.crt.cartid + " - " + wc.co.oid);
For some reason HTTP Post requests can not accept key-value objects and must be sent in this type of format. This isn't a stripe restriction, but HTTP in general.
I think it's telling you to enter them as such:
request.AddParameter("metadata", "[ { cartid: " + wc.crt.cartid + "} ,{ oid: " + wc.co.oid + " }]" );