How to save data into smart table in UI5? - odata

I have a smart table which has editable fields, I want to save these multiple records in the backend. How should I achieve this?
oModel.create("/Set", [{obj1}, {obj2}])
oModel.createBatchOperation("/set", "POST" , obj1)
oModel.createKey("set" , obj)
oModel.submitChanges()
All of them
use batch call, giving
same error -- 400 -- XML parse error.

If you are using sap.ui.model.odata.v2.ODataModel use below code
var oModel = this.getView().getModel();//gets the v2 odata model
oModel.setUseBatch(true);//setting batch true if not already set
var jModel = oTable.getModel("jTabModel").getProperty("/Carriers");
for (var i = 0; i < jModel.length; i++) {
var oEntry = jModel[i];
oModel.create("/FlightSet", oEntry, {
method: "POST",
success: function(data) {
},
error: function(e) {
}
});
}
oModel.submitChanges({
success: function(data, response) {
//To do
},
error: function(e) {
//To do
}
});

Related

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

Difficulty with upload csv to knockout js table (ASP MVC)

I've been working with these two tutorials, but am having difficulty merging them together to get an upload csv to populate the table. It most likely is my lack of understanding of the view model.
Here's the tutorial for the knockout js editable table from the knockout js site: KnockoutJS: Editable Grid Table
And here's the tutorial for uploading a csv I'm referencing:
KnockoutJS - Upload CSV
Here's the javascript code I've been working on to upload a csv to my table. I keep getting "JavaScript runtime error: Unable to get property 'push' of undefined or null reference" - I marked in comments the problem spot. As you can see, I'm having trouble with the view model.
<script>
var UserModel = function (users) {
var self = this;
self.users = ko.observableArray(users);
self.addUser = function () {
self.users.push({
id: "",
firstName: "",
lastName: ""
});
};
self.removeUser = function (user) {
self.users.remove(user);
};
self.save = function (form) {
sendData = ko.toJSON(self.users);
$.ajax({
url: '/Users/CreateMultiple',
contentType: 'application/json',
async: true,
type: 'POST',
dataType: 'json',
data: sendData,
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS");
}
});
};
};
var viewModel = new UserModel([
{ id: "", firstName: "", lastName: "" }
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
/////
/////Upload CSV
/////
$('#lnkUpload').click(function () {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
reader.onload = Load_CSVData;
reader.readAsText(FileToRead.files.item(0));
}
});
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
UserModel.users.push(new UserModel()//here's my problem
.id(csvID)
.firstName(csvFirstName)
.lastName(csvLastName)
)
});
}
</script>
I was able to identify the fully qualified for the observable array which in turn made it work:
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
viewModel.users.push({
id: csvID,
firstName: csvFirstName,
lastName: csvLastName
});
}

Make Array in Jquery For AJAX Posting

$('#saveplaylist').click(function () {
var length = $(' .organizer-media').length;
var contents=$(' .organizer-media');
var data = null;
for (var i = 0; i < length; i++) {
data[i] = contents[i].title;
}
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
})
As shown above in my code I am not able to send my values by making an array of data filled by using for loop How can I make an array of data & post it through AJAX?
You have to initialize the variable as an array, not null.
var data = [];
In addition to what Barmar said, you need to set content type of your ajax call to JSON
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
Remove space from ' .organizer-media' and ' .organizer-media'
and change
var data = null;
to
var data = new Array();
Instead of JSON.stringify() you could use the $.param() method
$('#saveplaylist').click(function () {
var length = $(' .organizer-media').length;
var contents=$(' .organizer-media');
var data = null;
for (var i = 0; i < length; i++) {
data[i] = contents[i].title;
}
$.ajax({
type: 'POST',
data: $.param({data: data}),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
});
});
This will store the content titles as members of the data array, which you should be able to access server side.
In Rails you would access this like so:
titles = params[:data]
In PHP it might be something like:
$titles = $_POST["data"];
EDIT:
One thing I missed, as Barmar mentioned above, you need to initialize data as an empty array, not null.

Checking if all data has been returned from server in Knockout

I am displaying data from the user on the user page and i would like to notify the user once all the data has been loaded and there is no more data to retrieve from the server using knockout.
Knockout script
$.views.Roster.GetPage = function ( pageNumber) {
$.grain.Ajax.Get({
Url: Views.Roster.Properties.Url,
DataToSubmit: { pageNumber: pageNumber, id: Views.Roster.Properties.Id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
},
OnError: function (jqXHR, status, errorThrown) {
var _response = $.parseJSON(jqXHR.responseText);
$.pnotify({ title:_response.title, text: _response.Message, type: _response.TypeString});
}
});
};
$.views.Roster.ViewModel = {
RosterUsers: ko.observableArray([]),
TotalRoster: null,
CurrentPage: ko.observable(1)
};
$.views.Roster.BindModel = function (data) {
var self = $.views.Roster.ViewModel;
$.views.Roster.ViewModel.TotalRoster = ko.computed(function () {
return self.RosterUsers().length;
});
$.views.Roster.RosterViewModel.AddUsers(data);
ko.applyBindings($.views.Roster.ViewModel);
}
Next = function () {
var _page = $.views.Roster.ViewModel.CurrentPage() + 1;
$.views.Roster.ViewModel.CurrentPage(_page);
$.views.Roster.GetPage(_page);
};
$.views.Roster.RosterViewModel = function (data) {
$.views.Roster.RosterViewModel.AddUsers(data);
};
$.views.Roster.RosterViewModel.AddUsers = function (data) {
$.each(data, function (index, value) {
$.views.Roster.RosterViewModel.PushUser(value);
});
};
$.views.Roster.RosterViewModel.PushUser = function (user) {
$.views.Roster.ViewModel.RosterUsers.push(new $.views.Roster.UserViewModel(user));
};
When you say 'once all the data has been loaded', I assume you mean when the GetPage method finishes loading a single page of users, as that is the only data loading that I see in the code above. Here is one way you can do it:
First, create an observable somewhere that you can bind to to tell the user if data is loading
$.views.Roster.ViewModel = {
RosterUsers: ko.observableArray([]),
TotalRoster: null,
CurrentPage: ko.observable(1),
DataIsLoading: ko.observable(false)
};
And add some markup that shows something in the UI when data is loading
<div data-bind="visible:DataIsLoading">Data is Loading, please wait...</div>
Then set DataIsLoading before you make the ajax call, then reset it when the call is done
$.views.Roster.GetPage = function ( pageNumber) {
$.views.Roster.ViewModel.DataIsLoading(true); // Add this!
$.grain.Ajax.Get({
Url: Views.Roster.Properties.Url,
DataToSubmit: { pageNumber: pageNumber, id: Views.Roster.Properties.Id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
$.views.Roster.ViewModel.DataIsLoading(false); // Add this!
},
OnError: function (jqXHR, status, errorThrown) {
var _response = $.parseJSON(jqXHR.responseText);
$.pnotify({ title:_response.title, text: _response.Message, type: _response.TypeString});
$.views.Roster.ViewModel.DataIsLoading(false); // Add this!
}
});
};

Ajax call to controller method not passing parameter

I am trying to make an AJax call to a controller method the parameter is null no matter what I try. I have followed all the similar SO posts but to no avail. Sorry if the answer is there, I cant find it. The code I have is...
Ajax Call
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
type: 'POST',
dataType: 'json',
data: JSON.stringify({guid: sguid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Controller Method
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
List<DeviceSoftware> ldevice = new List<DeviceSoftware>();
Guid i = Guid.Parse(guid);
ReportMethods reportingMethods = new ReportMethods();
ldevice = reportingMethods.GetNonCompliantApplicationReport(CompanyId);
DeviceSoftware ds = ldevice.Find(x => x.Device.Guid == i);
List<DeviceApplication> da = new List<DeviceApplication>();
if (ds != null)
{
da = ds.DeviceApplications;
}
return Json(da, JsonRequestBehavior.AllowGet);
}
The method is being hit its just guid is alway null. sguid does hold the data I am trying to pass.
Can someone tell me what I am missing?
Against everything I read I changed
data: JSON.stringify({guid: sguid}),
To
data: {guid: sguid},
Now working.
Fred,
You need to make GetBlacklistedSoftwareItems a post method....
try this...
[HttpPost]
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
Small changes needs to be done.
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
contentType: "application/json; charset=utf-8" ,//This is very important
type: 'POST',
dataType: 'json',
Data: JSON. stringify ({guild: squid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Add the contentType: "application/json; charset=utf-8" , to the $.Ajax Call.
:)

Resources