Uploading files on Dropbox using C# in ASP.NET - oauth-2.0

RequestResult strReq = OAuthUtility.Put(
"https://content.dropboxapi.com/1/files_put/auto/",
new HttpParameterCollection {
{"access_token",MYAccessToken},
{"path",Path.Combine(this.CurrentPath, Path.GetFileName(#"C:\test\jj.kk\Downloads\1990480.jpg")).Replace("\\","/")},
{"overwrite","true"},
{"autorename","true"}
}
);
I am using above code for uploading file on Dropbox but giving following error:
The remote server returned an error: (400) Bad Request.
RequestResult : { "error": "Content-Type (application/x-www-form-urlencoded) may not be one of (\'application/x-www-form-urlencoded\', \'multipart/form-data\')" }
Httpheader :
{Transfer-Encoding: chunked
Connection: keep-alive
X-Dropbox-Request-Id: 4029d2ae041cf1f25d8f58d06d158b83
X-Robots-Tag: noindex, nofollow, noimageindex
Content-Type: application/json
Date: Fri, 07 Oct 2016 15:24:17 GMT
Server: nginx
}
Is there any other way of uploading files on Dropbox in ASP.NET?

The error message you're getting is indicating that the issue with your API request is that the Content-Type has an unexpected value. That is, you (via the library you're using, presumably) are sending application/x-www-form-urlencoded. That isn't an allowed format for the Dropbox API /1/files_put endpoint, which expects the raw file data in the body of the request.
To answer your actual question though, there is another way to upload to Dropbox in ASP.NET. You can use Dropbox API v2, instead of Dropbox API v1 as you have here. (And in fact you should, since Dropbox API v1 is deprecated.)
To do so, we highly recommend using the official SDK:
https://www.dropbox.com/developers/documentation/dotnet
Alternatively, you can use the HTTP endpoints directly, e.g.,:
https://www.dropbox.com/developers/documentation/http/documentation#files-upload

Related

Request returns AccessDenied when trying to save in SQS

I have an API Gateway that publishes the request in SQS. This Gateway has SQS SendMessage policy, and this issue I am describing here does not happen when I use the Test option of the gateway.
I am using Insomnia to make requests to the server, with these headers:
Content-Type: application/x-www-form-urlencoded
x-api-key: <My API Key>
Basically the configuration was done following this tutorial:
https://medium.com/#pranaysankpal/aws-api-gateway-proxy-for-sqs-simple-queue-service-5b08fe18ce50
The only difference I included the MessageGroupId on the Mapping template for deduplication:
Action=SendMessage&MessageBody=$input.body&MessageGroupId=$context.resourcePath
The response I am getting is vey weird, because it is a Http 200, with header:
date: Mon, 12 Apr 2021 13:05:53 GMT
content-type: application/json
content-length: 377
x-amzn-requestid: xxxxxxxxxxxxxxxxxxx
x-amz-apigw-id: xxxxxxxxxxxxx
x-amzn-trace-id: Root=xxxxxx
And the body:
<?xml version="1.0"?>
<ErrorResponse
xmlns="http://queue.amazonaws.com/doc/2009-02-01/">
<Error>
<Type>Sender</Type>
<Code>AccessDenied</Code>
<Message>Access to the resource https://sqs.xxxxxxx.amazonaws.com/arn:aws:sqs:us-xxxx-x:xxxxxxxx:xxxxxxxxx.fifo is denied.</Message>
<Detail/>
</Error>
<RequestId>xxxxxxxxxxxxxx</RequestId>
</ErrorResponse>
x's are used to hide information I am not sure are sensible.
I am not sure how to proceed, it seems to an issue while publishing in the queue.
In my inexperience, I was not aware that API Gateway requires Deploy for most of the changes.

Microsoft Update DriveItem API throwing locked exception if the file is open in desktop

1.This is the behavior I am observing when I use Update DriveItem graph API to update my file name.https://learn.microsoft.com/en-us/graph/api/driveitem-update?view=graph-rest-1.0&tabs=http.
2.If the file is open in my office desktop document it throws locked exception. If i close the file renaming works fine.
3.I tested same in sharepoint their UI ,I am able to rename the file.But through graph API it throws locked exception if file is open.
Is this error expected ?. How can I get around this
https://learn.microsoft.com/en-us/graph/api/driveitem-update?view=graph-rest-1.0&tabs=http.
PATCH https://graph.microsoft.com/v1.0/drives/b!qnfox2pppU-AeWEPhWpRhNiB9gIq_ANJq5NFCiklU2Y5F3fDc7fsaQvB/items/014UHAXWYO5LX2RTA6YZE37E4XTG45PTTW
SdkVersion : graph-java/v1.6.0
Authorization : Bearer
{"name":"V-blah (1) (113_0_4_26).docx"}
423 : Locked
Strict-Transport-Security : max-age=31536000
Cache-Control : private
x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"West US","Slice":"SliceC","Ring":"5","ScaleUnit":"000","RoleInstance":"AGSFE_IN_57"}}
client-request-id : 33f16bde-55d1-XXXX
request-id : XXXXXXX
Content-Length : 251
Date : Sat, 02 May 2020 04:05:23 GMT
Content-Type : application/json
{
"error": {
"code": "resourceLocked",
"message": "The resource you are attempting to access is locked",
"innerError": {
"request-id": "d1bfa1f2-cXXXXX",
"date": "2020-05-02T04:05:23"
}
}
}
Ensure that the document library does not have "check-in required" enabled.
Assuming check-in is not required, I received the same HTTP 423 "resourceLocked" response for both scenarios: file opened in the browser (SharePoint Online UI) and file opened in desktop client. I believe this is working by design that you can't update a file's name when it is currently opened by another user or yourself in another instance.
Please see this reference about files locked for editing.
Try adding the HeaderOption that bypasses the shared lock, to the request.
new Microsoft.Graph.HeaderOption("Prefer", "bypass-shared-lock")
If you are using the graphServiceClient, add it to a List and pass it directly in your Request.

Send multiple files using HTTParty

Here is the code which is working using Net::HTTP::Post
request = Net::HTTP::Post.new(url)
...
form_data = [
['attachments[]', File.open('file1.txt')],
['attachments[]', File.open('file2.txt')]
]
request.set_form form_data, 'multipart/form-data'
http.request(request)
Now, I am trying to use httparty like below but it is not working.
body = { attachments: [ File.open('file1.txt'), File.open('file2.txt') ] }
HTTParty.post(url, body: body)
The response I am getting from web service call is below:
#<HTTParty::Response:0x557d7b549f90 parsed_response={"error"=>true, "error_code"=>"invalid_attachment", "error_message"=>"Attachmen
t(s) not found or invalid."}, #response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, #headers={"server"=>["nginx"], "date"=>[
"Mon, 20 May 2019 07:41:50 GMT"], "content-type"=>["application/json"], "content-length"=>["102"], "connection"=>["close"], "vary"=>["
Authorization"], "set-cookie"=>["c18664e1c22ce71c0c91742fbeaaa863=uv425hihrbdatsql1udrlbs9as; path=/"], "expires"=>["Thu, 19 Nov 1981
08:52:00 GMT", "-1"], "cache-control"=>["no-store, no-cache, must-revalidate", "private, must-revalidate"], "pragma"=>["no-cache", "no
-cache"], "x-ratelimit-limit"=>["60"], "x-ratelimit-remaining"=>["59"], "strict-transport-security"=>["max-age=63072000; includeSubdom
ains;"]}>
It looks like it is not able to read the contents of files. Does HTTParty support this or I need to use some other gem?
Something like this should work, I just tested it, worked for me no problem.
HTTParty.post(url,
body: { attachments: [
File.read('foo.txt'),
File.read('bar.txt')] })
With HTTParty you can pass IO/Files as parameters the same way (multipart is automatically set to true if there's a file in parameters).
But keep in mind that files should be closed after upload, otherwise you may run out of file descriptors before GC collects them:
files = ['file1.txt', 'file2.txt'].map{|fname| File.open(fname) }
begin
HTTParty.post(url, body: { attachments: files })
ensure
files.each(&:close)
end
That should work for you if net/http variant does (and is actually the same as your code).
Other thing to look at is content type detection by filename - because file upload consists of filename, content type and data itself.
Error 400 with "invalid_attachment" you're getting suggests that more probably it's related to content type or other validation on server side (so make sure you're testing with the same files and nothing else changes other than http lib), also check httparty to be a recent version
I've written a test program which sends the same multipart request using both Net::HTTP and HTTParty. Then it compares and prints the request strings so that we can compare them. The only substantive difference between the two requests is that HTTParty attempts to guess and set the Content-Type header (e.g. text/plain for a file named file1.txt), whereas Net::HTTP always uses application/octet-stream.
HTTParty definitely does read the files and send them in the request. So, I suggest you investigate if the server is returning an error due to the Content-Type (maybe the content type in your particular request is not supported).
For your reference, here is the test program and specific results.

NodeMCU - Lua - HTTP Post or luasocket - Need guidance

This is my first time here and thought of joining the forum because I am new to Lua programming and have almost given up on HTTP Post method.
I am trying my hands on IOT using ESP8266 (running on NodeMCU) and using ESPlore to send the Lua program to ESP8266.
So, my program's objective is to call an API and post few parameters using my Lua program running on ESP8266.
I tried the following approaches -
1. Using HTTP Post
conn=net.createConnection(net.TCP, 0)
conn:on("receive", display)
conn:connect(80,HOST)
conn:on("connection",function(obj)
local post_request = build_post_request(HOST,URI)
obj:send(post_request)
end
----function as below ----------------------------------------------------
function build_post_request(host, uri)
local data = ""
data = "param1=1&param2=2"
request = "POST uri HTTP/1.1\r\n"..
"Host: example.com\r\n"..
"apiKey: e2sss3af-9ssd-43b0-bfdd-24a1dssssc46\r\n"..
"Cache-Control: no-cache\r\n"..
"Content-Type: application/x-www-form-urlencoded\r\n"..data
return request
end
----------------Response --------------------------------------
HTTP/1.1 400 Bad Request
Date: Sun, 11 Oct 2015 16:10:55 GMT
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Connection: close
Apache Tomcat/7.0.54 - Error report
The request sent by the client was syntactically incorrect.
I don't understand what is wrong with it.
2. Using Luasocket
I have included following in my program -
local http = require"socket.http"
local ltn12 = require"ltn12"
and it throws following errors-
script1.lua:3: module 'socket.http' not found:
no field package.preload['socket.http']
no file 'socket/http.lc'
no file 'socket/http.lua'
I don't know how to get these libs and send to ESP8266 and not sure if that will suffice.
Question :
Which is the best method to post data to a server using an API.
a. If HTTP Post, what is the problem with my code.
b. If Luasocket then how do I send it to ESP8266 as I am not using a compiler on my laptop.
"Content-Type: application/x-www-form-urlencoded\r\n"..data
I don't understand what is wrong with it.
In HTTP,the headers are always delimited by \r\n\r\n. Without the second CR-LF pair, the following data with cause a header error as reported dy Tomcat.
Second you can't use the standard socket libraries on the ESP8266. You must use the net library which is a nodemcu wrapper around the Espressif SDK.

How do I post adaptive payment information to paypal?

I've managed to get an adaptive payments script to work in the apigee console, here is the request:
X-PAYPAL-REQUEST-DATA-FORMAT: JSON
X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T
X-HostCommonName: svcs.sandbox.paypal.com
Host: svcs.sandbox.paypal.com
Content-Length: 428
X-PAYPAL-DEVICE-IPADDRESS: 127.0.0.1
X-Forwarded-For: 10.203.10.109
X-PAYPAL-REQUEST-SOURCE: APIGEE-CONSOLE-1.0
X-Target-URI: https://svcs.sandbox.paypal.com
X-PAYPAL-RESPONSE-DATA-FORMAT: JSON
Content-Type: text/plain; charset=ISO-8859-1
Connection: Keep-Alive
"{
"actionType":"PAY",
"currencyCode":"USD",
"receiverList":{"receiver":[{"amount":"5.00","email":"cam_1315509411_per#btinternet.com"}]},
"returnUrl":"http://apigee.com/console/-1/handlePaypalReturn",
"senderEmail":"qwom_1315508825_biz#btinternet.com",
"feesPayer":"SENDER",
"cancelUrl":"http://apigee.com/console/-1/handlePaypalCancel?",
"requestEnvelope":{"errorLanguage":"en_US", "detailLevel":"ReturnAll"}
}"
How do I actually post this information to the https://svcs.sandbox.paypal.com/AdaptivePayments/Pay url? I can't find the easiest way to do it, should I use cURL and what are the variables names for each post value?
That depends on the rest of your application. PHP with cURL is fairly straightforward, but it's not too much of a hassle in other languages either.
PayPal has sample code online at https://www.x.com/developers/PayPal/documentation-tools/code-sample/78
If you were to do this yourself, you'd need to (in a nutshell):
- Send a proper HTTP header with the X- headers as shown above including the application ID.
- Send the API call via JSON, SOAP or NVP as POST or GET to the API endpoint
- Decode the response and act accordingly

Resources