restsharp how to add key value pair as parameter - c#

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 + " }]" );

Related

Yahoo Weather API by Lat and Lon

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);

C# - Geocode pharmacy by name and location

How can I find the coordinates of a pharmacy by it name and location?
I'm trying to search with the Google geocode API like this:
var pharmacyName = "Farmácia Ereirense";
var address = "Cartaxo, Santarém";
var url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + pharmacyName + ", " + address + "&sensor=false";
but I only got ZERO_RESULTS on the GeoResponse Status, and if I google "Farmácia Ereirense, Cartaxo, Santarém" it found the right location...
I already tried to do:
var pharmacyName = "Farmácia Ereirense";
var address = "Cartaxo, Santarém";
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?name=" + pharmacyName + ", " + address + "&key=" + apiKey;
but I got the INVALID_REQUEST result.
Documentation I based on
Finally I found the solution! We can do a Text Search request like this:
var pharmacyName = "Farmácia Ereirense";
var address = "Cartaxo, Santarém";
var url = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + pharmacyName + ", " + address + "&key=" + apiKey;
And it works just fine, like Google's search.
Documentation

the request signature we calculated does not match the signature you provided aws

I want to cors upload my video file from browser to Amazon S3 storage via asp.net project. But I keep getting this error:"the request signature we calculated does not match the signature you provided"
Here is the javascript code I have;
function uploadFile() {
var access_key = "xx";
var secret = "xx";
var policy = "xx";
var signature = "xx";
var file = document.getElementById('file').files[0];
var fd = new FormData();
var key = "folder1/" + (new Date).getTime() + '-' + file.name;
fd.append('key', key);
fd.append('acl', 'public-read-write');
fd.append('Content-Type', file.type);
fd.append('AWSAccessKeyId', access_key);
fd.append('policy', policy)
fd.append('signature', signature);
fd.append("file", file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open('POST', 'https://bucketName.s3.amazonaws.com/', true);
xhr.send(fd);
}
Here is the policy string ;
{" +
"\"Id\": \"Policyxxx\"," +
"\"Version\": \"2012-10-17\"," +
"\"Statement\": [" +
"{" +
"\"Sid\": \"Stmtxxx\"," +
"\"Action\": \"s3:*\"," +
"\"Effect\": \"Allow\"," +
"\"Resource\": \"arn:aws:s3:::bucketName/*\"," +
"\"Principal\": \"*\"" +
"}" +
"]" +
"}
and here is the getsignature method;
public static string GetS3Signature(string policyStr)
{
string b64Policy = Convert.ToBase64String(Encoding.ASCII.GetBytes(policyStr));
byte[] b64Key = Encoding.ASCII.GetBytes(AwsSecretKey);
HMACSHA1 hmacSha1 = new HMACSHA1(b64Key);
var c = Convert.ToBase64String(hmacSha1.ComputeHash(Encoding.ASCII.GetBytes(b64Policy)));
return c;
}
What could be the reason for the error
Any conditions which are mentioned in the policy must also be in the form data. For example if you have a condition like
["starts-with", "x-amz-meta-myelement", ""]
Then you have to send that key. If the policy has constraints on content-type or key prefix these may also cause signature errors.

Keep getting "Invalid Content-Range" response from AWS Glacier Multipart Upload

I can't figure out why I keep getting an invalid Content-Range from AWS Glacier. It looks to me like my format follows RFC 2616 but I keep getting an error. Help?
Here's the code:
using (var FileStream = new System.IO.FileStream(ARCHIVE_FILE, FileMode.Open))
{
while (FileStream.Position < FileInfo.Length)
{
string Range = "Content-Range:bytes " + FileStream.Position.ToString() + "-" + (FileStream.Position + Size - 1).ToString() + "/*";
var request = new Amazon.Glacier.Model.UploadMultipartPartRequest()
{
AccountId = "-",
VaultName = VAULT_NAME,
Body = Amazon.Glacier.GlacierUtils.CreatePartStream(FileStream, Size),
UploadId = UploadId,
Range = Range,
StreamTransferProgress = Progress
};
//request.SetRange(FileStream.Position, FileStream.Position + Size - 1);
response = GlacierClient.UploadMultipartPart(request);
}
}
Apparently I misinterpreted the Intellisense description:
//
// Summary:
// Identifies the range of bytes in the assembled archive that will be uploaded
// in this part. Amazon Glacier uses this information to assemble the archive
// in the proper sequence. The format of this header follows RFC 2616. An example
// header is Content-Range:bytes 0-4194303/*.
You're not supposed to include the name of the header itself so this line:
string Range = "Content-Range:bytes " + FileStream.Position.ToString() + "-" + (FileStream.Position + Size - 1).ToString() + "/*";
Should be:
string Range = "bytes " + FileStream.Position.ToString() + "-" + (FileStream.Position + Size - 1).ToString() + "/*";
Derp.

Code for Google Analytic product hit in c#

I'm new in google analytic. I go through some regarding this. I found that there is no direct method to hit a windows application in google analytic. But i found some solutions in stackoverflow. I tried that, but didn't work for me. Below is the code that I'm using.
private void analyticsmethod4(string trackingId, string pagename)
{
Random rnd = new Random();
long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;
// Get the first run time
timestampFirstRun = DateTime.Now.Ticks;
timestampLastRun = DateTime.Now.Ticks - 5;
timestampCurrentRun = 45;
numberOfRuns = 2;
// Some values we need
string domainHash = "123456789"; // This can be calcualted for your domain online
int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
string source = "Shop";
string medium = "medium123";
string sessionNumber = "1";
string campaignNumber = "1";
string culture = Thread.CurrentThread.CurrentCulture.Name;
string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;
string statsRequest = "http://www.google-analytics.com/__utm.gif" +
"?utmwv=4.6.5" +
"&utmn=" + rnd.Next(100000000, 999999999) +
// "&utmhn=hostname.mydomain.com" +
"&utmcs=-" +
"&utmsr=" + screenRes +
"&utmsc=-" +
"&utmul=" + culture +
"&utmje=-" +
"&utmfl=-" +
"&utmdt=" + pagename + // Here i passed my profile name "MyWindowsApp"
"&utmhid=1943799692" +
"&utmr=0" +
"&utmp=" + pagename +
"&utmac=" + trackingId + //Tracking id : ie "UA-XXXXXXXX-X"
"&utmcc=" +
"__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
"%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";
try
{
using (var client = new WebClient())
{
//byte[] bt = client.DownloadData(statsRequest);
Stream data = client.OpenRead(statsRequest);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
MessageBox.Show(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This example is also got from this site itself. I don't know where was the problem. Please direct me, how can i make it. This is the output i'm getting "GIF89a".
Thanks
Bobbin Paulose
So it's working. The Google Analytics call loads a tiny GIF image, and the querystring parameters provided in the request trigger all the Google Analytics goodness. If you're getting a response back, you have registered your event successfully with Google.

Categories

Resources