How to create a task in asana with bold description? - asana

I am able to create Project / task / attachment fine with Asana API with PHP.
Is there a way to create Bold for Emphasis description for task / project ?
I could not find that in Asana API.
Can someone point me to right direction?

I can confirm that if you send in html_notes instead of notes you will be able to use SOME html tags. The html tags that is valid is not documented, so you will have to test to find working tags.
"html_notes": "<strong>This will be bold in Asana</strong>"
I used the following with success when creating a task within a Workspace and a project. Note that this is using WebRequest in a ASP.NET WebApi (C#). But the Json string should work just fine with your project :)
IMPORTANT: Do not encode the html before POST.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://app.asana.com/api/1.0/tasks");
httpWebRequest.Method = "POST";
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Headers.Add("Authorization", "Bearer <PERSONAL_TOKEN>");
httpWebRequest.ContentType = "application/json";
string json = "{\"data\": {\"workspace\": \"123456789\",\"html_notes\": \"<strong>" + question.Message + "</strong>\",\"name\": \"" + Username + "\",\"projects\": \"123456789\"}}";
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}

A simple way using ASANA API's use this..
URL : https://app.asana.com/api/1.0/tasks
Method : POST
HEADER : Authorization:Bearer <your token>
Content-Type:application/json
Accept:application/json
Body :
{
"data": {
"approval_status": "pending",
"assignee": "1111----572318",
"assignee_status": "upcoming",
"due_on": "2019-09-15",
"followers": [
"31441----023","1617----554125"
],
"html_notes": "<body>Looking how can i create task under a <strong>project</strong></body>",
"name": "Task created form Postman - 3",
"workspace": "11288-----8660",
"projects":["1185----23561"]
}
}
Sample

Related

Graph API not allowing online meetings

I am currently setting up a web page where users can send event requests to others using the Microsoft Graph api. I would like users to be able to send an online meeting request and then provide the options of ms teams and Skype.
However as soon as I add the property 'isOnlineMeeting' and/or 'onlineMeetingProvider' I will always return an error 400 with a bad request. This is because the property doesn't exist on the /me/events.
(the response)
I have no idea why however, currently I am using the microsoft graph explorer to test the request.
I have made sure that every permission is needed to send an invite:
Calendar.Read
Calendar.Read.Shared
Calendar.ReadWrite
Calendar.ReadWrite.Shared
If a meeting is sent without these properties it works fine. I have created other personal outlook accounts and it works as expected with this property. I have asked other people in my org to try too and theirs works fine.
Does this mean that my ms account is broken in some way? if so how could I fix it in order to send this request.
Try this:
var body= "{email body};
var string = "{\"subject\": \"Join the Teams Meeting\", \"body\": {\"contentType\": \"HTML\", \"content\": \"" + body + "\" }, \"start\": {\"dateTime\": \"2020-09-28T19:30:34\",\"timeZone\": \"Pacific Standard Time\" }, \"end\": { \"dateTime\": \"2020-09-28T20:00:34\", \"timeZone\": \"Pacific Standard Time\"}, \"location\":{ \"displayName\":\"Team meeting\" }, \"attendees\": [ { \"emailAddress\": { \"address\":\"xxxx#in.xxx.com\", \"name\": \"xxxx xxxx\" }, \"type\": \"required\" } ],\"allowNewTimeProposals\": \"true\"}";
client = new RestClient("https://graph.microsoft.com/v1.0/me/events");
request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("accept-language", "en");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", string, ParameterType.RequestBody);
response = client.Execute(request);
To generate token:
var client = new RestClient("https://login.microsoftonline.com/{tenant-Id}/oauth2/v2.0/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("grant_type", "password");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&client_id={client-Id}&client_secret={client-secret}&scope={scopeurl}&userName={username}&password={password}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var json = response.Content;
var JSONObject = JObject.Parse(json);
var token = (string)JSONObject["access_token"];

404 Error on Google Sheets API from HTTP Request

I am trying to append some data to a Google Sheets spreadsheet using a HTML POST Request. I am having some difficulty in solving the 404 error I get when sending the request. My request code is shown below:
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == XMLHttpRequest.DONE) {
alert(httpRequest.status);
}
}
var params = {
"values": [
[
"value1",
"value2"
]
]
}
httpRequest.open('POST', 'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetID + 'values/Sheet1!B2:L2:append', true)
httpRequest.setRequestHeader('Authorization', 'Bearer ' + accessToken);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.send(JSON.stringify(params));
I have gained the necessary permissions in the access token, since I am able to create sheets, but I think there might be an issue with my url. Thanks in advance!
From the documentation sheets.append
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}:append
I think you are missing a / before values
'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetID + '/values/Sheet1!B2:L2:append', true)
Try testing it using the Try this api on the documentation page here

Google Machine Learning API Issue

I'm trying to use the Google Machine Learning API and I'm facing two problems.
In the API explorer I put the correct information and I get a response error:
Code 200
"error": "Missing \"instances\" field in request body: {\n \"httpBody\": \n
{\n \"data\": \"\\"instances\\" : \\"teste\\"\",\n
\"contentType\": \"application/json\"\n }\n}"
The request find my model (if I change the value in field name I get another error) but don't understand my json. That's the json:
{"instances" : [{"key":"0", "image_bytes": {"b64": "mybase64"} }]}
When I do the predict on the command line using gcloud, I get no errors and everything seems ok. The Json that I was create for gcloud is a little bit different:
{"key":"0", "image_bytes": {"b64": "mybase64"} }
I already tryied that one in the API explorer and no success.
So, I decided to use the .Net Api to try the predict and I get other situation: The Response is Empty (???).
Here is my code:
'get the service credential that I created
Dim credential = Await GetCredential()
Dim myService As New CloudMachineLearningEngineService(New BaseClientService.Initializer() With {
.ApplicationName = "my Project Name (Is That It???)",
.ApiKey = "my API Key",
.HttpClientInitializer = credential
})
Dim myBase64 As String = GetBase64("my image path to convert into a base64 String")
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myRequest = New GoogleCloudMlV1PredictRequest With {
.HttpBody = New GoogleApiHttpBody With {.Data = myJsonRequest,
.ContentType = "application/json"
}
}
'If I change the model name I get error
Dim myPredictRequest = myService.Projects.Predict(myRequest, "projects/myProject/models/myModel/versions/v1")
myPredictRequest.AccessToken = credential.Token.AccessToken
myPredictRequest.OauthToken = credential.Token.AccessToken
myPredictRequest.Key = "my API Key
'Execute the request
Dim myResponse = myPredictRequest.Execute()
'at this point, myResponse is Empty (myResponse.ContentType Is Nothing, myResponse.Data Is Nothing And myResponse.ETag Is Nothing)
If I change the model name I get a error informing that my model was not found, so my credentials are right.
I don't know what I'm doing wrong. Someboby can help with any of this issues?
Thanks!
UPDATE: --------------------------
I changed this Execute Command:
Dim myResponse = myPredictRequest.Execute()
To This One:
Dim s = StreamToString(myPredictRequest.ExecuteAsStream())
and Now I can get the same error with .Net API and google developers interface (Missing instances field...).
So If someboby just Know what is wrong with my Json request, It will help a lot.
The JSON you put in the API explorer is indeed correct (assuming, of course, your model has inputs key and image_bytes). This appears to be a bug with the explorer I will report.
The reason you are getting the error you are in the .NET code is because you are using an .HttpBody field. This code:
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myRequest = New GoogleCloudMlV1PredictRequest With {
.HttpBody = New GoogleApiHttpBody With {.Data = myJsonRequest,
.ContentType = "application/json"
}
}
Will produce a JSON request that looks like this:
{
"httpBody": {
"data": "{\"instances\" : [{\"key\":\"0\", \"image_bytes\": {\"b64\": \"mybase64\"} }]}",
"contentType": "application\/json"
}
}
When what you really need is:
{"instances" : [{"key":"0", "image_bytes": {"b64": "mybase64"} }]}
Hence the error message you see.
I don't know how to generate the correct response using the .NET library; based on the Python example in the docs, I would guess:
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myPredictRequest = myService.Projects.Predict(myJsonRequest, "projects/myProject/models/myModel/versions/v1")
But I don't have a good way of testing that. For reference, the Python equivalent is:
response = service.projects().predict(
name=name,
body=myJsonRequest
).execute()
I solved the problem with .Net API.
I created two new classes Inherits the Google API's classes.
Something like that:
Imports Google.Apis.CloudMachineLearningEngine.v1.Data
Imports Newtonsoft.Json
Public Class myGoogleCloudMlV1PredictRequest
Inherits GoogleCloudMlV1PredictRequest
<JsonProperty("instances")>
Public Property MyHttpBody As List(Of myGoogleApiHttpBody)
End Class
Imports Google.Apis.CloudMachineLearningEngine.v1.Data
Imports Newtonsoft.Json
Public Class myGoogleApiHttpBody
Inherits GoogleApiHttpBody
<JsonProperty("image_bytes")>
Public Property MyData As image_byte
<JsonProperty("key")>
Public Property key As String
End Class
So, in my original code I change this part:
Dim myBase64 As String = GetBase64("my_image_path_to_convert_into_a _base64_String")
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myRequest = New GoogleCloudMlV1PredictRequest With {
.HttpBody = New GoogleApiHttpBody With {.Data = myJsonRequest,
.ContentType = "application/json"
}
}
For this one:
Dim myBase64 As String = GetBase64("my_image_path_to_convert_into_a _base64_String")
Dim myRequest = New myGoogleCloudMlV1PredictRequest With {
.MyHttpBody = New List(Of myGoogleApiHttpBody)()
}
Dim item As myGoogleApiHttpBody = New myGoogleApiHttpBody With {
.key = "0",
.MyData = New image_byte With {
.b64 = myBase64
}
}
myRequest.MyHttpBody.Add(item)
And voilá, It's working!
Thanks for everyone!!
Github issue #1068 shows two work-arounds for this problem.
In summary, use service.ModifyRequest to insert the raw JSON content.
Or use service.HttpClient.PostAsync(...) directly.

How to pass JSON string to another api using RESTSharp?

Problem Specification:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
The above parameters should be passed to the system as a row HTTP POST in a JSON string.
I am trying to solve this problem using RESTSharp. But I am having some problem Like after executing the request my code return a Null response and I am not sure my JSON string is passing properly or not.
Here is my Code:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", #"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
Is there anything wrong with my code??
And I am little bit confused about
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
Basically I want to know how to utilize AdduUrlSegment() and AddParameter().
Thanks in advance.
For using request.AddUrlSegment("username", "Admin") you should define your url template properly: var request = new RestRequest("api/employee/{username} ", Method.POST);
Also you should set Content-Type
request.AddHeader("Content-Type", #"application/json");
befor adding a Body

How to attach files via ASP.net application to FogBugz with C#

I have an ASP.net application that allows the users to report bugs and attach files. The bug together with its detail and attachments should be saved in FogBugz.
I have managed to create everything except the file attachment part.
here is my code:
private void NewCaseWithFile()
{
string fbUrl = "https://test.fogbugz.com/api.asp";
string fbToken = logInFogBugz();
string param = "";
param += "cmd=new";
param += "&token=" + fbToken;
param += "&sTags=" + "OnlineService,";
param += "&sTitle=" + "Testing";
param += "&sEvent=" + "This case is being created from Visual Studio";
param += "&nFileCount=" + "1";
param += "&File1=" + "Picture.png";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(fbUrl + "?" + param);
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.ContentType = "multipart/form-data";
httpWebRequest.Accept = "application/xml";
httpWebRequest.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
XDocument doc = XDocument.Load(streamReader);
}
I have tried all instructions under "Editing Cases" but it did not help. In fact I have no idea what are File 1, File 2 and how to send them to FogBugz.
Can anyone help me with this?
Many thanks!
File1 should be specified in the body of your multipart/form-data post (not as a querystring parameter).
You actually have to specify all the bytes in the file.
There's an answer on fogbugz.stackexchange.com as well as a C# FogBugz API wrapper that will handle all the parts for you.
The form parts in the body of your post would look like
--sdfjdsjsdflk SOME BOUNDARY--
Content-Disposition: form-data; name="File1"; filename="foo.jpg"
Content-Transfer-Encoding: base64
Content-Type: image/png
slfkajdflksjflajfdj
sldfjsd;aljfds
these are actual data bytes from the foo.jpg file
slfkjdsfljds
sdflajsdfs
Or you can look at this question which points to an RFC with an example.

Resources