Adding Attachment to Work Item through custom Widget Using ajax call - azure-devops

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
});
});

Related

Create a file and add it to a folder with Sharepoint's Api Rest using Postman

I use this call: https://{site_url}/_api/web/GetFolderByServerRelativeUrl('/ Folder Name')/Files/add(url ='a.txt', overwrite = true).The file is inserted correctly but I don't know what to add so that I can fill the rest of the columns of the library of documents.But it can be done in the same call, it doesn't matter. But I need to modify the value in a record of a document library
Warrior,
Do you want to update values of other columns after uploading a file to a library? If so, you may hava a look below demo:
function getItem(file) {
var call = jQuery.ajax({
url: file.ListItemAllFields.__deferred.uri,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
return call;
}
function updateItemFields(item) {
var now = new Date();
var call = jQuery.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/Lists/getByTitle('Documents')/Items(" +
item.Id + ")",
type: "POST",
data: JSON.stringify({
"__metadata": { type: "SP.Data.DocumentsItem" },
CoordinatorId: _spPageContextInfo.userId,
Year: now.getFullYear()
}),
headers: {
Accept: "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"IF-MATCH": item.__metadata.etag,
"X-Http-Method": "MERGE"
}
});
return call;
}
You need to put this operation in a separated request.
BR

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.

How to get list items from a folder in custom list using rest API?

I am working with Office 365. I have used REST API for different types of operations. I can easily find list items in a folder in document library because they are files. I want the list items in a folder in custom list. For this I am not able to find any REST API. Can you please provide me any REST API which will be able to retrieve list items from folder in custom list ?
I got the answer. Following is the way
var camlQuery = {
'query': {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml': '<View><Query/></View>',
'FolderServerRelativeUrl': '/sites/EdvelopTest3/Lists/QuestionsList/test/test1'
}
};
var url = OEPContext.appWebUrl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('OEPLMSQuestions')/getitems?$select=ID,Title&#target='" + OEPContext.hostWebUrl + "'";
jQuery.ajax({
async: false,
url: url,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(camlQuery),
success: function (data) {
var result = "success";
},
error: function (data, msg) {
var result = "Fail";
}
});

how to read jquery.ajax() data in mvc 2 controller

I'm using mvc2 and jqueries to post the data from view to controller.
This is my view
$('#btnSaveAcademicInfo').click(function() {
var recordsToSave = [];
var curRecord = null;
$.each($("#academics tr"), function(i, v) {
curRecord = {};
curRecord.Institution = $(this).find('.tdName').text();
curRecord.PassoutYear = $(this).find('.tdPassOutYear').text();
curRecord.Percentage = $(this).find('.tdPercentage').text();
curRecord.Specialization = $(this).find('.tdspecialization').text();
recordsToSave.push(curRecord);
});
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: recordsToSave,
success: function(result) { success(result); },
datatype: "json"
});
});
and my controller is
[HttpPost]
public ActionResult SaveAcademicInfo(List<AcademicModel> data)
{
//Here data is always null
return View("GetPersonalDataById");
}
Here im not getting the data to controller. But when i use, data: JSON.stringify(recordsToSave), I'm able to see the data in firebug.
How do i read the data in controller.
Please help.
JSON.stringify converts a javascript object into a JSON string. If you want to send JSON requests in ASP.NET MVC 2 you need a JSON value provider as this is not built-in. See this blog post for more details. In ASP.NET MVC 3 this works out of the box thanks to the built-in JsonValueProviderFactory.
Also if you want to send a JSON request you need to specify the content type as well:
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: JSON.stringify(recordsToSave),
contentType: 'application/json',
dataType: 'json', // <!-- notice the capital T
success: function(result) {
success(result);
},
});
and if you don't want to use JSON you will need to format the request in a way that the default model binder can understand. Try like this:
var recordsToSave = [];
$.each($('#academics tr'), function (index, value) {
recordsToSave.push({
'name': '[' + index + '].Institution',
'value': $(this).find('.tdName').text()
});
recordsToSave.push({
'name': '[' + index + '].PassoutYear',
'value': $(this).find('.tdPassOutYear').text()
});
recordsToSave.push({
'name': '[' + index + '].Percentage',
'value': $(this).find('.tdPercentage').text()
});
recordsToSave.push({
'name': '[' + index + '].Specialization',
'value': $(this).find('.tdspecialization').text()
});
});
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: recordsToSave,
success: function (result) {
success(result);
}
});