Errors occur submit batch request - odata

I am trying to use batch request for sending http post to the server.
The code snippet, which generate the request:
_.each(aNewDates, function (oNew) {
oModel.create("/CostCenterCalendarSet", oNew, {
groupId: "newDates"
});
});
oModel.setDeferredGroups(["newDates"]);
and the submit method:
oModel.submitChanges({
groupId: "newDates",
oSuccess: function (oMsg) {
return observer.next(oMsg);
},
oError: function (oErr) {
return observer.error(oErr);
},
});
as response I've got following error:
What am I doing wrong?
Update
I tried with ODataModel read method and does not get any result.
let oPlantFilter = new sap.ui.model.Filter("Plant", sap.ui.model.FilterOperator.EQ, oSelectedData.sPlant);
let oWcFilter = new sap.ui.model.Filter("WorkCenter", sap.ui.model.FilterOperator.EQ, oSelectedData.sWc);
oModel.read("/CostCenterCalendarSet", {
groupId: "query-dates",
filters: [oPlantFilter, oWcFilter]
});
oModel.setDeferredGroups(["query-dates"]);
return Rx.Observable.create(function (subscriber) {
oModel.submitChanges({
groupId: "query-dates",
success: function (oData, oResponse) {
return subscriber.next(oResponse);
},
error: function (oErr) {
return subscriber.error(oErr);
},
});
});

Related

Graph API for SharePoint: Update / Create ListItems with Hyperlink / Picture fields

How do I shape the payload to enable a post or patch for fields that are Hyperlink/Picture?
Getting those fields is straight forward: they come as "fieldName" : { "Description":"asdf", "Url":"asdf.com"}
This works in flow using the Send HTTP Request to SharePoint block, but I can't figure out how to make this work using the graph api. Do i need to set the odata type explicitly (SP.FieldUrlValue doesn't work) and what is it for Hyperlinks?
Somethink like this: {"fieldName#odata.type", "Complex" } - we use this with Collection(Edm.String) for multiple lookup fields for instance.
Kind regards,
Gregor
Graph API does not support create this kind of column.
https://learn.microsoft.com/en-us/graph/api/resources/columndefinition?view=graph-rest-1.0
You could try to use rest api.
Create HyperLink field:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function (){
CreateListItemWithDetails("test3")
})
function CreateListItemWithDetails(listName) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": "test",
'link':
{
'__metadata': { 'type': 'SP.FieldUrlValue' },
'Description': 'Google',
'Url': 'http://google.com'
},
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
Update Hyperlink column:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function (){
CreateListItemWithDetails("test3")
})
function CreateListItemWithDetails(listName) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": "test",
'link':
{
'__metadata': { 'type': 'SP.FieldUrlValue' },
'Description': 'Google1',
'Url': 'http://google.com'
},
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(41)",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>

postman schema validation into reporter-htmlextra

I'm currently running some tests with postman where I get a schema and try to validate my results against it.
I know the schema is not consistent with the response I'm getting but I wanted to know how is it possible to expand the results to give a bit more information.
so for example if I have a request like this:
GET /OBJ/{ID}
it just fails with the feedback:
Schema is valid:
expected false to be true
I was hoping to manage to get a bit more feedback in my newman report
this is an example of my test:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// only preform tests if response is successful
if (pm.response.code === 200) {
var jsonData = pm.response.json();
pm.test("Data element contains an id", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).eql(pm.environment.get("obj_id"));
});
pm.test('Schema is valid', function() {
pm.expect(tv4.validate(jsonData, pm.globals.get("objSchema"))).to.be.true;
});
}
and this is how I run my tests:
const newman = require('newman');
newman.run({
insecure: true,
collection: require('../resources/API.postman_collection.json'),
environment: require('../resources/API.postman_environment.json'),
reporters: 'htmlextra',
reporter: {
htmlextra: {
export: './build/newman_report.html',
logs: true,
showOnlyFails: false,
darkTheme: false
}
}
}, function (err) {
if (err) {
throw err;
}
console.log('collection run complete!');
});
is there a way I can get more information about the validation failure?
I tried a few quick google search but have not come up to nothing that seemed meaningful
it's not exactly what I wanted but I managed to fix it with something like this:
// pre-check
var schemaUrl = pm.environment.get("ocSpecHost") + "type.schema";
pm.sendRequest(schemaUrl, function (err, response) {
pm.globals.set("rspSchema", response.json());
});
// test
var basicCheck = () => {
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});
};
// create an error to get the output from the item validation
var outputItemError = (err) => {
pm.test(`${err.schemaPath} ${err.dataPath}: ${err.message}`, function () {
pm.expect(true).to.be.false; // just output the error
});
};
var itemCheck = (item, allErrors) => {
pm.test("Element contains an id", function () {
pm.expect(item.id).not.eql(undefined);
});
var Ajv = require('ajv');
ajv = new Ajv({
allErrors: allErrors,
logger: console
});
var valid = ajv.validate(pm.globals.get("rspSchema"), item);
if (valid) {
pm.test("Item is valid against schema", function () {
pm.expect(valid).to.be.true; // just to output that schema was validated
});
} else {
ajv.errors.forEach(err => outputItemError(err));
}
};
// check for individual response
var individualCheck = (allErrors) => {
// need to use eval to run this section
basicCheck();
// only preform tests if response is successful
if (pm.response.code === 200) {
var jsonData = pm.response.json();
pm.test("ID is expected ID", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).eql(pm.environment.get("nextItemId"));
});
itemCheck(jsonData, allErrors);
}
}
individualCheck(true);
just create a function to do an item test where I do a stupid assert.false to output each individual error in the schema path

MVC Parallel transactions and session objects

I can't get the session values when I start a different operation while an operation is in progress like below;
$.ajax({
type: 'GET',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});
Controller side;
public ActionResult StartOperation(string customerId)
{
Session["OperationId"] = "operationid";
// Some web api transactions (This operations takes a few minutes.)
var data = new { Result = "Operation Completed." };
return Json(data, JsonRequestBehavior.AllowGet);
}
I am sure about Session["OperationId"] is not null, and then I call my cancel action while web api transactions in progress;
$(function () {
$('#btnCancelLogin').on('click', function () {
$.ajax({
type: 'GET',
cache: false,
url: '/Home/CancelOperation'
});
});
});
Controller side;
public ActionResult CancelOperation()
{
String operationId = Session["OperationId"] as String // return null
//Cancel operations
}
Why Session["OperationId"] is always null on CancelOperation() method ? Thanks for advices.
if you take data from ajax side for start operation you should use post. Actually your ajax type is incorrect.
$.ajax({
type: 'POST',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});
Or if you want to take data from controller you should return data
public ActionResult StartOperation(string customerId)
{
Session["OperationId"] = "operationid";
// Some web api transactions
return json(customerId);
}
also your ajax should be like this
$.ajax({
type: 'GET',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});

Rally sdk - get list of tasks from a story object

Know how to get list of tasks from a Rally story object? The Tasks is list in story. I tried with story.get("Tasks") and story.getCollection("Tasks"). But both the methods throw undefined error in debugger
Ext.Array.each(stories, function(story){
var storyTasks = ***story.get('Tasks');***
storyTasks.load({
fetch: ['Owner', 'FormattedID'],
callback: function(records, operation, success){
Ext.Array.each(records, function(record){
taskOwners.push({owner: record.get('Owner'),
points: story.PlanEstimate});
}, this);
},
scope: this
});
});
There's a really nice example of how to do this in the docs:
https://help.rallydev.com/apps/2.1/doc/#!/guide/collections_in_v2-section-collection-fetching
Here is an example that does it with promises:
launch: function() {
var stories = Ext.create('Rally.data.wsapi.Store', {
model: 'UserStory',
fetch: ['Tasks']
});
stories.load().then({
success: this.loadTasks,
scope: this
}).then({
success: function() {
//great success!
},
failure: function(error) {
//oh noes!
}
});
},
loadTasks: function(stories) {
var promises = [];
_.each(stories, function(story) {
var tasks = story.get('Tasks');
if(tasks.Count > 0) {
tasks.store = story.getCollection('Tasks');
promises.push(tasks.store.load());
}
});
return Deft.Promise.all(promises);
}

Why does YouTube's V3 API duplicate response data inside of a "result" object?

I'm calling YouTube's V3 API like so:
// Expects options: { channelId: string, success: function, error: function };
getChannelTitle: function (options) {
var request = GoogleAPI.client.youtube.channels.list({
part: 'snippet',
id: options.channelId,
fields: 'items/snippet/title'
});
this._executeRequest({
request: request,
success: function (response) {
console.log("response:", response);
options.success(response.items[0].snippet.title);
}
});
},
_executeRequest: function (options) {
options.request.execute(function (response) {
if (!response.error) {
options.success(response);
}
});
}
Everything works as expected, but the response from the request is a bit interesting:
Why is all of the response information duplicates inside of a "result" object? I don't see this from the API explorer: https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.list?part=snippet&id=UC_Gkp1Oa7e2a8NNaf5-KCpA&fields=items%252Fsnippet%252Ftitle&_h=5&

Resources