How to convert this CURL request to VB.NET code - vb.net

I am trying to upload a file to MixCloud using their API. In their documentation following curl request is the only example. I want this request to convert to VB.net WebRequest or other method. I need it in VB.net language. I tried everything including HttpResponseMessage but it reruns an error like bad request. Please help.
curl -F mp3=#upload.mp3 \
-F "name=API Upload" \
-F "tags-0-tag=Test" \
-F "tags-1-tag=API" \
-F "sections-0-chapter=Introduction" \
-F "sections-0-start_time=0" \
-F "sections-1-artist=Artist Name" \
-F "sections-1-song=Song Title" \
-F "sections-1-start_time=10" \
-F "description=My test upload" \
https://api.mixcloud.com/upload/?access_token=INSERT_ACCESS_TOKEN_HERE

I added VB.net code created using the method mentioned by #Martheen and I found the solution. Also I had to add
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
To allow TLS
This is final working code
Public Async Sub Upload(username As String, fileName As String, songTitle As String, description As String, accessToken As String)
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Using httpClient = New HttpClient()
Using request = New HttpRequestMessage(New HttpMethod("POST"), "https://api.mixcloud.com/upload/?access_token=" & accessToken)
Dim multipartContent = New MultipartFormDataContent()
multipartContent.Add(New ByteArrayContent(File.ReadAllBytes(fileName)), "mp3", Path.GetFileName(fileName))
multipartContent.Add(New StringContent(songTitle), "name")
multipartContent.Add(New StringContent(description), "description")
request.Content = multipartContent
Dim response = Await httpClient.SendAsync(request)
End Using
End Using
Catch ex As Exception
MsgBox(ex.InnerException.Message)
End Try
End Sub

Related

use HttpClient (POST) in vb.net to write data to InfluxDB v2.4

I want to do this (works):
curl --request POST "http://192.168.1.99:8086/api/v2/write?org=db1&bucket=data&precision=ns" --header "Authorization: Token 12345..." --header "Content-Type: text/plain; charset=utf-8" --header "Accept: application/json" --data-binary "solar,mytag=1 cwatt=125"
in vb.net without using influx library. I tried this:
Dim httpClient As HttpClient = New HttpClient()
Dim DAhttpContent As StringContent = New StringContent("solar,mytag=1 cwatt=222", Encoding.UTF8, "text/plain")
DAhttpContent.Headers.Add("Authorization:", "Token 12345...")
DAhttpContent.Headers.Add("Content-Type:", "text/plain; charset=utf-8")
DAhttpContent.Headers.Add("Accept:", "application/json")
Dim response = httpClient.PostAsync("http://192.168.1.99:8086/write?db=data&u=user1&p=writewrite1", DAhttpContent)
Error-> System.FormatException: "The header name format is invalid."
So I read many topics here on overflow and tried something else:
Private Shared Async Function Main3() As Task
Using xclient As HttpClient = New HttpClient()
Dim request_json = "solar,mytag=1 cwatt=222"
Dim content = New StringContent(request_json, Encoding.UTF8, "text/plain")
Dim authenticationBytes = Encoding.ASCII.GetBytes("12345...")
xclient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", Convert.ToBase64String(authenticationBytes))
xclient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim result = Await xclient.PostAsync("http://192.168.1.99:8086/api/v2/write?org=db1&bucket=data&precision=ns", content)
'Dim result_string As Task(Of String) = result.Content.ReadAsStringAsync() '<- Error "Content is no Member of Task(Of HttpResponseMessage)"
End Using
End Function
It runs without any error but also does not writes any data. So my problems are:
how to authenticate in Header correctly?
wait/return response outside Async function
Maybe it's easier to do by UDP (8089) packet transmission?
Any vb.net code example would be very helpful for me.
(I also cheked many similar questions here before.)
Thanks in advance!

How should a GraphQL request for file upload look like?

I use Graphene on the server side with similar code to the one from documentation:
class UploadFile(graphene.ClientIDMutation):
class Input:
pass
# nothing needed for uploading file
# your return fields
success = graphene.String()
#classmethod
def mutate_and_get_payload(cls, root, info, **input):
# When using it in Django, context will be the request
files = info.context.FILES
# Or, if used in Flask, context will be the flask global request
# files = context.files
# do something with files
return UploadFile(success=True)
It's all clear, but how should the request look like ?
I've seen people suggesting multipart/form-data, but AFAIK that requires additional layer to parse the multipart request, so that's probably not what I need.. or is it ? :
curl -X "POST" "http://127.0.0.1:5001/graphql" \
-H 'Content-Type: multipart/form-data; boundary=----GraphQLFileUpload' \
-F "operations={\"query\":\"mutation ($files: [Upload!]!) {uploadFile(selfie: $file) {status}}\",\"variables\":{}}" \
-F "map={\"x\":[\"variables.files.x\"]}" \
-F "x=#/tmp/dummy.jpg "
I'll reply myself. The curl code I had was based on an external library that confused the hell out of me.
Here's my solution that doesn't require any additional library:
Python server code (graphene):
class UploadImage(graphene.Mutation):
class Arguments(object):
file = graphene.String(required=True)
status = graphene.Boolean()
def mutate(self, info, file):
img = info.context.files[file].read()
# more stuff
return UploadImage(status=True)
Curl request (multipart form)
curl -X POST http://localhost:5001/graphql \
-H 'content-type: multipart/form-data; boundary=----GraphQlFileUpload' \
-F 'query=mutation {uploadImage(file: "photo") {status}}' \
-F 'photo=#selfie.jpg'

ERROR: The remote server returned an error: (400) Bad Request

I am using aspx vb .net to connect with instagram api
I am using the following link as references: https://code.msdn.microsoft.com/Haroon-Said-e1d8d388
ERROR: The remote server returned an error: (400) Bad Request.
It is weird becuase i followed all steps and imported json as showed in above link. any idea? below is my code:
Dim json As String = ""
Try
Dim parameters As New NameValueCollection
parameters.Add("client_id", Client_ID)
parameters.Add("client_secret", ClientSecret)
parameters.Add("grant_type", "authorization_code")
parameters.Add("redirect_uri", Redirect_URI)
parameters.Add("code", Code)
Dim client As WebClient = New WebClient()
Try
'ERROR HERE
Dim result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters)
...
Catch ex As Exception
labelTest.Text += "---" & ex.Message
End Try
Thanks. yeah I been working on this for couple months now and trying to debug but I just have no idea whats going on. I mean I looked at insta api webbsite sill no luck. I tested my values also and they seem to be correct:
curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
client_secret = f208d9fc9cec4b69bdd5f8f1386a
client_secret = d836619eede4490fd12983b95961
grant_type = authorization_code
redirect_uri = http://localhost:1861/UI/Home.aspx
code = 6185508825da0c28a33ac5dcc77
note, 'code' i am getting when when user logs into insta. I used the following url to get the code:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
I know authorize is correct becuase it gives me code in url
solved!
just changed response_type from code to token... it will give you access_token

How to translate this cURL command to a VB?

I'm trying to translate the following cURL command that extrats a .diff content in GitHub to VB:
curl -H 'Authorization: token myGitHubToken' -H "Accept: application/vnd.github.v3.diff" https://api.github.com/repos/[USR]/[REPO]/commits/[COMMITID]
The cURL works fine. And my code in VB with HttpWebRequest is
Dim url As New Uri("https://api.github.com/repos/[USR]/[REPO]/commits/[COMMITID]")
Dim myReq As HttpWebRequest = HttpWebRequest.Create(url)
SetAllowUnsafeHeaderParsing20()
myReq.Headers.Add("Authorization: token myGitHubToken")
myReq.Accept("application/vnd.github.v3.diff")
myReq.KeepAlive = False
Dim response As HttpWebResponse = CType(myReq.GetResponse(), HttpWebResponse)
But in GetResponse, throws me a WebException :
"The remote server returned an error: (403) Forbidden"
Is ok my traslation? There is something wrong?

How can i update a jenkins job using the api

I have to create/update a jenkins job using its api because all of my jobs are using parameters which are also used by other scripts and I am trying to centralize the scripts so when i change it in one place, the change reflects in all.
currently, if someone changes the script, they they also have to manually edit the parameters of the jenkins job as well.
I saw the example of the Remote API for creating jobs and was able to successfully create test jobs but how can i edit an existing job besides deleting it and creating it again(which isnt an option as i have to maintain the build history).
You could use python like this:
from jenkinsapi.jenkins import Jenkins
jenkinsSource = 'http://10.52.123.124:8080/'
server = Jenkins(jenkinsSource, username = 'XXXXX', password = 'YYYYY')
myJob=server.get_job("__test")
myConfig=myJob.get_config()
print myConfig
new = myConfig.replace('<string>clean</string>', '<string>string bean</string>')
myJob.update_config(new)
in case anyone else is also looking for the same answer,
It appears the solution is far easier, all you have to do is update the config.xml and post the updated config.xml back to jenkins and your job will be updated.
You can also POST an updated config.xml to the URL which can fetch config.xml, to programmatically update the configuration of a job.
The fetch url pattern: $JENKINS_SERVER/job/$JOB_NAME/config.xml
detailed doc pattern: $JENKINS_SERVER/job/$JOB_NAME/api
example: https://ci.jenkins-ci.org/job/infra_atlassian-base/api/
http://asheepapart.blogspot.ca/2014/03/use-jenkins-rest-api-to-update-job.html
That little bit of scripting looks to be what you are looking for. Uses the REST API to get and set the config with some regex S&R in the middle.
Edit: Code below based on comment. It is copied directly from the blog so I take no credit for it.
# First, get the http://jenkins.example.com/job/folder-name/job/sample-job--template/configure looking like you want
read -s token
# type token from http://jenkins.example.com/user/$userName/configure
# Download the configuration XML for the template job (which will be our model template)
curl -v -u "bvanevery:$token" http://jenkins.example.com/job/folder-name/job/sample-job--template/config.xml > generic-config.xml
# My modules
declare modules=('module1' 'module2' 'module3')
# POST the updated configuration XML to Jenkins
for m in ${modules[#]}; do
echo "module $m";
sed "s/MODULE/$m/g" generic-config.xml > $m-config.xml;
curl -v -X POST --data-binary #$m-config.xml -u "bvanevery:$token" \
-H 'Content-Type: application/xml' \
"http://jenkins.example.com/job/folder-name/job/$m/config.xml" ;
done
For those using RestSharp, I found that I needed to make sure that:
The user ID performing the update had permission to do so under Manage > Global Security > Authorization Matrix
I had a current Jenkins Crumb token, required once CSRF (also under Manage > Security) is enabled.
Send the updated XML using a parameter of the Request object with the value of [ParameterType.RequestBody] (link)1 for the type argument.
private XmlDocument JobConfigGet()
{
Uri JobConfigURI = GetJenkinsURI("job/" + _args.JobName + "/config.xml", null);
RestClient restClient = new RestClient(JobConfigURI);
RestRequest restRequest = new RestRequest(Method.GET);
byte[] ua = Encoding.ASCII.GetBytes(Properties.Settings.Default.UserID + ":" + Properties.Settings.Default.UserPassword);
restRequest.AddHeader("authorization", "Basic " + Convert.ToBase64String(ua));
IRestResponse restResponse = restClient.Execute(restRequest);
if (restResponse.ResponseStatus != ResponseStatus.Completed || restResponse.StatusCode != HttpStatusCode.OK)
throw new Exception(string.Format("Unable to retrieve job config: {0}. Wrong ResponseStatus ({1}) or StatusCode ({2}) returned.\nURL: {3}", _args.JobName, restResponse.ResponseStatus.ToString(), restResponse.StatusCode.ToString(), restClient.BaseUrl.AbsoluteUri));
if (restResponse.ContentType != "application/xml")
throw new Exception("Unexpected data type returned for job config: " + _args.JobName + ". Expected 'application/xml'. Got: " + restResponse.ContentType + ".\nURL: " + restClient.BaseUrl.AbsoluteUri);
XmlDocument jobConfig = new XmlDocument();
jobConfig.LoadXml(restResponse.Content);
return jobConfig;
}
private void JobConfigUpdate(XmlDocument JobConfig, string JenkinCrumb)
{
// Update JobConfig XML as needed here.
Uri JobConfigURI = GetJenkinsURI("job/" + _args.JobName + "/config.xml", null);
RestClient restClient = new RestClient(JobConfigURI);
RestRequest restRequest = new RestRequest(Method.POST);
byte[] ua = Encoding.ASCII.GetBytes(Properties.Settings.Default.UserID + ":" + Properties.Settings.Default.UserPassword);
restRequest.AddHeader("authorization", "Basic " + Convert.ToBase64String(ua));
string[] crumbSplit = JenkinCrumb.Split(':');
restRequest.AddHeader(crumbSplit[0], crumbSplit[1]);
restRequest.AddParameter("text/xml", JobConfig.InnerXml, ParameterType.RequestBody);
IRestResponse restResponse = restClient.Execute(restRequest);
string resp = restResponse.Content;
}
curl -v -X POST https://jenkinsurl.fr:8443/job/jobname/config.xml --data-binary "#config.xml" -u "jenkinsusername:yourjenkinstoken" -H "Content-Type: application/xml"