devops using Ajax access query data WIQL - azure-devops

I am trying to access azure-devops data using Ajax. And below is my working code.
$.ajax({
url: 'https://dev.azure.com/ORG/products/_apis/wit/workitems/2065741?$expand=all&api-version=5.1',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + 'XXXX')
}
}).done(function( results ) {
});
After I need to access data using WQIL but it is giving an unexpected token error. I want to access WorkItem, and user activity. Can you please help with this?
$.ajax({
url: 'https://dev.azure.com/ORG/products/_apis/wit/wiql?api-version=5.1 ',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + 'XXXX')
},
JSON.Stringfy("QUERY":"SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] FROM workitemLinks WHERE " +
"( [Source].[System.TeamProject] = #project AND [Source].[System.WorkItemType] = 'User Story' ) AND ( [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' ) "+
" AND ( [Target].[System.TeamProject] = #project AND [Target].[System.WorkItemType] = 'Task' ) ORDER BY [System.Id] MODE (MustContain)")
}).done(function( results ) {
x=results
});

The previous script you are using is the method used to execute API, but not suitable for execute WIQL script. That's why you are facing that error.
Executing WIQL in Ajax is actually a request process: Send the wiql statement to the server you want to access, request to execute the query statement(Wiql), and return the execution result. Therefore, this is a process of requesting the execution of the Post command. But in your script, it did not tell the server what instructions need to be executed.
Here is the simple sample can for you refer to use WIQL with Ajax:
<script type="text/javascript">
$(document).ready(function () {
$("#SelectWIT").on("click", function () {
var d = { "query": " Select [System.Id] from WorkItems Where [System.WorkItemType] = 'Bug' "};
$.ajax({
type: 'POST',
url: 'https://dev.azure.com/{org name}/{project name}/_apis/wit/wiql?api-version=1.0',
contentType: 'application/json',
data: JSON.stringify(d),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "{PAT token}"));
},
}).done(function (data) {
var items = [];
$.each(data.workItems, function (key, val) {
items.push("<li> <a href='" + val.url + "'>" + val.id + "</a></li>");
});
$("<ul/>", {
html: items.join("")
}).appendTo("body");
}).error(function (e) {
var s = "error error error";
});
})
});
</script>
The logic of my script is to request to run a API with a WIQL statement as request body, send this request to the project I want to access. Then display the response data with js syntax into the body of the page. This is the output:
Since I am not sure what is your next operation. You can replace the Wiql statement and the Url with yours in this script. Then change the corresponding done function to achieve what you want.

Somehow WQIL is giving error 400 it looks like a permission issue.
So I Solved it in a different way. Instead of the query, there is another method which gives me all the details of the workitem I just need to pass workitem Id's in that.
var d ={
"ids": [
20813,21677
],
"fields": ["System.Id","System.WorkItemType","System.Title","System.AssignedTo","System.State","System.Tags"]
};
$.ajax({
type: 'POST',
url: 'https://dev.azure.com/ORG/products/_apis/wit/workitemsbatch?api-version=5.1',
contentType: 'application/json',
data: JSON.stringify(d),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "XXXXX"));
},
}).done(function (data) {
x=data
});

Related

Multipart/mixed request for google drive bulk deletion using request npm package

I was trying to do bulk deletion of files from google drive using rest API. So i was framing the request for bulk deletion request i was able to achieve the deletion with the similar request framing method Bulk delete files on Google Drive with raw XMLHttpRequest but i was trying to achieve this without sending the body instead of sending multipart array in the request object. I am getting error 400 with following response body
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
This is my request object which is failing
const _multipart = []
arrayOfFileIds.forEach((current) => {
const obj = {
body: 'Content-Type: application/http\n\n' +
'DELETE https://www.googleapis.com/drive/v3/files/' +
current + '\nAuthorization: Bearer ' + authToken
}
_multipart.push(obj)
})
const requestOptions = {
url: 'https://www.googleapis.com/batch/drive/v3',
method: 'POST',
headers: {
'Content-Type': 'multipart/mixed'
},
multipart: _multipart
}
And below request Object is working
const boundary = 'END_OF_PART'
const separation = '\n--' + boundary + '\n'
const ending = '\n--' + boundary + '--'
const requestBody = arrayOfFileIds.reduce((accum, current) => {
accum += separation +
'Content-Type: application/http\n\n' +
'DELETE https://www.googleapis.com/drive/v3/files/' +
current +
'\nAuthorization: Bearer ' + authToken
return accum
}, '') + ending
const requestOptions = {
url: 'https://www.googleapis.com/batch/drive/v3',
method: 'POST',
headers: {
'Content-Type': 'multipart/mixed; boundary=' + boundary
},
body: requestBody
multipart: _multipart
}
Modification points:
The access token can be included in the request header.
Put Content-Type of each batch request out of body.
When these points are reflected to your script, it becomes as follows.
Modified script:
const _multipart = [];
arrayOfFileIds.forEach((current) => {
const obj = {
"Content-Type": "application/http",
body: "DELETE https://www.googleapis.com/drive/v3/files/" + current + "\n",
};
_multipart.push(obj);
});
const requestOptions = {
url: "https://www.googleapis.com/batch/drive/v3",
method: "POST",
headers: {
"Content-Type": "multipart/mixed",
Authorization: "Bearer " + authToken,
},
multipart: _multipart,
};
Note:
When I tested the above modified script, no error occurs. The files can be deleted. When you tested the above script, when an error occurs, please confirm the script and the access token, again.
Reference:
request

Adding Attachment to Work Item through custom Widget Using ajax call

How to Add Attachment to Work Item through custom Widget using ajax call. I read about API call but did not understand how it would be done, through ajax I am able to create the work item using my widget, but unable to add attachment to it. Find my ajax code below:
$("#btnAttachment").click(function () {
var restURL = "https://dev.azure.com/organizationName/{" + VSS.getWebContext().project.id + "}/_apis/wit/attachments?fileName='C:\Users\Administrator\Downloads\picturemessage_4hm34b3k.kot.png'&api-version=5.0";
var myPatToken = "xyz";
$.ajax({
contentType: 'application/octet-stream',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
},
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Failure");
console.log(JSON.stringify(data.responseText));
},
type: 'POST',
url: restURL
});
});

How to create users using external API in owncloud

My application creates owncloud users using external APIs.
I tried with get owncloud version using external API. Below is the code I used:
$.ajax({
type: 'GET',
url: 'http://localhost/owncloud/index.php/apps/news/api/2.0/version',
contentType: 'application/json',
success: function (response) {
// handle success
},
error: function () {
// handle errors
},
beforeSend: function (xhr) {
var username = 'admin';
var password = 'admin';
var auth = btoa(username + ':' + password);
xhr.setRequestHeader('Authorization', 'Basic ' + auth);
}
});
The above code didn't work.
How to achieve this?
Thanks in advance.
The code you have put is right.
You could as well test if your api is returning the data using something like postman or chrome rest client.
then(function(response) {
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
})
.done(function(res) {
swal("Deleted!", "Your ListJds has been deleted.", "success");
})
.error(function(res) {
res;
swal("Delete Failure!", "Please Try Again.", "error");
});
})

SharePoint 2013 REST API AJAX update workflow task

I need your help.
I'd like to complete custom workflow task, (SH 2010 WF) running over 2013.
I've been using a pice of code. to update a task list using Rest API in JavaScript AJAX.
I test this code with other list and run OK, but When I like to update a task list. I received different error MSG.
If I like to updated Title filed I received ""message":{"lang":"es-ES","value":"Value does not fall within the expected range."}}},"status":400,"statusText":"Bad Request"}"
If I like to Update Result field I can see the filed in properties.
Do you have any conceptual description about how to work with workflow task and their content types using Rest API
Thank in advance
Ramiro
I'll share my code.
function updateJson(endpointUri,payload, success, error)
{
return getFormDigest('https://partner.coca-cola.com/sites/SLBU2013Test/POC').then(function (data) {
$.ajax({
url: endpointUri,
type: "POST",
data: JSON.stringify(payload),
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest" : data.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: success,
error: error
});
});
}
function getItemTypeForListName(name) {
console.log("SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem");
return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}
function updateListItem(webUrl,listTitle,listItemId,itemProperties,success,failure)
{
var listItemUri = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + listItemId + ")";
console.log(listItemUri);
var itemPayload = {
'__metadata': {'type': 'SP.Data.TasksListItem'}
};
for(var prop in itemProperties){
itemPayload[prop] = itemProperties[prop];
console.log(itemProperties[prop]);
}
updateJson(listItemUri,itemPayload,success,failure);
}
function getFormDigest(webUrl) {
return $.ajax({
url: webUrl + "/_api/contextinfo",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" }
});
}
function Calcular (){
var itemProperties = {'Status':'Completadas'};
updateListItem('https://partner.coca-cola.com/sites/SLBU2013Test/POC','Tasks',2,itemProperties,printInfo,logError);
function printInfo()
{
console.log('Item has been created');
}
function logError(error){
console.log(JSON.stringify(error));
}
};
There is another similar post. My answer there was to do some screen scraping and redirect users to the UI. Short story is that we could not update the list with REST, but could with CSOM. Regardless, the WF ignored the task changes. Here's the link: Update task item programatically in Sharepoint with CSOM.

Create DocumentSet with REST api

How would one format the rest uri to create a document set in SP?
The JSOM code below works fine, but I would prefer to use the REST in order to be able to call it from a workflow.
var dsresult = SP.DocumentSet.DocumentSet.create(context, parentFolder, "docsetfromjsom", docsetCtId);
I tried this format based on this MSDN article
var restQueryUrl = spAppWebUrl + "/_api/SP.AppContextSite(#target)/SP.DocumentSet.DocumentSet.create('serverrelativeurl','docsetname','ctid')?#target='spHostUrl'";
Tried other formats as well but none successful. In jsom you also need to include the context, but I am assuming that for the rest call you don't need to use it (i think). Anyone tried this before?
Thanks!
I've already answered a similar question at SharePoint StackExchange.
To summarize, it does not seem possible to create Document Set using SharePoint 2013 REST API since SP.DocumentSet.DocumentSet.create function is not accessible via REST. But you could utilize SharePoint 2010 REST API instead for that purpose.
The following example demonstrates how to create a Document Set using SharePoint 2010 REST Interface:
function getListUrl(webUrl,listName)
{
return $.ajax({
url: webUrl + "/_api/lists/getbytitle('" + listName + "')/rootFolder?$select=ServerRelativeUrl",
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function createFolder(webUrl,listName,folderUrl,folderContentTypeId)
{
return $.ajax({
url: webUrl + "/_vti_bin/listdata.svc/" + listName,
type: "POST",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"Slug": folderUrl + "|" + folderContentTypeId
}
});
}
function createDocumentSet(webUrl,listName,docSetName)
{
return getListUrl(webUrl,listName)
.then(function(data){
var folderUrl = data.d.ServerRelativeUrl + '/' + docSetName;
return createFolder(webUrl,listName,folderUrl,'0x0120D520');
});
}
Usage
Create Document Set named Orders in Documents library:
createDocumentSet(webUrl,'Documents','Orders')
.done(function(data)
{
console.log('Document Set ' + data.d.Name + ' has been created succesfully');
})
.fail(
function(error){
console.log(JSON.stringify(error));
});