Unable to get Data from vendor entity using filter - intuit-partner-platform

When I am trying with Date I am able tp get data from filter. But when I am trying to get data from filter using DateTime, I am unable to get Data. Below is my request body:
Filter=LastUpdatedTime :AFTER: 2013-06-07T15:00:00-0700 :AND: LastUpdatedTime :BEFORE: 2013-06-07T16:56:35-0700&PageNum=1&ResultsPerPage=100
and code:
requestBody = String.Format(requestBody, pageNumber, pageSize, After.ToString("yyyy-MM-ddTHH:mm:ss"), Before.ToString("yyyy-MM-ddTHH:mm:ss"));
HttpWebRequest httpWebRequest = WebRequest.Create(commonService.ServiceContext.BaseUrl + "vendors/v2/" + commonService.ServiceContext.RealmId) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
string oAuthHeader = GetDevDefinedOAuthHeader(context, httpWebRequest, requestBody);
httpWebRequest.Headers.Add("Authorization", oAuthHeader);
requestXML.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(requestXML.ToString());
Please tell me which format of Datetime do I need to send?

This is the data format you need to use:
<StartCreatedTMS>2009-11-17T22:35:08.0Z</StartCreatedTMS>
<EndCreatedTMS>2010-01-08T20:54:56.0Z</EndCreatedTMS>
thanks
Jarred

Related

Copying, modifying and sending request POST Fiddler

sorry for my English)))
I have been trying to solve my problem for a long time, but unfortunately so far without success ((((
I have a POST request of a certain type, I need to change it and send it to another address, and the original request should go further to its address. I'm trying to work with the exchange. More to the point, I have a request like this :
https://api.binance.com/api/v3/order?symbol=CELRBTC&orderId=73902412&recvWindow=55000&timestamp=1635266807744&signature=556b9c4121eb819d96a440b54661181e75ab2324a9d3b5fe0a73dd793626cb96
I need to send this request after the original one
https://fapi/binance.com/fapi/v1/order?symbol=KEEPUSDT&side=BUY&type=MARKET&quantity=100&timeInForce=GTC&recvWindow=5000&timestamp=1591702613943&signature= 3c661234138461fcc7a7d8746c6558c9842d4e10870d2ecbedf7777cad694af
In addition, the public API is passed in the header
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/plain; q=0.9, text/html;q=0.8,
Accept-Charset: UTF-8, *;q=0.8
Accept-Encoding: gzip, deflate
X-MBX-APIKEY: YIGXAtXbQg0790CnIvKzo3oIQPmEPwiySjdQj28h0H3g87D2rwcun0kRWvh4m9J6
Host: api.binance.com
I tried to do all this work in the onBeforeRequest method
static function OnBeforeRequest(oSession: Session) {
if (oSession.RequestMethod == "POST" && oSession.uriContains("order") ) {
oSession.utilDecodeResponse()
var strBody=oSession.GetRequestBodyAsString();
// timestamp, time ms
var timestampSTART= oSession.url.IndexOf("timestamp=") + 10;
var timestampEND= oSession.url.IndexOf("&", timestampSTART);
var timestamp = oSession.url.Substring(timestampSTART, 13);
// SYMBOL
var symbolStart = oSession.url.IndexOf("symbol=")+7;
var symbolend = oSession.url.IndexOf("BTC", symbolStart)+3;
var symbol = oSession.url.Substring(symbolStart, symbolend-symbolStart);
// Signature (timestamp+SecretAPIKey=Hmac Sha256) theoretically, it can be taken from the original request, but it is more reliable to make your own
var signStart = oSession.url.IndexOf("signature=")+10;
var sign = oSession.url.Substring(signStart);
//PRICE
var PriceStart = oSession.url.IndexOf("price=")+6;
var PriceEND = oSession.url.IndexOf("&", PriceStart);
var priceStr = oSession.url.Substring(PriceStart, PriceEND-PriceStart);
var price = parseFloat(priceStr);
// Quantity
var quantity = 50/ price*63000;
var apiBIN = "https://fapi.binance.com/fapi/v1/order?" ;
// var result = apiBIN+"symbol="+symbol+"&side=BUY&type=MARKET&quantity="+ quantity+"&timeInForce=GTC&recvWindow=5000&timestamp="+timestamp+"&signature="+sign;
// oSession.utilSetRequestBody(result)
// FiddlerApplication.oProxy.SendRequest(oSession.RequestHeaders, oSession.requestBodyBytes, null);
have selected the necessary parameters from the request, but I do not understand how to send it in any way, and I also lose the header with the API key.
Separately, I want to note the "Signature" parameter, which is created using the Hmac Sha256 algorithm from the secret API key and time, which I also can't figure out how to describe it in the code.
I would be very grateful for any help, with the possibility of some payment for substantial help.
I used C# to solve the problem. I didn't know Fiddler could choose the language. Technically, I have achieved my goal, but currently finance is writing an incorrect request. I will deal with this separately. Special thanks to Robert for his help.
public static void OnBeforeResponse(Session oSession)
{
if (oSession.HTTPMethodIs("POST") && oSession.uriContains("order"))
{
String strBody = oSession.GetRequestBodyAsString();
//Price
int PriceStart = strBody.IndexOf("price=")+6;
int PriceEND = strBody.IndexOf("&", PriceStart);
string priceStr = strBody.Substring(PriceStart, PriceEND-PriceStart);
float priceF = float.Parse(priceStr, System.Globalization.CultureInfo.InvariantCulture);
// SYMBOL
int symbolStart = strBody.IndexOf("symbol=")+7;
int symbolend = strBody.IndexOf("BTC", symbolStart);
string symbol = strBody.Substring(symbolStart, symbolend-symbolStart);
// Quantity
int quantStart = strBody.IndexOf("quantity=")+9;
int quantend = strBody.IndexOf("&price", quantStart);
string quant = strBody.Substring(quantStart, quantend-quantStart);
float quantity = float.Parse(quant, System.Globalization.CultureInfo.InvariantCulture)*2;
// timestamp
decimal timestamp = Math.Round(Convert.ToDecimal(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds), 0);
//Sign
Encoding ascii = Encoding.ASCII;
string secretKey = "lfaeGkjitNwvyG2lqDueMhSAOzRFlzL73w5pKRCAvSy7YrxyTkvwKCcHBHj...";
HMACSHA256 hmac = new HMACSHA256(ascii.GetBytes(secretKey));
// string query_string_LIMIT = "symbol="+symbol+"USDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity="+quantity+"&price="+priceF+"&recvWindow=5000&timestamp="+timestamp+"&signature=";
string result = "symbol="+symbol+"USDT&side=BUY&type=MARKET&quantity="+ quantity+"&recvWindow=5000&timestamp="+timestamp+"&signature=";
String signature = BitConverter.ToString(hmac.ComputeHash(ascii.GetBytes(result))).Replace("-","");
oSession.host="fapi.binance.com";
string resultRequest = "symbol="+symbol+"USDT&side=BUY&type=MARKET&quantity="+ quantity+"&recvWindow=5000&timestamp="+timestamp+"&signature="+signature;
byte[] resulByte = System.Text.Encoding.ASCII.GetBytes(resultRequest);
//oSession.utilReplaceInRequest("api/v3/order","fapi/v1/order?"+resultFin);
oSession.url = oSession.url.Replace("api/v3/order", "fapi/v1/order?"+resultRequest);
FiddlerApplication.oProxy.SendRequest (oSession.RequestHeaders, resulByte, null);
}

Mailkit use of resource image with LinkedResources.Add

Trying to use a resource image:
var builder = new BodyBuilder();
var image =
builder.LinkedResources.Add("pack://application:,,,/Resources/LOGO_275.png");
image.ContentId = MimeUtils.GenerateMessageId();
but needs a string (filename:)
How can i use a resource image ?
Kind Regards
Johan
var builder = new BodyBuilder();
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LOGO_275.png")) {
var image = builder.LinkedResources.Add("LOGO_275.png", stream);
image.ContentId = MimeUtils.GenerateMessageId();
}
The Add() methods that take a string filename and a Stream only use the filename string to figure out the MIME-Type and set the filename property of the attachment.
I had to use NameSpace.Resources.Resource.ext otherwise GetManifestResourceStream() returned null
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("WPF_Bestelbons.Resources.LOGO_275.png"))

How to upload an audio file in apex code via MultiPart FormData

I am working on a project in which I need to upload an audio file to the External webservice via Apex code. So I am using multipart form data to do the same but every time I am getting an error i.e ActionController::UnknownFormat
I am trying to do the same via multipart form data in apex.
String body = '--' + boundary + '\r\n';
body += 'Content-Disposition: form-data; name="recording[s3_location]"; filename="abc.mp3"\r\nContent-Type: audio/mpeg\r\n\r\n';
body += 'F:\Test.mp3\r\n';
body += '--' + boundary + '--';
Expected result code: 201(success)
Actual Result Code: 500(ActionController::UnknownFormat)
I tried with postman its working fine but whenever i am trying with my code i am getting the exception. Please help me. Thanks in advance :)
Here is a working solution for sending one file at a time:
// form boundary must be a string that will very likely never appear again in the form
public static final String BOUNDARY = '----FormBoundary4Amf13kZd';
public static final String EXTRABOUNDARY = '--' + BOUNDARY;
/**
*
*
* #param file The file that will be uploaded.
* #param contentType The content-type of the file. Will default to application/octet-stream.
* #param filename Name to give the file.
* #param formDataMap Any extra metadata that you want to send.
*
* #return Blob of the complete multipart form.
*/
public static Blob multiPartFormDataBody(Blob file, String contentType, String filename, Map<String, String> metadataMap) {
contentType = contentType == '' ? 'application/octet-stream' : contentType;
String bodyStartHex = EncodingUtil.convertToHex(Blob.valueOf(EXTRABOUNDARY + '\r\nContent-Disposition: form-data; name=\"file\"; filename="' + filename + '"\r\nContent-Type: ' + contentType + '\r\n\r\n'));
String bodyEndHex = EncodingUtil.convertToHex(Blob.valueOf(EXTRABOUNDARY + '--\r\n'));
bodyStartHex += EncodingUtil.convertToHex(file);
if (metadataMap != null && metadataMap.size() != 0) {
String formElements = '\r\n';
for (String key : metadataMap.keySet()) {
formElements += EXTRABOUNDARY + '\r\nContent-Disposition: form-data; name=\"' + key + '\"\r\n\r\n' + metadataMap.get(key) + '\r\n';
}
bodyStartHex += EncodingUtil.convertToHex(Blob.valueOf(formElements));
} else {
// the extra '--' at the end is crucial
bodyEndHex = EncodingUtil.convertToHex(Blob.valueOf('\r\n' + EXTRABOUNDARY + '--'));
}
return EncodingUtil.convertFromHex(bodyStartHex + bodyEndHex);
}
The important thing to note here is that you MUST convert your entire mutltipart-form string to a hexidecimal string and then back to Blob before sending to an external webservice, because you cannot mix the file binary and the UTF-8 boundary strings. You first get the Blob of the boundaries and metadata and convert them to hex. Then you take your input file Blob and convert it to hex. Then you combine the hex strings together and convert them back to a Blob to be sent via HttpRequest:
public static HttpResponse sendMultiPartForm(Blob file, String contentType, String filename, Map<String, String> metadataMap) {
HttpRequest request = new HttpRequest();
Http http = new Http();
request.setEndpoint('https://example.com/api/upload');
request.setMethod('POST');
// Boundary must be set to exactly what was set before
request.setHeader('Content-Type', 'multipart/form-data; boundary=' + BOUNDARY);
request.setBodyAsBlob(multiPartFormDataBody(file, contentType, filename, metadataMap));
request.setHeader('Content-Length', String.valueOf(request.getBodyAsBlob().size()));
return http.send(request);
}
I left out explanation for the carriage returns and newlines, because they need to be so exact here that honestly everyone should just copy and paste them. It took a lot of trial and error to get it right.

Dotnet core: send byte array as file from web api without saving it to disk

I have a web api that need to let the user download/inline a binary file I have saved to a database.
So far now I could achieve it like this:
string ContentType = (string) (result["content_type"] ?? "");
string FileName = (string) (result["file_name"] ?? "");
byte[] content = (byte[]) result["data"];
Stream stream = new MemoryStream(content);
var fullFileName = Path.GetTempFileName();
File.WriteAllBytes(fullFileName, content);
_res.ContentType = ContentType;
_res.StatusCode = (int)HttpStatusCode.OK;
_res.Headers.Add("Content-Disposition", $"{Disposition}; filename=\"{FileName}\"");
await _res.SendFileAsync(fullFileName);
I'd like to know how could I send directly the memory stream to the response, in order to avoid saving the file to disk.
You'll want to use HttpResponse.BinaryWrite or MemoryStream.WriteTo:
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=file.xls");
Response.BinaryWrite(myByteArray);
// myMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
I found an easier way
string ContentType = (string) (result["content_type"] ?? "");
string FileName = (string) (result["file_name"] ?? "");
byte[] content = (byte[]) result["data"];
_res.ContentType = ContentType;
_res.ContentLength = content.Length;
_res.StatusCode = (int)HttpStatusCode.OK;
_res.Headers.Add("Content-Disposition", $"{Disposition}; filename=\"{FileName}\"");
await _res.Body.WriteAsync(content, 0, content.Length);

How to calculate Amazon's MD5 hash for http request

Does anyone know how to calculate the MD5 hash that is needed to be used with Amazon's SubmitFeed API? I am using ColdFusion and every time I calculate the MD5 hash on my end it never matches what Amazon calculates.
Amazon responds with this error:
ContentMD5DoesNotMatch
the Content-MD5 HTTP header you passed for your feed (C7EF1CADB27497B46FCD6F69516F96E0) did not match the Content-MD5 we calculated for your feed (x+8crbJ0l7RvzW9pUW+W4A==)
I am using the built-in function that ColdFusion uses for hashing (example hash(myStr)). Is there a step I am missing?
public any function EncryptSignature(required string argValue,required string publicKey) hint="I create my own signature that I will matching later." {
local.filters=StructNew();
local.filters["F:publicKey"]=arguments.publicKey;
var jMsg=JavaCast("string",arguments.argValue).getBytes("iso-8859-1");
var thisSecretKey = getDAO().getSecretKey(local.filters).apiSecretKey;
var jKey=JavaCast("string",thisSecretKey).getBytes("iso-8859-1");
var key=createObject("java","javax.crypto.spec.SecretKeySpec");
var mac=createObject("java","javax.crypto.Mac");
key=key.init(jKey,"HmacSHA1");
mac=mac.getInstance(key.getAlgorithm());
mac.init(key);
mac.update(jMsg);
return lCase(binaryEncode(mac.doFinal(),'Hex'));
//return Encrypt(arguments.argValue,getapiUsersDAO().getSecretKey(arguments.publicKey),'HMAC-SHA1');
}
The problem is that Feed must have preceding
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
Even adding it as a Declaration is not enough
var memoryStream = new MemoryStream();
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("AmazonEnvelope",
...
if you are using XmlWriter:
using (var xmlWriter = XmlWriter.Create(memoryStream))
{
doc.WriteTo(xmlWriter);
}
You have to save XDocument to file and then get stream from file. Only in this case XDocument preserves declaration (designed behaviour of Save() and WriteTo() methods):
var memoryStream = new MemoryStream();
doc.Save(memoryStream);
var file = Path.GetTempFileName();
using (var fileStream = File.OpenWrite(file))
{
var buffer = memoryStream.GetBuffer();
fileStream.Write(buffer, 0, (int)memoryStream.Length);
}
return File.Open(file, FileMode.Open, FileAccess.Read);
I checked this online tool and you just need to send that MD5 in base64 encoding. It is currently just hexadecimal encoded.
I'm afraid I don't know what the ColdFusion way to do that is, maybe this:
SHA or MD5 Digests in ColdFusion
Here is what I did to get this to work:
<cfset getMD5 = ToBase64(binaryDecode(hash(xmlRequest),'hex'))>
And bang it matched Amazons MD5 hash.
Here is an alternative java-way
found on http://www.kba.suche-spezialwerkzeug.de/pdf/MWSDeveloperGuide.pdf
public static String computeContentMD5HeaderValue(FileInputStream fis)
throws IOException, NoSuchAlgorithmException {
DigestInputStream dis = new DigestInputStream(fis,
MessageDigest.getInstance("MD5"));
byte[] buffer = new byte[8192];
while (dis.read(buffer) > 0)
;
String md5Content = new String(
org.apache.commons.codec.binary.Base64.encodeBase64(dis.getMessageDigest().digest())
);
// Effectively resets the stream to be beginning of the file via a
// FileChannel.
fis.getChannel().position(0);
return md5Content;
}
This will give your desire output.
<cfset binaryValue = binaryDecode( 'C7EF1CADB27497B46FCD6F69516F96E0', "hex" )>
<cfset base64Value = binaryEncode( binaryValue, "base64" )>
<cfdump var="#base64Value#">