Attach POST data to BackgroundDownloader - post

I am implementing a Windows Phone 8.1 application that creates BackgroundDownloaders to restore cloud files back to the phone.
The cloud requires to POST the file ID as an additional JSON POST request and i cannot find a way to define it the BackgroundDownloader object.
Any ideas?

The way to do it is by creating a temp file to hold the JSON post data and send it to the CreateDownload function (as the last StorageFile parameter).
In addition, i added a Content-Type header to describe it (for me it is application/x-www-form-urlencoded) and add it with SetRequestHeader.
//set the Content-Type header
BackgroundDownloader^ downloader = ref new BackgroundDownloader();
Platform::String^ SKey2 = ref new Platform::String(L"Content-Type");
Platform::String^ SValue2 = ref new Platform::String(L"application/x-www-form-urlencoded");
downloader->SetRequestHeader(SKey2, SValue2);
//Create a temporary file and write the POST data into it
StorageFile^ postDataFile = nullptr;
....
//Call CreateDownload with the postDataFile
downloader->CreateDownload(uri, file, postDataFile);
That worked for me.

Related

Data Gets Converted when passed to CREATE_STREAM

I have created an UI5 Application to read a file and send it to a custom OData Service in the Backend.
onUploadFile: function() {
var oFileUpload =
this.getView().byId("fileUploaderFS");
var domRef = oFileUpload.getFocusDomRef();
var file = domRef.files[0];
var that = this;
var reader = new FileReader();
var ftype = file.type;
reader.readAsArrayBuffer(file);
reader.onload = function(evt) {
var vContent = evt.currentTarget.result
console.log(vContent);
var hex = that.buf2hex(vContent);
that.updateFile(hex, ftype);
}
},
buf2hex: function(buffer) {
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
When I print the content of hex on the console before sending it to the backend, the data starts with 89504e470d0a1a0a0000000d49484 ....
Even before sending the data in the payload to Odata Service it shows the correct data
Here is the Odata Service
Inside the Create Stream the data when received, is getting converted into something else. As a result the image that has been saved is not opening.
I tried to change the Data Type of Content in SEGW to Binary and it did not work. I also tried to convert the data in the create_stream but in vain. At last I tried reading the data in UI5 in different formats but of no use.
This whole Odata service works perfectly fine when I load the data through Postman Application.
Please help me resolve this Issue. Thanks In Advance.
The sap.ui.unified.FileUploader has everything built in. No need for conversions from Buffer to hex.
Make sure that your FileUploader knows where to upload the file
<unified:FileUploader xmlns:unified="sap.ui.unified"
id="fileUploaderFS"
uploadUrl="/sap/opu/odata/sap/Z_TEST_SRV/FileSet"
/>
The attribute uploadUrl points to the media entity for which you implemented the create_stream method.
Then when the upload is triggered via button press, simply get the FileUploader, set the token (for security reasons when doing a POST request), and fire the upload method.
onUploadFile: function () {
const oFileUpload = this.getView().byId("fileUploaderFS");
const sToken = this.getModel("nameOfTheModel").getSecurityToken();
const oTokenParam = new FileUploaderParameter({
name: "x-csrf-token",
value: sToken
});
oFileUpload.removeAllHeaderParameters()
oFileUpload.addHeaderParameter(oTokenParam);
oFileUpload.upload();
}
To use FileUploaderParameter, make sure to import it at the beginning:
sap.ui.define([
// ...,
"sap/ui/unified/FileUploaderParameter"
], function (/*..., */FileUploaderParameter) {
// ...
Now about your File entity. When working with it via create_stream or read_stream, you don't use the entity structure but is_media_resource. This means your entity doesn't need a property content. Or most of the other properties (except a unique id and the mime type). All other properties would only be used if you want to do one of the CRUD methods (which happens almost never when dealing with streams).

How to send timezone to dialogflow request using php script?

We have a chat interface which we are using to request to dialogflow. Here the chat window is designed in php.
Now the chat can be initiated in any location, so when user connects we are also trying to capture timezone and send in the request to dialogflow. Based on the timeZone the results also differ.
Now i used the below code to append timezone, based on api considered from github in php.
GIT HUB link from where i have taken the code
https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/dialogflow/src/detect_intent_texts.php
The script taken from git hub is as follows
// Actual Script
// START dialogflow_detect_intent_text
//namespace Google\Cloud\Samples\Dialogflow;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\QueryParameters;
use Google\Cloud\Dialogflow\V2\SessionEntityTypesClient;
use Google\Cloud\Dialogflow\V2\EntityTypesClient;
use Google\Cloud\Dialogflow\V2\ContextsClient;
function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US')
{
$test = array('credentials' => 'apikey/test-cd4f0-XXXXX.json');
// new session
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
printf('Session path: %s' . PHP_EOL, $session);
// query for each string in array
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
// output relevant info
$fulfilmentText = $queryResult->getFulfillmentText();
$sessionsClient->close();
}
echo detect_intent_texts('vehicle-test-cd4f0','text chat','123456','en-US','America/New_York');
// END dialogflow_detect_intent_text
Environment Details
OS : Linux
PHP 7.1
dialogflow v2
I have modified the script when sending data from detectIntent.
But my queryParams object returns me empty data, therefore the default timezone mentioned in the agent is considered. My main concern is to send TimeZone in the request. Which i am able to do with the online testing in google cloud interface https://cloud.google.com/dialogflow/docs/reference/rest/v2/projects.agent.sessions/detectIntent?apix=true. The same implementation is not working for me. What i am doing wrong? Please suggest.
/*
Modified script
All the other statements
*/
// I tried to add this code before the detectintent method to get timezone but the variable returns empty data.
// get response and relevant info
//queryParams optional adding new code before detectintent
$optionalArgs = new QueryParameters();
$optionalArgs->setTimeZone('America/New_York');
$optionalArgs->getTimeZone();
$optionArgs = (array)$optionalArgs;
$response = $sessionsClient->detectIntent($session, $queryInput, $optionArgs);// I have added $optionArgs for adding time zone
// other statements
//
// end of code

ios swift 2.1 - unable to send Patch request with body

I'm trying to write a http rest client for my webservice and i need to send some PATCH requestes with data in the body.
I'm using the JUST library for sending requests ( https://github.com/JustHTTP/Just )
My express application just doesn't see the request.
Here's some code (i'm testing in playground, and everything went fine with other kind of requests like put, post...)
headers = ["accept":"application/json","content-type":"application/json","authorization":"key"] //key is ok
var data = ["id":3, "quantity":6]
var r = Just.patch("http://api.marketcloud.it/v0/carts/1233", headers:headers, data:data) //1233 is a cart Id
print(r)
print(r.json)
The method Just.patch returns an HTTPResult Object.
this says 'OPTIONS http://api.marketcloud.it/v0/carts/13234 200'
Also this object should contain a json, but it's 'nil'.
On the server-side, my express applications doesn't receive the request (it just logs an 'OPTION', but nothing else).
Could this be a playground-related problem? Or a just-related one?
Thanks for any suggestion
I managed to contact the library's author via twitter and he fixed the bug and answered me in less than 24h!
Here's the new release of the library.
https://github.com/JustHTTP/Just/releases

"Bad request" when trying to delete a entry in a Lightswitch database

I'm trying to delete entries in my lightswitch database, from a external app.
I'm using restsharp, and the code looks like the following:
var request = new RestRequest("/FilesSet/{Id}", Method.DELETE);
request.AddParameter("Id", 8);
var resp = client.Execute(request);
Here is the full error message:
The request URI is not valid. Since the segment 'FilesSet' refers to a collection, this
must be the last segment in the request URI. All intermediate segments must refer to a
single resource.
It seems like you're trying to locate an entity and delete it. In the OData URL convention, the canonical URL for accessing an entity in a collection is as follows:
~/FilesSet({Id})
Thus, you need to modify your code as follows:
var request = new RestRequest("/FilesSet({Id})", Method.DELETE);
request.AddParameter("Id", 8);
var resp = client.Execute(request);
Reference: 4.3.1 Canonical URL

Google data API for .Net allows Sharing outside organization in Google apps account

I am using Google Data API for .Net(version 1.9) in my application.
I have created a Google apps account and i have set the "Users cannot share documents outside this organization" setting under Google Docs.
When i try to share a file outside of the domain(organization) from Google docs web, i get a error saying the file cannot be shared outside of my domain.
But when i try the same thing from the API, it succeeds. I get a 200 success from the API. When i try to access the file from the share link it says 'You need permission to access this resource'. My question is shouldn't the API return with a error? how can i handle this case?
Here is the code that I am using:
DocumentsRequest request = null;
/* request initialization */
string csBatchReqBody = "<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:gAcl="http://schemas.google.com/acl/2007" xmlns:batch="http://schemas.google.com/gdata/batch"><category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/acl/2007#accessRule"/><entry><id>https://docs.google.com/feeds/default/private/full/document:1DsELtiNwq-ogOrp8cAONdMpGR4gBF79PjijTae-vVNg/acl/user:myusername#mydomain.com</id><batch:operation type="query"/></entry><entry><batch:id>1</batch:id><batch:operation type="insert"/><gAcl:role value="reader"/><gAcl:scope type="user" value="myusername#gmail.com"/></entry>"
string Url = "https://docs.google.com/feeds/default/private/full/document:1DsELtiNwq-ogOrp8cAONdMpGR4gBF79PjijTae-vVNg/acl/batch";
byte[] byteArray = Encoding.ASCII.GetBytes(csBatchReqBody);
MemoryStream inputStream = new MemoryStream(byteArray);
AtomEntry reply = request.Service.Insert(new Uri(Url), inputStream, "application/atom+xml", "");
MemoryStream stream = new MemoryStream();
reply.SaveToXml(stream);
The API actually returns a 400 if you try to share a file outside the domain and the admins have set the "Users cannot share documents outside this organization" flag.
Your code sends a batch request (even if for a single element), you'd have to check the batch response to notice the error.
Instead, use the following code to share a document to a single user, it assumes that entry is the DocumentEntry you want to share:
AclEntry acl = new AclEntry();
acl.Scope = new AclScope("username#gmail.com", "user");
acl.Role = new AclRole("reader");
acl = service.Insert(new Uri(entry.AccessControlList), acl);

Resources