Getting workitems from tfs via javascript - javascript

I have some problem with Getting workitems from tfs via the following javascript code:
var res = new XMLHttpRequest();
var body = "{'query' : \"select * from workitems where [Change Number] = 'CH-0000433' \"}" ;
res.open("POST","<SERVER_NAME>/tfs/InternalApplications/Testing%20Services/_apis/wit/wiql?api-version=1.0",true,<LOGIN>,<PASSWORD>);
res.setRequestHeader('Content-type', 'application/json');
res.send(body);
when I am trying to execute this script, I am getting the 401 - Unauthorized error
I`ve wrote the PowerShell analogue of this script, and it works fine:
$q2 = """select Id from workitems where [Change Number] = 'CH-0000433' """
$res = Invoke-WebRequest <Server_Name>/tfs/InternalApplications/Testing%20Services/_apis/wit/wiql?api-version=1.0 `
-ContentType application/json `
-Credential $(Get-Credential) `
-Method Post `
-Body "{'query' : $q2}" `
-UseBasicParsing
I suppose that in javascript case I am passing credentials incorrectly, so how should I change it?

I've tested on TFS 2017 with the code snippet below and it is working:
var jsonObj = [{
"op": "add",
"path": "/fields/System.Title",
"value": "cecetest1"
}];
$.ajax({
url: 'http://TFS2017:8080/tfs/DefaultCollection/ScrumProject/_apis/wit/workitems/$Task?api-version=1.0',
type: 'PATCH',
contentType: "application/json-patch+json",
data: JSON.stringify(jsonObj),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("domain\\username" + ":" + "password"));
},
})

Related

"401 Error Code" using google script app fetch post

Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->
"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"
since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.
Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.
function posting(){
var Username = "{API KEY}"
var Password = "x"
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(Username+ ':' + Password)
};
var url ='{API URL}'
var data ={
"document":{
"customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
"issue_date":"2022-05-09",
"context_id":5,
"document_items":[
{
"quantity":2,
"price":134,
"item_id":" b04993fe-7b17-42a1-b5e5-2d34890794c9"
}
]
},
};
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
UrlFetchApp.fetch(url, option);
}
I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.
And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.
From:
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
To:
var option = {
"method": "post",
"payload": JSON.stringify(data),
headers, // or "headers": headers
"contentType": "application/json"
};
Note:
In this modification, it supposes that the values of "Basic " + Utilities.base64Encode(Username+ ':' + Password), data and url are correct. Please be careful this.

How to pass authorization headers to WCF service in javascript?

This is the request that I am sending via javascript on a click of a button.
_crmProxy = "http://xxxxxxx:12355/dev_test/Service1.svc";
var name = "yz\\c.crm";
var pwd = "321#";
var text = "Parshu";
var response = null;
$.ajax({
async: true,
type: "POST",
headers : {
'Authorization' : 'Basic ' + btoa(name + ':' + pwd),
'Content-Type' :'application/json'
},
data: '{"userName": "' + text + '" }',
url: _crmProxy + "/WelcomeUser",
success: function (result) {
response = result.WelcomeUserResult;
},
error: function (error) {
alert("err");
}
});
but I am getting 401 Unauthorized OPTIONS error and couldn't go ahead. Can you please tell me where am I going wrong.
Thank you.
Prashant

How to create todoist task using todoist api v7?

I'm trying to create a task in todoist but cant seem to do so
According to this todoist documentation, the below should work for creating a todoist task
$ curl https://todoist.com/api/v7/sync \
-d token=0123456789abcdef0123456789abcdef01234567 \
-d sync_token="VRyFHr0Qo3Hr--pzINyT6nax4vW7X2YG5RQlw3lB-6eYOPbSZVJepa62EVhO" \
-d resource_types='["projects", "items"]' \
-d commands='[
{ "type": "item_add",
"temp_id": "fdef5d16-a40a-475e-bd4a-0ccbd6fd8c3f",
"uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752",
"args": { "project_id": "24a193a7-46f7-4314-b984-27b707bd2331", "content": "Task1" } },
{ "type": "item_add",
"temp_id": "6f5e0b50-af7a-4133-bfc0-e8c041b819d2",
"uuid": "d16ad84a-e10b-4894-af7d-93ba6adf7a1e",
"args": { "project_id": 176637191, "content": "Task2" } },
]'
I've tried the following with little luck
commands = [{"type": "item_add", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"project_id": 2159935681,"content":"Test Task"}}]
$.ajax({
type: "GET",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["projects", "items"]',
'commands':commands
}
})
I've also tried the following:
commands = [{"type": "item_add", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"project_id": 2159935681,"content":"Test Task"}}]
$.ajax({
type: "POST",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["projects", "items"]',
'commands':commands
}
})
This results in the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://en.todoist.com/api/v7/sync/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I've also tried removing the project id
commands = [{"type": "item_add", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"content":"Test Task"}}]
$.ajax({
type: "GET",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["items"]',
'commands':commands
}
})
I've also tried adding the temp_id parameter:
commands = [{"type": "item_add","temp_id": "fdef5d16-a40a-475e-bd4a-0ccbd6fd8c3f", "uuid": "a3aa2f44-23b4-4986-b513-ef7663bbb752", "args": {"project_id": 2159896038,"content":"Test Task"}}]
$.ajax({
type: "POST",
url: 'https://en.todoist.com/api/v7/sync/',
dataType: 'json',
async: false,
data: {
'token': todoist_api_token,
'sync_token':'*',
'resource_types':'["projects", "items"]',
'commands':commands
}
})
I've even tried the todoist api v8 version following the todoist instrucitons for the v8 api here
$.ajax({type: "POST",
url: 'https://beta.todoist.com/API/v8/tasks',
dataType: 'json',
async: false,
data: {'token':todoist_api_token,'content': 'Appointment with Maria'}
});
This returns "Bad Request"
I did find that the following works for v6:
$.ajax({type: "POST",
url: 'https://todoist.com/API/v6/add_item',
dataType: 'json',
async: false,
data: {'token':todoist_api_token,'content': 'Appointment with Maria'}
});
sync_token
In the first example I see that the sync token is set. It should be var sync_token = '*' and after the ajax request you should save the token with sync_token = response.sync_token; I see that you realized that in the later examples.
commands
The rest looks good but I can't see your commands and I guess the problem comes from there. The commands object has to be stringified with JSON.stringify(commands).
working example
I created a working example below. You have to replace the todoist_api_token = "" with your token and the project id's in the example task.
// Global variables
var todoist_api_token = ""; // Put your token here
var sync_token = "*";
// To get a project id: clicke on a project and look at the url.
// In the example "#project%2F2179064046" you have to remove "#project%2F".
// and the project id is 2179064046
// Run example task after document load
window.onload = function() {
console.log("Add example task to todoist");
var example_tasks = [
{"content": "Task1", "project_id": 2179064046},
{"content": "Task2", "project_id": 2179064046}
];
todoist_add_tasks_ajax(example_tasks);
}
// Functions
todoist_add_tasks_ajax = function(tasks) {
var commands = todoist_tasks_to_commands(tasks);
var data = {
"token" : todoist_api_token,
'sync_token' : sync_token,
'resource_types' : '["projects", "items"]',
'commands' : commands
};
jQuery.ajax({
url: "https://todoist.com/api/v7/sync",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
console.log(response);
sync_token = response.sync_token;
},
error: function(response) {
console.log(response);
},
});
}
todoist_tasks_to_commands = function(tasks) {
var commands = [];
tasks.forEach(function(args) {
var temp_commands = {
"type": "item_add",
"temp_id": create_guid(),
"uuid": create_guid(),
"args": args
};
commands.push(temp_commands)
});
commands = JSON.stringify(commands);
return commands;
}
function create_guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
/*
// Install jQuery
javascript: (function(e, s) {
e.src = s;
e.onload = function() {
jQuery.noConflict();
console.log("jQuery installed");
};
document.head.appendChild(e);
})( document.createElement('script'), 'http://code.jquery.com/jquery-latest.min.js')
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

External Sharing of Folders in SharePoint Online using REST API

I am new to SharePoint Online and REST API.
I am currently working on a SharePoint Add-In which creates folders in a document library residing in the Host Web and share the permission to specified external users. I am currently attempting to do everything using REST API.
I am successfully able to create the folders but I am currently unable to share the folders to external users.
I am having trouble resolving the following endpoints when attempting to use the host web context. The first endpoint below is for resolving the external email, and the second one is for performing the actual sharing of the folder to the external user.
[appUrl]/_api/SP.AppContextSite(#target)/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerResolveUser?#target='[hostUrl]'
[appUrl]/_api/SP.AppContextSite(#target)/SP.Web.ShareObject?#target='[hostUrl]'
I am getting the error 404 Not Found: Cannot find resource for the request SP.UI.ApplicationPages.ClientPeoplerPickerWebServiceInterface.clientPeoplePickerResoveUser. The same error occurs for SP.Web.ShareObject when I try to force it to run.
Below is the javascript that I am using
var ShareToRecipients = function(folder, recipient, appUrl, hostUrl){
var url = appUrl = "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerResolveUser";
url = WebComponents().getTargetUrl(url, hostUrl);
var sharedDocUrl = hostUrl + "/ExternalShareDocLib/" + foldername;
var checkUser = $.ajax({
url: url,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'queryParams': {
"__metadata": {'type': "SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters"},
"AllowEmailAddresses": true,
"AllowMultipleEntities": false,
"AllUrlZones": false,
"MaximumEntitySuggestions": 50,
"PrincipalSource": 15,
"PrincipalType": 1,
"QueryString": recipient
}
}),
headers:{
"accept": "application/json;odata=verbose",
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
error: function(jqXHR, textStatus){
myapp.LogAPIError(jqXHR, textStatus)
}
});
checkUser.success(function(data){
var user = data.d.ClientPeoplePickerResolveUser;
var result = JSON.parse(users);
if(users !== undefined){
var reqUrl = appUrl + "/_api/SP.Web.ShareObject";
reqUrl = WebComponents().getTargetUrl(reqUrl, hostUrl);
var shareCall = $.ajax({
url: reqUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
"url": reqUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
"url": sharedDocUrl,
"peoplePickerInput": '[' + user + ']',
"roleValue": "1073741827",
"groupId": 0,
"propagateAcl": false,
"sendEmail": true,
"includeAnonymousLinkInEmail": true,
"emailSubject": "A document folder has been shared to you",
"emailBody": "A document folder has been shared to you. The folder name is " + folder
})
});
});
shareCall.success(function(data){
myApp.LogInformation("Successfully shared " + folder + " to " + recipient);
});
shareCall.error(function(jqXHR, textStatus){
myApp.LogAPIError(jqXHR, textStatus);
});
}
});}
For generating the Host URL Endpoint
var WebComponents = function(){
var getTargeturl = function (url, hostUrl){
if(hostUrl){
var api = "_api/";
var index = url.indexOf(api);
url = url.slice(0, index + api.length)+
"SP.AppContextSite(#target)" +
url.slice(index + api.length);
var connector = "?";
if(url.indexOf("?") > -1 && url.indexOf("$") > -1){
connector = "&";
}
url = url + connector + "#target='" + hostUrl + "'";
}
return url;
}
return{
getTargeturl: getTargeturl
}}
Can you help verify if I am using the endpoints correctly and if what I am trying to do is even possible?
Appreciate the help.
Cheers,
Neil
Adding my resolution just in case anyone else encounters this issue.
I was able to use the API by:
Removing url = WebComponents().getTargetUrl(url, hostUrl)
and reqUrl = WebComponents().getTargetUrl(reqUrl, hostUrl).
Giving the App Full Control in the Tenant via the AppManifest.xml

"JSON_PARSING_ERROR: Unexpected character (d) at position 0." when sending GCM request from GAS

This seems very similar to a number of other questions and it seems obvious that the error indicates there's something wrong with my JSON payload. But I'm at a loss as to why.
I'm running a Google Apps Script to test sending a message to Google Firebase Cloud Messaging.
My code:
function SendGCMessage() {
var url = "https://gcm-http.googleapis.com/gcm/send";
var apiKey = "AbCdEfG";
var to = "ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"
var payload = {
"data": {
"message" : "This is the message"
},
"to":to
};
var sendCount = 1;
var headers = {
"Content-Type": "application/json",
"Authorization": "key=" + apiKey
};
var params = {
headers: headers,
method: "post",
payload: payload
};
var response = UrlFetchApp.fetch(url, params);
return {message: "send completed: " + response.getContentText()};
}
When I run this in debug mode, the object payload looks fine - like a normal Javascript object. params as well. UrlFetchApp takes a Javascript object, not a String in JSON notation. However I did try "JSON.stringify(params)" and I got an error. What did I do wrong?
Note: params looks like this when I pause it in the debugger:
{"headers":{"Content-Type":"application/json","Authorization":"key=AbCdEfG"},"method":"post","payload":{"data":{"message":"This
is the message"},"to":"ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"}}
I discovered the problem, thanks to https://stackoverflow.com/a/10894233/3576831
the 'payload' parameter must be a string as specified here:
https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
Adjusting this section of the script works:
var params = {
headers: headers,
method: "post",
payload: JSON.stringify(payload)
};

Categories