Creating new tasks with the Wrike API and VB.net - vb.net

I'm having trouble creating new Wrike tasks using VB.net and the Wrike API. I however, am able to connect to Wrike to GET a list of folders so I know I'm able to successfully authenticate.
Link to task creation docs:
https://developers.wrike.com/documentation/api/methods/create-task
The only required field is "Title"
Dim accessToken As String = API_Token
Dim apiVersion As String = "v4"
Dim ApiBaseUrl As String = "https://www.wrike.com"
Dim folderID As String = "Some Folder ID Here"
Dim address As String = ApiBaseUrl & "/api/" & apiVersion & "/folders/" & folderID & "/tasks"
Dim result As String
Dim task_str_ As String = "importance=Normal&description=Test task description&dates={""start"":""2019-07-24"",""due"":""2019-07-30""}&title=Task Created With VS&status=Active"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "PUT"
request.ContentType = "application/json"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write(task_str_)
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch ex As Exception
TextBox1.Text = ex.ToString
End Try
Here is the error I'm receiving:
System.Net.WebException: The remote server returned an error: (400) Bad Request

Once I made the suggested changes, everything works good.
Dim accessToken As String = API_Token
Dim apiVersion As String = "v4"
Dim ApiBaseUrl As String = "https://www.wrike.com"
Dim folderID As String = "Some Folder ID Here"
Dim address As String = ApiBaseUrl & "/api/" & apiVersion & "/folders/" & folderID & "/tasks"
Dim result As String
Dim task_str_ As String = "importance=Normal&description=Test task description&dates={""start"":""2019-07-24"",""due"":""2019-07-30""}&title=Task Created With VS&status=Active"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "POST"
request.ContentLength = task_str_.Length
request.ContentType = "application/x-www-form-urlencoded"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write(task_str_)
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch ex As Exception
TextBox1.Text = ex.ToString
End Try

Related

I created this code in Visual.Net and it gives an error message This is the error

I created this code in VB.Net and it gives an error message. This is the error in this sentence Dim resp As Dynamic = JObject.Parse(response.Content).
Private Function GetBearerToken() As String
Try
Dim client = New RestClient(Config_class.tokenurl)
Dim request = New RestRequest(Method.POST)
request.AddHeader("cache-control", "no-cache")
request.AddHeader("content-type", "application/x-www-form-urlencoded")
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=" & client_id & "&client_secret=" + client_secret, ParameterType.RequestBody)
Dim response As IRestResponse = client.Execute(request)
Dim resp As Dynamic = JObject.Parse(response.Content)
Dim token As String = resp.access_token
Return token
Catch ex As Exception
End Try
Return ""
End Function
Private Function GetBearerToken() As String
Try
Dim client = New RestClient(Config_class.tokenurl)
Dim request = New RestRequest(Method.POST)
request.AddHeader("cache-control", "no-cache")
request.AddHeader("content-type", "application/x-www-form-urlencoded")
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=" & client_id & "&client_secret=" + client_secret, ParameterType.RequestBody)
Dim response As IRestResponse = client.Execute(request)
Dim resp As Dynamic = JObject.Parse(response.Content)
Dim token As String = resp.access_token
Return token
Catch ex As Exception
End Try
Return ""
End Function
What is 'Dynamic'? Try 'JObject' as the type, according to the documentation for JObject:
Dim resp As JObject = JObject.Parse(response.Content)

VB.NET ~ PUT WebRequest raising exceptions when trying to GetResponse of it

I am getting TWO exceptions. The first one in the regular code and the second into the exception handling block.
I have this function (below) that supposed to change user settings in a Web API using PUT method. Everything runs fine until the point that I try to get a response from the web request. Then it raises the first exception (unknown) and when I try to handle the error I get a second exception "Object reference not set to an instance of an object".
As far as I know normally what will cause this error is the attempt of getting a response of an unassigned web request, but in this case it IS assigned and the Uri is valid. All the credentials for authorization are correct too.
This is my code:
Try
Dim webRequest As System.Net.HttpWebRequest
webRequest = System.Net.HttpWebRequest.Create(InternalSettings.APIurl + "/config")
webRequest.Headers("Authorization") = InternalSettings.APIpwd
webRequest.Headers("API-Application-Key") = InternalSettings.APIkey
webRequest.Method = "PUT"
webRequest.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = ""
postData += "SaveAllCustomersData=false"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
'The next line will raise an unknown exception
Dim myHttpWebResponse As HttpWebResponse = webRequest.GetResponse
Dim responseReader As StreamReader = New StreamReader(myHttpWebResponse.GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest.GetResponse().Close()
Catch ex As WebException
'The next line will raise a "Object reference not set to an instance of an object" exception
Dim resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
Dim obj = JsonConvert.DeserializeObject(resp)
Return False
End Try
If you are using basic authentification you can try something like this:
Dim strUrl As String = InternalSettings.APIurl + "/config"
Dim request As WebRequest = DirectCast(WebRequest.Create(strUrl), HttpWebRequest)
Dim strResponse As String = ""
Dim byteAuth() As Byte = Encoding.UTF8.GetBytes(InternalSettings.APIkey & ":" & InternalSettings.APIpwd)
Dim strPost As String = "SaveAllCustomersData=false"
Dim bytePost() As Byte = Encoding.UTF8.GetBytes(strPost)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "PUT"
request.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(byteAuth))
Using sw = New StreamWriter(request.GetRequestStream())
sw.Write(bytePost, 0, bytePost.Length)
sw.Flush()
Using response As HttpWebResponse = request.GetResponse()
Using sr = New StreamReader(response.GetResponseStream())
strResponse = sr.ReadToEnd()
End Using
End Using
End Using

Can we call JSON POST API from VB.NET Windows App?

Here I am always getting "The remote server returned an error: (500) Internal Server Error.". Even the API is correct and working nicely through POSTMAN and in other languages also. Please guide me so solve this issue. I am attaching the function which is calling the API directly.
Private Function SendRequest() As String
Dim response As String
Dim request As WebRequest
Dim encoding As New System.Text.ASCIIEncoding
Dim uri = ""
Dim Tran = "15"
Dim Amount As Integer = 1000
Dim ReferenceID = "015bfa15-15ec-4dc7-903c-053ffacb6688"
Dim POS = "57290070"
Dim Store = "RESTSIM00000001"
Dim Chain = "J#P-Reg"
Dim JSONString = "{""tran"":""" & Tran & """,""amount"":""" & Amount & """,""reference"":""" & ReferenceID & """,""pos"":""" & POS & """,""store"":""" & Store & """,""chain"":""" & Chain & """}"
Dim jsonDataBytes() As Byte = encoding.GetBytes(JsonConvert.SerializeObject(JSONString))
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = "application/json"
request.Method = "POST"
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

Context type error http post visual basic

I have been trying to send an HTTP post to a web service and got this message:
"The 'Content-Type' header must be modified using the appropiat
property or method, Parameter nama:name"
This happens when i try to update a customer with this JSON fotmat :
{"display_name":"john smith","email":"johnsmith#something","company_name":"enterprise"}
This is a part of the code i have been using to connect to the API:
Dim sUrl As String = "https://subscriptions.zoho.com/api/v1/customers"
Dim wHeader As WebHeaderCollection = New WebHeaderCollection()
Dim wRequest As HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(sUrl), HttpWebRequest)
wHeader.Clear()
wHeader.Add("Authorization: Zoho-authtoken 7ca5747efb3be868e155e707e679f9f5")
wHeader.Add("X-com-zoho-subscriptions-organizationid: 397080968")
wHeader.Add("Content-Type: application/json;charset=UTF-8")
wRequest.Accept = "application/json"
MsgBox(wHeader.ToString)
wRequest.Headers = wHeader
wRequest.Method = "POST"
Dim postData As String = sw.ToString
MsgBox(postData)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
wRequest.ContentLength = byteArray.Length
Dim dataStream As Stream = wRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = wRequest.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
LblResponse.Text = sResponse
Console.WriteLine(sResponse)
reader.Close()
dataStream.Close()
response.Close()
Catch ex As Exception
If ex.InnerException IsNot Nothing Then
LblResponse.Text = ex.Message + " >> " + ex.InnerException.ToString()
Else
LblResponse.Text = ex.Message
End If
End Try
any ideas ?

Prestashop - Unable to upload a new image product with the prestashop 1.6 webservice

I'm trying to upload a new image for a product with the prestashop webservice through a vb .net application, but I get the following error message:
"Unable to save this image".
The URL used to upload the image is this: http://localhost/prestashop/api/images/products/1
And the source code of the function that make the request is this:
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Image)
Dim response As String = Nothing
Try
Dim ms As New MemoryStream()
imageToAdd.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim byteArray As Byte() = ms.ToArray()
Dim requestUrl As String = Me.WebServiceURL & "/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.Method = WebServicePrestashop.CRUDMethod.Create
'webRequest.ContentType = "image/jpeg"
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = byteArray.Length
MsgBox(byteArray.Length)
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)
Dim imageNew As Image = Image.FromStream(webResponse.GetResponseStream())
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub
I'm using the HTTP POST method, and the POST content is the bynary content of the new image.
How can I fix it?.
Here the solution.
I think the key is that I must write the body of the webrequest programatically adding to the stream of the webrequest the boundary (in binary array format), the Content-Type chain (in binary array format) and the content of the image to upload (in binary array format).
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Byte())
Dim response As String = Nothing
Try
Dim requestUrl As String = "urlShop" & "/api/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.KeepAlive = True
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = imageToAdd.Length
webRequest.Method = "POST"
webRequest.ContentType = "image/jpeg"
Dim boundary As String = "----" & DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture)
webRequest.ContentType = "multipart/form-data; boundary=" & boundary
Dim beginPostData = "--" & boundary & vbCrLf & "Content-Disposition: form-data; name=""image""; filename=""torrente.jpg""" & _
vbCrLf & "Content-Type: image/jpeg" & vbCrLf & vbCrLf
Dim boundaryBytes = System.Text.Encoding.ASCII.GetBytes(vbCrLf & "--" & boundary & "--" & vbCrLf)
Dim beginPostDataBytes = System.Text.Encoding.ASCII.GetBytes(beginPostData)
webRequest.ContentLength = beginPostData.Length + imageToAdd.Length + boundaryBytes.Length
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(beginPostDataBytes, 0, beginPostDataBytes.Length)
dataStream.Write(imageToAdd, 0, imageToAdd.Length)
dataStream.Write(boundaryBytes, 0, boundaryBytes.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream())
response = reader.ReadToEnd()
MsgBox(response)
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub