Calling Predicate() constructor causes Knockout to throw unexplained exception. - breeze

I'm new to breeze and I can't begin to imagine what's causing this to happen. This is a two part question:
1) My function is very simple. I'm querying with two predicates:
var getUserHealthMetricFromId = function (userId, healthMetricId, forceRemote) {
var p1 = new Predicate('userId', '==', userId);
var p2 = new Predicate('healthMetricId', '==', healthMetricId);
var query = EntityQuery.from('UserHealthMetrics').select('lowerValue', 'upperValue')
.where(p1.and(p2));
if (!forceRemote) {
//results = getUserHealthMetricFromLocal(userId, healthMetricId);
var query = query.using(breeze.FetchStrategy.FromLocalCache);
}
var promise = manager.executeQuery(query);
return promise;
};
While I'm debugging (Chrome) the first predicate declaration line, calling the Predicate ctor causes execution to jump to the following finally clause in Knockout-3.0.0.debug.js (line 1483):
finally {
ko.dependencyDetection.end();
_isBeingEvaluated = false;
}
When I execute the "_isBeingEvaluated = false" statement,
an exception is inexplicably thrown landing me here (line 2607):
} catch (ex) {
ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
throw ex;
}
Thinking this might have more to do with Knockout than with Breeze, I tested by altering the code by hardcoding the Id's so that the parameter variables (which are observables) aren't involved in calling the ctor anymore:
var p1 = new Predicate('userId', '==', 1);
var p2 = new Predicate('healthMetricId', '==', 4);
No dice. The same thing happens. When I try to step into Predicate() the same thing happens. I just throws me over to the knockout debug file.
2) In the same function, the variables I'm passing in are showing up as dependentObservables() in the debug window. These values are the product of another breeze call to the server. Why would breeze render these as dependentObservables instead of plain observables (I do not declare any computeds anywhere in the code)? Here's a quick overview of my code:
In the view model:
var latestEntriesObservable = ko.observableArray(null);
function activate() {
$('#rangeDialog').hide();
var promise = Q.all([datacontext.getLatestEntries(latestEntriesObservable, currentUserId, false),
datacontext.getUserHealthMetrics(userHealthMetricsObservable, currentUserId, false),
datacontext.getUserHealthMetricNames(userHealthMetricNamesObservable, currentUserId, false)]);
return promise;
}
var getLatestEntries = function (latestEntriesObservable, userId, forceRemote) {
var lastEntryQuery = EntityQuery.from('LatestEntries').withParameters({ id: 1 });
if (!forceRemote) {
var e = getLocal('HealthMetricValues', 'healthMetricId');
if (e.length > 0) {
latestEntriesObservable(e);
return Q.resolve();
}
}
return manager.executeQuery(lastEntryQuery)
.then(querySucceeded)
.fail(queryFailed);
// handle the ajax callback
function querySucceeded(data) {
if (latestEntriesObservable) {
latestEntriesObservable(data.results);
//latestEntriesObservable(model.toProtectedObservableItemArray(data.results));
}
log('Retrieved latest entries.', data, true);
}
};
function getLocal(resource, orderBy) {
var query = EntityQuery.from(resource).orderBy(orderBy).withParameters({ id: 1 });
return manager.executeQueryLocally(query);
}
If I haven't provided enough code to help make a diagnosis I'll be happy to provide more upon request.
Any suggestions would be much appreciated!

Ok, I think the issue is that the class is actually breeze.Predicate. In order to save typing we often assign a local variable like this.
var Predicate = breeze.Predicate;
var p1 = new Predicate('userId', '==', 1);
or you can explicitly do this via
var p1 = new breeze.Predicate('userId', '==', 1);
or
var p1 = breeze.Predicate.create('userId', '==', 1);
Presumably, you are doing the same thing with EntityQuery, i.e.
var EntityQuery = breeze.EntityQuery;

Related

Why my md-autoComplete is not displaying return values

I am using Angular Material for the first time. I am stuck with an issue with autocomplete. Below is my template:
<md-autocomplete class="flex"
md-no-cache="true"
md-selected-item="c.receipt"
md-item-text="item.name"
md-search-text="SearchText"
md-items="item in querySearch(SearchText)"
md-floating-label="search">
<md-item-template>
<span><span class="search-result-type">{{item.GEOType}}</span><span md-highlight-text="SearchText">{{item.GEOName+(item.country?' / '+item.country:'')}}</span></span>
</md-item-template>
<md-not-found>No matches found.</md-not-found>
</md-autocomplete>
And in ctrl I have:
$scope.querySearch = function (query) {
var GeoDataAPIUrl = '/api/TargetSettings/RetrieveCorridorLeverValues';
if (query.length < 5)
return;
else {
var GeoDataSearchUrl = GeoDataAPIUrl + '?' + 'strGeoName=' + query;
$http
.get(GeoDataSearchUrl)
.then(function (geoAPIResponse) {
console.log("GeoAPIResponse was ", geoAPIResponse);
return geoAPIResponse.data;
},
function (geoAPIError) {
console.log("GeoAPI call failed ", geoAPIError);
});
}
};
With above code, I am getting nothing as suggestions, only my not-found text is displayed, while my http call return an array which is printed in console too. Am I missing something??
I saw at many places, people have used some filters with autocomplete, I dont think that is something essential.
Pls advice how to make above work.
$http returns promise and md-autocomplete uses same promise to display the result. In your case you are returning result but not promise. Your code should be
$scope.querySearch = function (query) {
var GeoDataAPIUrl = '/api/TargetSettings/RetrieveCorridorLeverValues';
if (query.length < 5)
return;
else {
var GeoDataSearchUrl = GeoDataAPIUrl + '?' + 'strGeoName=' + query;
var promise = $http.get(GeoDataSearchUrl).then(function (geoAPIResponse) {
console.log("GeoAPIResponse was ", geoAPIResponse);
return geoAPIResponse.data;
},
function (geoAPIError) {
console.log("GeoAPI call failed ", geoAPIError);
});
return promise;
}
};
It will work now.

q promise and map doesn't change after iteration

I'm using Q Promises to retrieve data from my redis repository. The problem I'm having, is that through each iteration, the array object (localEncounter) I'm using to store data returned from the chained functions is never updated at each iteration. Previously, I tried to solve this with a foreach loop and spread but the results were the same.
How should I correct this so that localEncounter is updated at each iteration, and ultimately localEncounters contains correct data when returned? Thank you.
var localEncounters = [];
var localEncounter = {};
Promise.all(ids.map(function(id) {
return localEncounter, getEncounter(id, client)
.then(function (encounter) {
encounterObject = encounter;
//set the fields for the return object
localEncounter['encounterid'] = encounterObject[f_id];
localEncounter['screeningid'] = encounterObject[f_screening_id];
localEncounter['assessmentid'] = encounterObject[f_clinical_assessment_id];
localEncounter['psychevalid'] = encounterObject[f_psych_eval_id];
//get screening
return getScreening(encounterObject[f_screening_id], client);
})
.then(function (screening) {
//set the fields for the return object
localEncounter['screeningbegintime'] = screening[f_begin_time];
//get assessment
return getAssessment(localEncounter['assessmentid'], client);
})
.then(function (assessment) {
//set the fields for the return object
localEncounter['assessmentbegintime'] = assessment[f_begin_time];
//get psycheval
//localEncounters.push(assessment);
return getPsychEval(localEncounter['psychevalid'], client);
})
.then(function (psychEval) {
//set the fields for the return object
localEncounter['assessmentbegintime'] = psychEval[f_begin_time];
localEncounters.push(localEncounter);
}
, function (reason) {
console.log(reason); // display reason why the call failed;
reject(reason, 'Something went wrong creating the encounter!');
})
})).then(function(results) {
// results is an array of names
console.log('done ');
resolve(localEncounters);
})
Solution: I only needed to move the declaration of localEncounter inside the map iterator
before:
var localEncounter = {};
Promise.all(ids.map(function(id) {
after:
Promise.all(ids.map(function(id) {
var localEncounter = {};
This now allows that each id iteration gets its own localEncounter object.

breeze observableArray binding - are properties observable?

I have a viewmodel which consists of a list(foreach loop) of DoctorPrices and when clicking on an item in the list it open up a CRUD form on the side. However when i update the values on the CRUD the observableArray that is bound to the foreach is not refreshing? (although the values are updates in the DB correctly)
From my data access module i call the following query.
function getDoctorServices(doctorId) {
var query = breeze.EntityQuery
.from('DoctorPrices')
.where('DoctorID', 'eq', doctorId).orderBy('ListOrder');
return manager.executeQueryLocally(query);
}
In my viewmodel i have the following code:
this.services = ko.computed(function() {
return doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID());
});
services is bound using a foreach loop (not posting here as the code is simple and works)
When i click on a one of the DoctorPrices it gets the data as follows and places it in an observable:
this.selectedPrice = function (data, event) {
self.currentService(data);
self.showEdit(true);
};
I then bind selectPrice to a simple form that has the properties on it to be modified by the user. I then call manager.SaveChanges().
This results in the following problem: the value is being updated correctly but the GUI / Original List that is bound in the foreach is not being updated? Are the properties in breeze not observables? What is the best way to work with something like this.
I thought of a workaround and changing the code with something like this:
doctorList.viewModel.instance.currentDoctorID.subscribe(function() {
self.services([]);
self.services(doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID()));
});
But i feel that clearing the array in that way is sloppy and not the right way of doing things specially with long lists.
Can someone please point me in the right direction on how to bind observableArray properties properly so they are updated?
Additional code my VM Component:
function services() {
var self = this;
this.showForm = ko.observable(false);
this.currentService = ko.observable();
this.services = ko.observableArray(doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID()));
this.title = ko.observable();
doctorList.viewModel.instance.currentDoctorID.subscribe(function() {
self.services([]);
self.services(doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID()));
self.showDetails(false);
});
this.show = function (value) {
self.showForm(value);
};
this.showDetails = ko.observable(false);
this.addNewService = function() {
self.currentService(doctorServices.createService(doctorList.viewModel.instance.currentDoctorID()));
console.log(self.currentService().entityAspect.entityState);
self.showDetails(true);
};
this.showDelete = ko.computed(function() {
if (self.currentService() == null)
return false;
else if (self.currentService().entityAspect.entityState.isDetached()) {
self.title('Add new service');
return false;
} else {
self.title('Edit service');
return true;
}
});
this.deleteService = function() {
self.currentService().entityAspect.setDeleted();
doctorServices.saveChanges();
doctorList.viewModel.instance.currentDoctorID.notifySubscribers();
};
this.closeDetails = function () {
doctorServices.manager.rejectChanges();
doctorList.viewModel.instance.currentDoctorID.notifySubscribers();
self.showDetails(false);
};
this.selectService = function (data, event) {
self.currentService(data);
self.showDetails(true);
};
this.saveChanges = function () {
console.log(self.currentService().entityAspect.entityState);
if (self.currentService().entityAspect.entityState.isDetached()) {
doctorServices.attachEntity(self.currentService());
}
console.log(self.currentService().entityAspect.entityState);
doctorServices.saveChanges();
doctorList.viewModel.instance.currentDoctorID.notifySubscribers();
self.currentService.notifySubscribers();
self.showDetails(true);
};
}
return {
viewModel: {
instance: new services()
},
template: servicesTemplate,
};
Below is my Breeze Data Class:
define('data/doctorServices', ['jquery', 'data/dataManager', 'knockout','mod/medappBase', 'breeze', 'breeze.savequeuing'], function ($, manager, ko,base, breeze, savequeuing) {
var services = ko.observableArray([]);
return {
attachEntity:attachEntity,
getServices: getServices,
services: services,
manager:manager,
getDoctorServices: getDoctorServices,
getServiceById: getServiceById,
createService:createService,
hasChanges: hasChanges,
saveChanges: saveChanges
};
function getServices() {
var query = breeze.EntityQuery.from("DoctorPrices");
return manager.executeQuery(query).then(function (data) {
services(data.results);
}).fail(function (data) {
console.log('fetch failed...');
console.log(data);
});;
}
function getDoctorServices(doctorId) {
var query = breeze.EntityQuery
.from('DoctorPrices')
.where('DoctorID', 'eq', doctorId).orderBy('ListOrder');
var set = manager.executeQueryLocally(query);
return set;
}
function getServiceById(serviceId) {
return manager.createEntity('DoctorPrice', serviceId);
//return manager.getEntityByKey('DoctorPrice', serviceId);
}
function handleSaveValidationError(error) {
var message = "Not saved due to validation error";
try { // fish out the first error
var firstErr = error.innerError.entityErrors[0];
message += ": " + firstErr.errorMessage;
base.addNotify('error', 'Could not save.', message);
} catch (e) { /* eat it for now */ }
return message;
}
function hasChanges() {
return manager.hasChanges();
}
function attachEntity(entity) {
manager.addEntity(entity);
}
function createService(doctorId) {
return manager.createEntity('DoctorPrice', { DoctorPricingID: breeze.core.getUuid(), DoctorID:doctorId }, breeze.EntityState.Detached);
};
function saveChanges() {
return manager.saveChanges()
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
base.addNotify('success', 'Saved.', 'Your updates have been saved.');
}
function saveFailed(error) {
var reason = error.message;
var detail = error.detail;
if (error.innerError.entityErrors) {
reason = handleSaveValidationError(error);
} else if (detail && detail.ExceptionType &&
detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
// Concurrency error
reason =
"Another user, perhaps the server, " +
"may have deleted one or all of the settings." +
" You may have to restart the app.";
} else {
reason = "Failed to save changes: " + reason +
" You may have to restart the app.";
}
console.log(error);
console.log(reason);
}
}
});
Please note this is my frist attempt at both a data class and VM. At the moment i am relying heavily on clearing the array ([]) and using notifySubscribers to make the array refresh :(
I bet you're missing an observable somewhere. I can't tell because you keep hopping from property to property whose definition is not shown.
For example, I don't know how you defined this.currentService.
I'm confused by this:
this.services = ko.computed(function() {
return doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID());
});
Why is it a ko.computed? Why not just make it an observable array.
self.service = ko.observableArray();
// ... later replace the inner array in one step ...
self.service(doctorServices.getDoctorServices(
doctorList.viewModel.instance.currentDoctorID()));
I urge you to follow the observability trail, confident that your Breeze entity properties are indeed observable.
vm.selectedPrice = ko.dependentObservable(function () {
return doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID());
}, vm);
vm is ur model on which u applied bindings , try this it will work.

Error Breeze OData - Metadata query failed for http://localhost:5781/odata/$metadata

I researched questions on forum but not find true result.
Error:
Metadata query failed for //localhost:5781/odata/$metadata; Unable to process returned
metadata: NamingConvention for this server property name does not roundtrip
properly:diagram_id-->Diagram_id Error: Metadata query failed for //localhost:5781/odata/$metadata; Unable to process returned metadata: NamingConvention for this server property name does not roundtrip properly:diagram_id
Code
(function () {
'use strict';
var serviceId = 'entityManagerFactory';
angular.module('myApp')
.factory(serviceId, ['breeze', emFactory]);
function emFactory(breeze) {
configureBreeze();
var serviceRoot = window.location.protocol + '//' + window.location.host + '/';
var serviceName = serviceRoot + 'odata/';
var factory = {
newManager: newManager,
serviceName: serviceName
};
return factory;
function configureBreeze() {
// use Web API OData to query and save
breeze.config.initializeAdapterInstance('dataService', 'webApiOData', true);
// convert between server-side PascalCase and client-side camelCase
breeze.NamingConvention.camelCase.setAsDefault();
}
function newManager() {
var mgr = new breeze.EntityManager(serviceName);
return mgr;
}
}})();
Code other :
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('myApp')
.factory(serviceId, ['$q', 'logger', 'entityManagerFactory', datacontext]);
function datacontext($q,logger,emFactory) {
logger = logger.forSource(serviceId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
var manager = emFactory.newManager();
var service = {
getEmployees: getEmployees
};
return service;
/*Hiện thực ở đây*/
function getChangesCount(){
return manager.getChanges().length;
}
function getEmployees(forceRefresh) {
var count;
if (forceRefresh) {
if(manager.hasChanges()){
count = getChangesCount();
manager.rejectChanges();//undo tất cả các thay đổi ko được lưu
logWarning('Số nhân viên' + count + 'bị thay đổi', null, true);
}
}
// Lúc ko có forceRefesh,xem xét nhận bộ nhớ cache hơn từ xa
return breeze.EntityQuery.from('Employees')
.using(manager).execute()
.then(success).catch(failed);
function success(response) {
count = response.results.length;
logSuccess('Đã nhận ' + count + ' nhân viên', response, true);
return response.results;
}
function failed(error) {
var message = error.message || "Truy vấn để bảng nhân viên bị lỗi";
logError(message, error, true);
}
}
}})();
Code other :
(function () {
'use strict';
var controllerId = 'employees';
angular.module('myApp')
.controller(controllerId, ['datacontext', 'logger', employees]);
function employees(datacontext, logger) {
logger = logger.forSource(controllerId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var vm = this;
vm.employees = [];
initialize();
/*Hiện thực*/
function initialize() {
getEmployees();
}
function getEmployees(forceRefresh) {
return datacontext.getEmployees(forceRefresh).then(function (data) {
return vm.employees = data;
console.log(data);
});
}
}}());
This problem very likely has to do with the camelCase naming convention and the language and/or property names that you are using. My guess is that if you remove the line that sets camelCase as the default then the error will go away. If so, then you will need to write your own custom naming convention. See http://www.breezejs.com/documentation/naming-convention
The reason that this is occurring, (I'm guessing here), is that the camelCase naming convention is very simplistic and may not work for your property names and/or language. It assumes that all server property names begin with an uppercase character and that this character can be converted to a lowercase character, and further that this process can be reversed. My guess is that one of your property names already has a first character that is lower case or that calling toLower/toUpper on some first character in a property name does not itself roundtrip. (This can occur is some non-latin character sets).
If either of these cases is occuring, its actually rather easy to create your own namingConvention to use instead of 'camelCase'. Again see the docs mentioned above.

How to create a "loading" spinner in Breeze?

I'm trying to create a loading spinner that will be displayed when breeze is communicating with the server. Is there some property in Breeze that is 'true' only when breeze is sending data to the server, receiving data, or waiting for a response (e.g. after an async call has been made but no response yet)? I thought of binding this data to a knockout observable and binding the spinner to this observable,
Thanks,
Elior
Use spin.js
http://fgnass.github.io/spin.js/
Its so simple..make it visible before you execute the query and disable it after the query succeeds or fails.
I don't see any property that is set or observable while Breeze is querying, but if you are using a datacontext, or some JavaScript module for your data calls, this is what you can do -
EDIT
Taking John's comments into account, I added a token'd way of tracking each query.
var activeQueries = ko.observableArray();
var isQuerying = ko.computed(function () {
return activeQueries().length !== 0;
});
var toggleQuery = function (token) {
if (activeQueries.indexOf(token) === -1)
{ activeQueries.push(token); }
else { activeQueries.remove(token); }
};
var getProducts = function (productsObservable, forceRemote) {
// Don't toggle if you aren't getting it remotely since this is synchronous
if (!forceRemote) {
var p = getLocal('Products', 'Product','product_id');
if (p.length > 0) {
productsObservable(p);
return Q.resolve();
}
}
// Create a token and toggle it
var token = 'products' + new Date().getTime();
toggleQuery(token);
var query = breeze.EntityQuery
.from("Products");
return manager.executeQuery(query).then(querySucceeded).fail(queryFailed);
function querySucceeded(data) {
var s = data.results;
log('Retrieved [Products] from remote data source', s, true);
// Toggle it off
toggleQuery(token);
return productsObservable(s);
}
};
You will need to make sure all of your fail logic toggles the query as well.
Then in your view where you want to place the spinner
var spinnerState = ko.computed(function () {
datacontext.isQuerying();
};

Resources