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

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.

Related

out of memory exception while drawing image in asp.net

We are drawing and editing pdf by using the following code,but when we play with 11mb size file,we are getting out of memory exception,can we fix the issue,I had used System.Drawing.Image.FromFile instead of FromStream but no luck..
public static string ImageCar()
{
string FileName = HttpContext.Current.Session["filename"].ToString();
Document doc = new Document(FileName);
ArrayList arrFiles = new ArrayList();
string strFileName = "";
for (int pageCount = 1; pageCount <= TotalPages; pageCount++)
{
using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image_" + strDateTime + "_" + pageCount + ".png"), FileMode.Create, FileAccess.ReadWrite))
{
strFileName = HttpContext.Current.Server.MapPath("Path" + strDateTime + "_" + pageCount + ".png");
arrFiles.Add(strFileName);
PngDevice pngDevice = new PngDevice();
//Convert a particular page and save the image to stream
pngDevice.Process(doc.Pages[pageCount], imageStream);
using (System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream))
{
ScaleImage(image, 1189, 835, HttpContext.Current.Server.MapPath("Input/image1_" + strDateTime + "_" + pageCount + ".png"), out height, out Aratio);
image.Dispose();
imageStream.Close();
if (pageCount == 1)
fields = CheckFields(doc, pageCount, "image1_" + strDateTime + "_" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed);
pages = pages + "," + "image1_" + strDateTime + "_" + pageCount + ".png";
Ratios = Ratios + "," + Aratio;
Allheights = Allheights + "," + height;
// Delete file from image folder
try
{
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
}
catch (Exception ex)
{
}
}
}
}
Ratios = Ratios.Substring(1, Ratios.Length - 1);
pages = pages.Substring(1, pages.Length - 1);
Allheights = Allheights.Substring(1, Allheights.Length - 1);
if (fields != "")
{
fields = fields.Substring(3, fields.Length - 3);
}
return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields;
}
System.Drawing has known memory leaks in a ASP site, and should never be used.
It will eventually case OOM errors, and while you can avoid it by restarting the server every so often, or throwing more memory at it, there is no real, long term fix. Use some other library for the image manipulation portion, and you should have less issues.
See the bottom of this page:
https://msdn.microsoft.com/en-us/library/system.drawing(v=vs.110).aspx
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

Google Cloud Speech response always empty error

I am sending audio to GCS, via "https://speech.googleapis.com/v1/speech:recognize?key=<my key>", the following way:
byte[] audioBytes = g_NPCAudioListener.GetAudioClipMonoData16(88200);
string jsonData = "{" +
"\"config\": {" +
"\"encoding\": \"LINEAR16\"," +
"\"sampleRateHertz\": 48000," +
"\"languageCode\": \"en-US\"" +
"}," +
"\"audio\": {" +
"\"content\" : \"" + Convert.ToBase64String(audioBytes) + "\"" +
"}" +
"}";
byte[] postData = System.Text.Encoding.UTF8.GetBytes(jsonData);
g_NPCController.Debug("Sending to google: " + jsonData);
using (WWW req = new WWW(g_Google_Speech_URL, postData, g_JSONHeaders)) {
yield return req;
if (req.error == null) {
g_NPCController.Debug(req.text.Replace("\n", "").Replace(" ", ""));
} else {
string msg = Convert.ToString(req.bytes);
g_NPCController.Debug("Google Speech Error: " + req.error + "\n - error: " + req.text);
}
}
Everything is up to specification, however, I keep getting nothing but an error flag with an empty body.
While working on the main JSON impl, I was getting "Invalid parameter" and such... but now that I am streaming 88200 chunks of 16-bit uncompressed audio bytes, I keep getting an error with no text attached to it - not even a code. Did anyone come across a similar situation?
If relevant, the audio I get it from an AudioClip in Unity, then convert the 32-bit float[] to a byte[originalAudio.Length * sizeof(float)] and then to base64 as required.
Thanks.

restsharp how to add key value pair as parameter

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

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.

Payment succeeds, and our data matches querystring data, but falls thru to INVALID anyway!

Why does my ipn script I wrote always fail? It always goes to INVALID even though it matches everything in the query string that paypal sends to me?
notification.cshtml?tx=b78v54b5b55rby92S&st=Completed&amt=3.04&cc=USD&cm=&item_number=&merchant_return_link=Return+to+web+site+name&form_charset=UTF-8
And the part that checks it is:
string LiveURL = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LiveURL);
// Set request back values.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] parameters = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string RequestString = System.Text.Encoding.ASCII.GetString(parameters);
RequestString += "&cmd=_notify-validate";
request.ContentLength = RequestString.Length;
// Send request to PP and get response.
StreamWriter Sout = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
Sout.Write(RequestString);
Sout.Close();
StreamReader Sin = new StreamReader(request.GetResponse().GetResponseStream());
string response = Sin.ReadToEnd();
Sin.Close();
if(result != null && result.OrderStatus == "Confirmed")
{
switch(response)
{
case "VERIFIED":
if(Request["st"] == "Completed")
{
var PPQuery = "SELECT TransactionId, OrderTotal FROM Orders WHERE OrderId = '" + Session["OSFOID"] + "' AND UserId = '" + WebSecurity.CurrentUserId + "'";
var ppQueryResult = database.Query(PPQuery);
foreach(var item in ppQueryResult)
{
decimal fff = 3.04M;
if(item["TransactionId"] != Request["tx"])
{
if(item["OrderTotal"] == TotalPrice)
{
// Payment was a success. Convey that to the user.
output = "Thanks. Order complete.";
}
else
{
// Possible fraud. Log it.
}
}
else
{
// This is a duplicate transaction. Log it and Redirect to homepage.
}
}
}
break;
case "INVALID":
output = "Invalid was returned. Investigate further.";
break;
default:
output = "Other exception has occured. Investigate further and log.";
break;
}
}
The code looks fine. The problem must be with response not matching "VERIFIED".
You're not in Turkey by chance, and changing response to uppercase prior to the comparison? *
*) If the locale is Turkey, uppercasing a string turns i into İ, not I (just one of the many traps with string manipulation)
Within the "VERIFIED" block, check:
if (Request.Params["payment_status"] == "Completed")
{
...
}
Request["st"] is incorrect.
Be sure to set IPN URL in one place in PayPal admin and do not use the other form of return URL checking (can't remember the name of it offhand) and IPN at the same time.
There is no "merchant_return_link" parameter; I think it should be "notify_url"... the URL string and the list of params doesn't look right to me; for example: &cm=&item_number
I know your list of params will be unique for your situation, but here's some sample code where I construct the URL to be passed to PayPal:
protected string GetPayPalURL(string SERVER_URL, string business, string[] itemNames,
int[] quantities, decimal[] amounts, double[] weight, string invoiceID, string transID, string NOTIFY_URL)
{
// Customer will be required to specify delivery address to PayPal - VERY IMPORTANT
const string NO_SHIPPING = "2";
StringBuilder url = new StringBuilder();
url.Append(SERVER_URL + "?cmd=_cart&upload=1");
url.Append("&business=" + HttpUtility.UrlEncode(business));
for (int i = 0; i < itemNames.Length; i++)
{
url.Append("&item_name" + "_" + (i + 1).ToString() + "=" + HttpUtility.UrlEncode(itemNames[i]));
url.Append("&quantity" + "_" + (i + 1).ToString() + "=" + quantities[i].ToString().Replace(",", "."));
url.Append("&amount" + "_" + (i + 1).ToString() + "=" + amounts[i].ToString().Replace(",", "."));
url.Append("&weight" + "_" + (i + 1).ToString() + "=" + weight[i].ToString().Replace(",", "."));
}
url.Append("&no_shipping=" + HttpUtility.UrlEncode(NO_SHIPPING));
url.Append("&custom=" + HttpUtility.UrlEncode(invoiceID));
url.Append("&txn_id=" + HttpUtility.UrlEncode(transID));
url.Append("&notify_url=" + HttpUtility.UrlEncode(NOTIFY_URL));
return url.ToString();
}
I think the Paypal method you are trying to do is as follows on code project
and if you get payment_status = INVALID, then check the reason in payment_reason
i dont see in the code where you are defining result which is checked in the if, also in the switch you are checking against request, surely this should be against response?

Categories

Resources