Upload file in BOX using BOX API using C# - box-api

I have BOX account and in API document
curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer ACCESS_TOKEN" \
-F filename=#FILE_NAME \
-F parent_id=PARENT_FOLDER_ID
I am stuck with this filename and parent_id how to pass the filename and parent_id
i have tried lots of way, but nothing is working for me.
Following is the code:
httpWReq.Method = "POST";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "multipart/form-data";
//{\"parent_id\":\""+parentID +"\"}
//byte[] file = File.ReadAllBytes(postData);
httpWReq.ContentLength = data.Length;
using (Stream reqStream = httpWReq.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
//reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse())
{
//Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
response.Close();
}
Need Help
Thanks in Advance

Vaibhav,
Please see example of how official Box C# SDK is doing upload:
https://github.com/box/box-windows-sdk-v2/blob/master/Box.V2/Managers/BoxFilesManager.cs
Is there any reason why you don't want to use Box Windows SDK?

Related

Jenkins Multibranch Pipeline check only the new or changed files pushed to GIT

we are working with a tool where the elements are all written via .json.
Currently my GIT folder structure looks like this:
elementsfolder -> element1.json, element2.json, element3.json
scriptsfolder -> e.g. transformation.py
testfolder -> run-element.sh
Jenkinsfile
The problem I have now is that the .json files in folder elementsfolder should be tested with the bashscript from the testfolder and (if necessary) a script like transformations.py should be called. This also works so far, but all .json files are always tested (no matter if unchanged or not). But this should not be the case. Only the elements that are either changed or newly created should be tested. We have at the end of the day over 6000 elements, accordingly, the test over all elements would be too costly. Can anyone help me with this? In Jenkins the pipeline looks like this (I only post the stage build, because test and deploy are similar):
stages {
stage('Build') {
environment {
CREDS = credentials('creds')
ENDPOINT = 'automation-api'
}
steps {
sh '''
username=$USR
password=$PSW
# Login curl
login=$(curl -k -s -H "Content-Type: application/json" -X POST -d \\{\\"username\\":\\"$username\\",\\"password\\":\\"$password\\"\\} "$ENDPOINT/session/login" )
token=$(echo ${login##*token\\" : \\"} | cut -d '"' -f 1)
# Build
#1. Validation .json
curl -k -s -H "Authorization: Bearer $token" -X POST -F "definitionsFile=#element/*.json" "$ENDPOINT/build"
#2. Show Error
curl --show-error --fail -k -s -H "Authorization: Bearer $token" -X POST -F "definitionsFile=#element/*.json" "$ENDPOINT/build"
#3. Logout
curl -k -s -H "Authorization: Bearer $token" -X POST "$ENDPOINT/session/logout"
'''
}
}
If you are checking out from an SCM Jenkins will allow you to check the Changeset between the last build and the current build. So basically you can first try to find the files that really changed and then use only those files. Refer to the following example. After getting the list of files that changed you can either move them to a new directory or delete the unchanged files from the elementsfolder. The following sample getFilesChanged will return a list of all the changed/added files in the repo. You may want to tweak this function to match your requirement.
pipeline {
agent any
stages {
stage('clone') {
steps {
git branch: 'main', url: 'https://github.com/xxx/sample.git'
}
}
stage('build') {
steps {
script {
println(getFilesChanged())
// Do your cleanup here and then execute the SH block
}
}
}
}
}
def getFilesChanged() {
def filesList = []
def changeLogSets = currentBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
def files = new ArrayList(entry.affectedFiles)
for (int k = 0; k < files.size(); k++) {
def file = files[k]
filesList.add(file.path)
}
}
}
return filesList
}

Jenkins : Extract data from Jira curl

I use a curl to get the status of a Jira issue :
result = sh(returnStdout: true, script: """curl -D- -k -u $JIRA_LOGIN:$JIRA_PWD -X GET -H "Content-Type: application/json" $url""")
This returns a String like :
{"expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations","id":"*****","self":"*****","key":"*****","fields":{"status":{"self":"*****","description":"Issues in development","iconUrl":"****","name":"DEVELOPMENT","id":"10400","statusCategory":{"self":"****","id":4,"key":"indeterminate","colorName":"yellow","name":"In Progress"}}}}
How I can extract the data "DEVELOPMENT" in this string ? I try to parse it in JSON but it's not working :
status_json = new JsonSlurper().parse(result)
with the error "java.io.NotSerializableException: groovy.json.JsonSlurper"
You can check out the JsonSlurper's documentation:
Jira holds all issue fields under the "fields" key in JSON. So, after you get the JSON, you just need to go to the fields.status.name in order to get "DEVELOPMENT" text.
Here's a simple approach:
def jsonSlurper = new JsonSlurper()
def issueObj = jsonSlurper.parseText('...') // Your Jira response will be here
issueObj.fields.status.name // It will give you the status' name.

How to parse a simple JSON object (accessing single elements)?

I'm trying to process simple JSON data in a Google-Apps-Script (a Webhook Receiver). For a test I send data from the console:
curl -d "{"result":true,"count":42,"exchange":"Kroakex"}" -H "Content-Type: application/json" -X POST https://script.google.com/macros/s/xxx/exec
... but I can't access the json elements in my processing function:
function doPost(e) {
var jsonString = JSON.stringify(e.postData.contents);
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj); // ---> "{result:true,count:42,exchange:Kroakex}"
console.log(jsonObj.count); // ---> "undefined"
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
sheet.insertRowAfter(lastRow);
sheet.getRange(lastRow + 1, 1).setValue(jsonObj['count']); // ---> nothing
sheet.getRange(lastRow + 1, 2).setValue(jsonObj['exchange']); // ---> nothing
sheet.getRange(lastRow + 1, 3).setValue(jsonObj); // ---> {result:true,count:42,exchange:Kroakex}
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
When I instead create the JSON string manually with this line, it all works fine:
const jsonString = '{"result":true, "count":42, "exchange":"Kroakex"}';
Can anyone help?
I would like to propose the following modification.
Modification points:
I think that in your curl command, there are the modification points.
When your curl command is used, e.postData.contents is "{result:true,count:42,exchange:Kroakex}". Because at -d "{"result":true,"count":42,"exchange":"Kroakex"}", " is used in "{,,,}". In this case, your Google Apps Script cannot parse the values as JSON object. Please escape " or enclose by '. By this, e.postData.contents becomes "{\"result\":true,\"count\":42,\"exchange\":\"Kroakex\"}".
In this case, please use -L and -X POST is not required.
The modified curl command is as follows.
curl -L -d '{"result":true,"count":42,"exchange":"Kroakex"}' -H "Content-Type: application/json" https://script.google.com/macros/s/###/exec
or
curl -L -d "{\"result\":true,\"count\":42,\"exchange\":\"Kroakex\"}" -H "Content-Type: application/json" https://script.google.com/macros/s/###/exec
By above modification, your Google Apps Script becomes as follows.
Modified script:
function doPost(e) {
var jsonObj = JSON.parse(e.postData.contents); // <--- Modified
console.log(jsonObj);
console.log(jsonObj.count);
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
sheet.insertRowAfter(lastRow);
sheet.getRange(lastRow + 1, 1).setValue(jsonObj['count']);
sheet.getRange(lastRow + 1, 2).setValue(jsonObj['exchange']);
sheet.getRange(lastRow + 1, 3).setValue(JSON.stringify(jsonObj)); // <--- Modified
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
When you use the curl command, I think that the returned value might be suitable for return ContentService.createTextOutput("post request received"); instead of return HtmlService.createHtmlOutput("post request received");.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Added:
When you want to access to Web Apps using the URL of https://script.google.com/macros/s/###/dev, it is required to use the access token. The modified curl command is as follows.
curl -L \
-H "Authorization: Bearer ### access token ###" \
-H "Content-Type: application/json" \
-d '{"result":true,"count":42,"exchange":"Kroakex"}' \
"https://script.google.com/macros/s/#####/dev"
In this case, https://www.googleapis.com/auth/drive.readonly and https://www.googleapis.com/auth/drive can be used for the scope.
Reference:
How to use dev mode from outside

Need to code a CURL command to VB.net

I need to code this Curl/json command on VB.net. I am not sure how to use HttpWebRequest. Please HELP!!!
curl -X GET --header "Accept: /" --header "X-Auth-Token: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTc3NTQ1" "http://staging-exact-integration.posios.com/PosServer/rest/core/company"
HttpClient is what you're after.
To add headers, you simply create a custom HttpRequestMessage:
Dim client As New HttpClient()
Dim request As New HttpRequestMessage() With
{
.RequestUri = New Uri("http://staging-exact-integration.posios.com/PosServer/rest/core/company"),
.Method = HttpMethod.Get,
}
request.Headers.Add("X-Auth-Token", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTc3NTQ1")
Dim result = client.SendAsync(request).Result

How can I POST JSON data to a remote server in Laravel 4?

I am trying to HTTP POST JSON encoded data to a remote server.
Using cURL, this would be done as
curl -X POST -H "Content-Type: application/json" -d '{"name":"Jeff"}' http://somesite/someuri
I can not find a Laravel approach to doing this.
[ * * * UPDATE: My Solution * * * ]
I ended up using PHP's HttpRequest
$httpRequest_OBJ = new httpRequest($server, HTTP_METH_POST, NULL);
$httpRequest_OBJ->setBody($jsonEncodedData);
$httpRequest_OBJ->setContentType('application/json');
$result = $httpRequest_OBJ->send();
$reply = $result->getBody();
In this SO post I answered a very similar question, and it's a direct solution to your problem, please follow the link for detailed instructions.
How to send JSON by POST in Laravel 4 via CURL (jyggen/curl)
To put it in a nutshell, after you install the jyggen/curl package in your laravel app with composer, all you have to do is:
use jyggen\Curl;
$url = "http://some.url/"; //the gateway to which you want to post the json payload
$file = 'path/to/file.json';
$data = File::get($file); //or wherever else you get your json from
$request = new Request($url); // jyggen\Curl\Request
$request->setOption(CURLOPT_FOLLOWLOCATION, true);
$request->setOption(CURLOPT_RETURNTRANSFER, true);
$request->setOption(CURLOPT_POST, true);
$request->setOption(CURLOPT_POSTFIELDS, $data);
$request->setOption(CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
);
$request->execute();
if ($request->isSuccessful()) {
return $request->getRawResponse();
} else {
throw new Exception($resquest->getErrorMessage());
}
Above #Gadoma example works pretty well in Laravel 5 also. But I had to change use to:
use Jyggen\Curl\Request;
and also remove line:
$request->setOption(CURLOPT_RETURNTRANSFER, true);
since there were some errors. Now it works like charm.