How to catch (and display on the client) server-side OData business validation errors in JayData using AngularJs - jaydata

If I am using code such as this (from: http://jaydata.org/blog/jaydata-and-angularjs-continued):
$scope.saveChanges = function () {
$scope.northwind.saveChanges()
.then(function () {
$scope.selectedProduct = null;
},function() {
$scope.northwind.stateManager.reset();
});
};
How do I catch any server-side business validation errors that the server may return?

This works:
$scope.saveChanges = function () {
$scope.ApplicationData.saveChanges()
.then(function () {
$scope.selectedToDo = null;
}, function (error) {
var xml = error.message,
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$ValidationResults = $xml.find("ValidationResults");
angular.forEach($ValidationResults, function (ValidationResult) {
angular.forEach(ValidationResult.childNodes, function (childNode) {
alert(childNode.childNodes[0].textContent);
});
});
$scope.ApplicationData.stateManager.reset();
});
};

Related

Node.js named pipe C#

I am trying to make a NodeJS program and a c# communicate but I can't get the communication working. I think it used to work before but after an update, I needed to change the NodeJS code, and since I really don't have much experience with NodeJS I probably messed up something there. Help would be appreciated.
NodeJS code:
logCommand(req, resp) {
const { command } = req;
var PIPE_NAME = "mypipe";
var PIPE_PATH = "\\\\.\\pipe\\" + PIPE_NAME;
var server = net.createServer(function (stream) {
stream.on('data', function (c) {
});
stream.on('end', function () {
server.close();
});
});
server.on('close', function () {
server.close();
})
server.listen(PIPE_PATH, function () {
})
let logfile = fs.createWriteStream(path.join(config.Config.App.filesPath, 'CairossRun.txt'), {
flags: 'a',
autoClose: true
});
let text1 = `error\n\n`
if (resp.win_lose === 1) {
text1 = `Run: Succes\nTypeOfReward: NoRune\nEndOfTransmission\n\n`;
const rewards = resp.changed_item_list ? resp.changed_item_list : [];
if(rewards){
rewards.forEach(reward => {
if (reward.type === 8) {
text1 = `Run: Succces\nTypeOfReward: Rune\nRuneType: ${JSON.stringify(reward.info.rank)}\nRuneSlot: ${JSON.stringify(reward.info.slot_no)}\nRuneSet: ${JSON.stringify(reward.info.set_id)}\nRuneStars: ${JSON.stringify(reward.info.class)}\nEndOfTransmission\n\n`;
}
});
}
}
else {
text1 = `Run: Failed\nnEndOfTransmission\n\n`;
}
server.on('connection', function (stream) {
stream.write(text1);
})
server.on('drain', function (stream) {
stream.write(text1);
})
C# code:
public bool Connecting()
{
Console.WriteLine("connecting");
pipe = new NamedPipeClientStream(".", "mypipe", PipeDirection.In);
try
{
pipe.Connect(5000);
}
catch (TimeoutException e)
{
}
if (pipe.IsConnected)
{
Console.WriteLine("connected");
fileReader = new StreamReader(pipe);
return true;
}
else
return false;
}

Migrating callbacks to Async

I'm struggling with migrating a HAPI function that verifies a JWT token and then makes a database call using the decoded credentials.
The problem is that jwt.verify uses a callback, but Hapi and Hapi.MySQL2 have both been updated to use async functions
The main function is as follows
exports.LoadAuth = (req, h) => {
let token = req.headers.authorization.split(' ')[1]
VerifyToken(token, async function (err, decoded) {
if (!err) {
let sql = '#SELECT STATEMENT USING decoded.id'
const [data] = await mfjobs.query(sql, decoded.id)
let auids = []
data.forEach(function (ag) {
auids.push(ag.Name)
})
auids = base64(auids.toString())
return auids
} else {
return {message: 'Not Authorised'}
}
})
}
The VerifyToken function is as follows:
VerifyToken = (tok, done) => {
jwt.verify(tok, Buffer.from(secret, 'base64'), function (err, decTok) {
if (err) {
done(err)
} else {
done(null, decTok)
}
})
}
Debugging everything above works up to the point that the data should be returned to the front end. At which point I get an ERROR 500
I know that the issue is with the VerifyToken function as if I omit this and hard code the decoded.id into the query the correct data reaches the front end.
Any pointers?
You can convert your VerifyToken function to Promises.
let VerifyToken = (tok) => {
return new Promise((resolve, reject) => {
jwt.verify(tok, Buffer.from(secret, 'base64'), function (err, decTok) {
if (err) {
reject(err)
} else {
resolve(decTok)
}
})
});
}
Now you have a function that you can use with async await notation and internally checks jwt validation via callbacks.
Then we can slightly modify your controller as follows.
exports.LoadAuth = async (req, h) => {
let token = req.headers.authorization.split(' ')[1];
try {
let decoded = await VerifyToken(token);
let sql = '#SELECT STATEMENT USING decoded.id';
const [data] = await mfjobs.query(sql, decoded.id);
let auids = [];
data.forEach(function (ag) {
auids.push(ag.Name)
});
auids = base64(auids.toString());
return auids
} catch (e) {
return {message: 'Not Authorised'}
}
}
We just converted your handler function to async function, and we already have a VerifyToken function that returns a promise so, we can call it with the await operator.

Protractor specs leaking

I'm still quite new to promises and the like and I need some help with this problem. One of my it blocks does not end before the next one begins ending up in a StaleElementReferenceError a whole specfile later from where the code was supposed to be called.
listView.js (I know it looks weird but I set it up this way for an unrelated reason):
module.exports = function () {
var public = {};
public.checkFilters = function (filters) {
var promises = [];
for (var i = 0; i < filters.length; i++) {
promises[i] = getFilterPromise(filters[i]);
}
return protractor.promise.all(promises);
};
var getFilterPromise = function (filter) {
return public.getHeaderIndex(filter.on).then(function (headerIndex) {
return checkRows(filter.values, headerIndex);
});
};
public.getHeaderIndex = function (text) {
var headers = table.all(by.tagName('th'));
var correctHeaderIndex;
return headers.each(function (header, index) {
header.getText().then(function (actualHeaderText) {
if (actualHeaderText === text) {
correctHeaderIndex = index;
}
})
}).then(function () {
return new Promise(function (resolve, reject) {
if (correctHeaderIndex) {
resolve(correctHeaderIndex);
} else {
reject('Header not found');
}
});
});
};
public.getWorkflowCount = function () {
return workflows.count();
};
var checkRows = function (matchers, headerIndex) {
var mismatch = false;
return workflows.each(function (element, index) {
public.getTextFromCell(index, headerIndex).then(function (actual) {
if (!anyMatch(actual, matchers)) {
mismatch = true;
}
});
}).then(function () {
return new Promise(function (resolve, reject) {
if (mismatch) {
reject('Header not found');
} else {
resolve('all rows matched');
}
});
});
};
var anyMatch = function (actual, matchers) {
var match = false;
for (var j = 0; j < values.length; j++) {
if (text === values[j]) {
match = true;
}
}
return match;
};
public.getTextFromCell = function (row, column) {
return workflows.get(row).all(by.tagName('td')).get(column).getText();
};
return public;
}();
LV_00:
describe('LV_00:', function () {
it('statusfilter', function () {
P.listView.filter('status', H.regStatus.S.inProgress);
});
it('statusfilter works', function () {
P.listView.checkFilters([{
on: H.lang.S.status,
values: [H.regStatus.S.inProgress]
}]);
});
});
I think you should move the test preparation code into the beforeEach():
describe('LV_00:', function () {
beforeEach('statusfilter', function () {
P.listView.filter('status', H.regStatus.S.inProgress);
});
it('statusfilter works', function () {
P.listView.checkFilters([{
on: H.lang.S.status,
values: [H.regStatus.S.inProgress]
}]);
});
});
You may also need to use the done callback function:
describe('LV_00:', function (done) {
beforeEach('statusfilter', function () {
P.listView.filter('status', H.regStatus.S.inProgress).then(function () {
done();
});
});
it('statusfilter works', function () {
P.listView.checkFilters([{
on: H.lang.S.status,
values: [H.regStatus.S.inProgress]
}]);
});
});
assuming filter() returns a promise.
Found the solution thanks to alecxe proposing to use done() I used the following after some googling around.
it('statusfilter', function () {
P.listView.filter('status', H.regStatus.S.inProgress);
});
it('statusfilter works', function () {
protractor.promise.controlFlow().execute(function () {
return P.listView.checkFilters([{
on: H.lang.S.status,
values: [H.regStatus.S.inProgress]
}]);
});
});
Found here: Prevent Protractor from finishing before promise has been resolved

No Data from Service to Controller to Scope -> Result Undefined Angularjs Ionic

My problem is, that the controller just send an undefiend and not the data from http of service. I inspect it with chrome. I am new at ionic. By calling the AppSqliDBFactory.getMasterdataId() method, it shows an undefiend, also at the scope variable.
.controller('ReadMasterdataCtrl', function ($scope, $state, $ionicNavBarDelegate, MasterdataService, AppSqliDBFactory){
$scope.masterdataId;
$scope.masterdataData;
AppSqliDBFactory.getMasterdataId().then( function (masterdata){
$scope.masterdataId = masterdata[0].masterdataId;
}).catch(function (err){
console.log(err);
});
//here is the error -> no data at "$scope.masterdataData = masterdata;"
MasterdataService.getMasterdataDB($scope.masterdataId)
.then(function (masterdata) {
$scope.masterdataData = masterdata;
console.log("getMasterdataDB respont");
console.log($scope.masterdataData);
}).catch(function (err) {
console.log(err);
});
})
//Service
.factory('MasterdataService', function ($q, $http, SERVER_URL) {
//Create JSON Object
var srv = {};
//Array for JSON Objects
srv.masterdata = [];
srv.getMasterdataDB = function (masterdataId) {
var deferred = $q.defer();
var masterdata;
var masterdataId = masterdataId;
var baseUrl = 'xxxx';
$http.get(SERVER_URL + baseUrl + masterdataId).success(function (response){
masterdata = response[0];
console.log(masterdata);
return deferred.resolve(masterdata);
}).error(function (err){
return deferred.reject(err);
});
return deferred.promise;
//return srv.getMasterdata();
};
// Public API
return {
getMasterdataDB: function ( masterdataId) {
return $q.when(srv.getMasterdataDB( masterdataId));
}
};
});
Simplified:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
});
MasterdataService.getMasterdataDB($scope.masterdataId).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
When MasterdataService.getMasterdataDB() is called, AppSqliDBFactory.getMasterdataId() may not have been resolved yet, so $scope.masterdataId can be undefined (which is probably what is happening in your case).
You have to call AppSqliDBFactory.getMasterdataId() after AppSqliDBFactory.getMasterdataId() has been resolved:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
MasterdataService.getMasterdataDB($scope.masterdataId).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
});
Or with chaining:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
return MasterdataService.getMasterdataDB($scope.masterdataId);
}).then(function (masterdata) {
$scope.masterdataData = masterdata;
});

KnockoutJS : initial values are not posted to server when using ko.toJSON(this)?

I've this javascript viewmodel defined:
function PersonViewModel() {
// Data members
this.Name = ko.observable();
this.Function_Id = ko.observable();
this.SubFunction_Id = ko.observable();
this.Functions = ko.observableArray();
this.SubFunctions = ko.observableArray();
// Whenever the Function changes, update the SubFunctions selection
this.Function_Id.subscribe(function (id) {
this.GetSubFunctions(id);
}, this);
// Functions to get data from server
this.Init = function () {
this.GetFunctions();
this.Function_Id('#(Model.Function_Id)');
};
this.GetFunctions = function () {
var vm = this;
$.getJSON(
'#Url.Action("GetFunctions", "Function")',
function (data) {
vm.Functions(data);
}
);
};
this.GetSubFunctions = function (Function_Id) {
var vm = this;
if (Function_Id != null) {
$.getJSON(
'#Url.Action("GetSubFunctions", "Function")',
{ Function_Id: Function_Id },
function (data) {
vm.SubFunctions(data);
}
);
}
else {
vm.SubFunction_Id(0);
vm.SubFunctions([]);
}
};
this.Save = function () {
var PostData = ko.toJSON(this);
var d = $.dump(PostData);
alert(d);
$.ajax({
type: 'POST',
url: '/Person/Save',
data: PostData,
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
};
}
$(document).ready(function () {
var personViewModel = new PersonViewModel();
personViewModel.Init();
ko.applyBindings(personViewModel);
});
When the Submit button is clicked, the data from the select lists is posted, but NOT the 'Function_Id'.
When I choose a different value in the Function dropdown list, and the click the Submit button, the value for 'Function_Id' is correctly posted.
How to fix this ?
It's because the scope of the this keyword in javascript
this.Init = function () {
this.GetFunctions(); // this === PersonViewModel.Init
this.Function_Id('#(Model.Function_Id)'); // calls PersonViewModel.Init.Function_Id(...)
};
You should store the refrence to the PersonViewModel instance.
var self = this;
self.Init = function () {
self.GetFunctions();
self.Function_Id('#(Model.Function_Id)'); // calls PersonViewModel.Function_Id(...)
};