Why I cannot using cookies variable value outside the cookie.get function? - electron

I just began to learning using electron.
I have set a cookie and I want using it value.
function getCookie(cname) {
var value = {
name: cname
};
session.defaultSession.cookies.get(value, function (error, cookies) {
let cookieStr = ''
for (var i = 0; i < cookies.length; i++) {
let info = cookies[i];
cookieStr += `${info.name}=${info.value};`;
console.log(info.value, info.name);
let somevalue = info.value;
}
console.log(cookieStr);
alert(somevalue); //alert 1
});
alert(somevalue); //alert 2
}
</script>
I got the cookieStr value in console.log.
Then in somewhere place, I want to use cookieStr value by calling getcookie(cname) but it keep undefined. How to use the cookie value outside the function?
I have tried display the value with 'alert 1' inside the cookie.get function and it is work. But, the 'alert 2' which outside cookie.get function keep displaying undefined.
Thank you

Reading cookies in electron is an asynchronous function. So its better to call the the function with a callback to return value. or else promisify the function.
function getCookie(cname,callback) {
var value = {
name: cname
};
session.defaultSession.cookies.get(value, function (error, cookies) {
let cookieStr = ''
for (var i = 0; i < cookies.length; i++) {
let info = cookies[i];
cookieStr += `${info.name}=${info.value};`;
console.log(info.value, info.name);
let somevalue = info.value;
}
callback(cookieStr);
});
//alert(somevalue); //alert 2
}
getCookie('test',function(returnValue){
//use the return value here
})

Related

SAPUI5 oData.V2 How to invoke a function after everything in a batch request is done?

I have an issue while making an SAPUI5 odata V2 batch request :
var that = this;
var oServiceModel = that.getModel("oServiceModel");
odataMod = this.getModel("Service");
odataMod.setUseBatch(true);
var aData = oServiceModel.getData();
var stupidService = _.filter(aData, function (ae) {
return ae.Info === "-N/A";
});
var i = 0 ;
_.forEach(stupidService, function (sap) {
oGlobalBusyDialog.setText("Deleting service :" + sap.ObjectID);
oGlobalBusyDialog.setTitle("Deleting Service");
oGlobalBusyDialog.open();
that.removeService(sap).then(function () {
if (i === 615) {
oGlobalBusyDialog.close();
}
}).catch(function () {});
});
my Delete function is like this:
removeService: function (service) {
var that = this;
return new Promise(
function (resolve, reject) {
odataMod.remove('/ProjectTaskServiceCollection(\'' + service.ObjectID + '\')/', {
success: function (oData) {
resolve(oData);
},
error: function (oResult) {
that.handleError(oResult);
oGlobalBusyDialog.close();
reject(oResult);
}
});
});
What's happening ,is that if I'm trying to delete 500 entry, and if 200 entry cannot be deleted, the error message gets displayed 200 times
How to make it in a way to only display the error message once ?
Also, I want to turn off the batch request once everything is done odataMod.setUseBatch(false); how to do it ?
*EDIT: *
I've manage to do :
var aDeffGroup = odataMod.getDeferredGroups();
//add your deffered group
aDeffGroup.push("deletionGroup");
for (var s = 0; s < 5; s++) {
odataMod.remove('/ProjectTaskServiceCollection(\'' + stupidService[s].ObjectID + '\')/', {
//pass groupid to remove method.
groupId: "deletionGroup"
});
}
odataMod.submitChanges({
// your deffered group id
groupId: "deletionGroup",
success: function() {
//Get message model data from Core and it contains all errors
// Use this data to show in dialog or in a popover or set this to your local model see below code
var aErrorData = sap.ui.getCore().getMessageManager().getMessageModel();
console.log(aErrorData);
}
});
yet stills my console.log(aErrorData); still prints multiple error message
Instead of doing individual deletion odata calls. Add these all remove methods in a single group, then call odatamod.submitChanges() method.
Example:
//get all deffered groups
var aDeffGroup = odataMod.getDeferredGroups();
//add your deffered group
aDeffGroup.push("deletionGroup");
//set it back again to odatamodel
odataMod.setDeferredGroups(aDeffGroup);
odataMod.remove('/ProjectTaskServiceCollection(\'' + service.ObjectID + '\')/', {
//pass groupid to remove method.
groupId: "deletionGroup"});
odataMod.submitChanges({
// your deffered group id
groupId:"deletionGroup",
success: function() {
//Get message model data from Core and it contains all errors
// Use this data to show in dialog or in a popover or set this to your local model see below code
var aErrorData = sap.ui.getCore().getMessageManager().getMessageModel();
});

Get Current rows cells values one by one on "BindingSelectionChanged" event from table in html form in Word using office.js

Hello I am creating a application using office.js which will be used in excel and word application addIn and I have written some code that actually gives the text of entire row cell by cell. but as my requirement was to maintain styles and of every cell and store them in database so that when again addin runs it should load the data in same format it was stored. Currently it is just text i am getting in response. I have asked a similar question like this which was to get the text with styles from current cell that really works great.
How do I get the formatting the Current cell of the table in Word using office.js
There is another thing if it is possible to get the cell html by row and column position that will also solve the problem.
Thank you!
Hi i found the solution of my problem but this is solution for word only this is not working in excel but this was working for me so i am writing here :-
function Addtable() {
var document = Office.context.document;
var headers = [["Cities"]];
var rows = [['<b>Hello there</b> <ul><li>One</li><li>Two</li></ul>'], ['Roma'], ['Tokyo'], ['Seattle']];
var html = '<table>';
html += '<thead>';
for (var i = 0; i < headers.length; i++) {
html += '<tr>';
var cells = headers[i];
for (var j = 0; j < cells.length; j++) {
html += '<th>' + cells[j] + '</th>';
}
html += '</tr>';
}
html += '</tr>';
html += '</thead>';
html += '<tbody>';
for (var i = 0; i < rows.length; i++) {
html += '<tr>';
var cells = rows[i];
for (var j = 0; j < cells.length; j++) {
html += '<td>' + cells[j] + '</td>';
}
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
Office.context.document.setSelectedDataAsync(html, { coercionType: Office.CoercionType.Html }, function (asyncResult) {
document.bindings.addFromSelectionAsync(Office.BindingType.Table, function (result) {
console.log(result);
var binding = result.value;
binding.addHandlerAsync(Office.EventType.BindingSelectionChanged, onBindingSelectionChanged);
});
});
}
The above is the function that i call when i want to generate a table with html values in it.
and bellow is is code that i am using to get the value of the current cell and replacing with some dummy value.
var onBindingSelectionChanged = function (results) {
if (!isExecuted) {
Word.run(function (context) {
var tableCell = context.document.getSelection().parentTableCell;
context.load(tableCell);
return context.sync()
.then(function () {
if (tableCell.isNull == true) {
//selection is not within a cell.....
console.log("selection not in a header");
}
else {
// the selection is inside a cell! lets get the content....
var body = tableCell.body;
var html = tableCell.body.getHtml();
var tableHtml = tableCell.body.getHtml();
context.sync()
.then(function () {
var cellHtml = html.value;
var newHtml = "<table><tr><td><ul><li>yellow</li></ul></td></tr></table";
// Option 1
body.insertHtml(newHtml, Word.InsertLocation.replace);
// Option 2
//body.clear();
//body.insertHtml(newHtml, Word.InsertLocation.end);
return context.sync().then(function () {
console.log('HTML was successfully replaced.');
}).catch(function (e) {
console.log(e.message);
});
}).catch(function (e) {
console.log(e.message);
});
}
}).catch(function (e) {
console.log(e.message);
});
});
isExecuted = true;
}
else {
isExecuted=false;
}
};
Thank you!

Add a key on the fly Cloud Code Parse

I want to add a key on the fly to an object, for example, I run a query to get the Items (class Test), next for each item a count the number of Favorite Records it has (suppose that 1 is the UserId). But, when a I call the function from iOS (Swift), I'm getting the list of PFObject, but not has the dynamic key (I don't want to save the Key on Items (class Test), because that's only to get the data on the fly).
Parse.Cloud.define("getAllItemsTestInstag",function(request,response){
var query = new Parse.Query("Test");
query.find().then(function(tests){
var elementProcessed = 0;
for (var i = 0; i < tests.length; i++) {
var testItem = tests[i];
var innerQuery = new Parse.Query("Favorite");
innerQuery.equalTo("UserId",1);
innerQuery.equalTo("Test",testItem);
innerQuery.count({
success: function(count){
if(count == 0){
testItem.set("related",true);
}else{
testItem.set("related",false)
}
console.log("Relacion conteo : " + count);
elementProcessed++;
if(elementProcessed == tests.length){
response.success(tests);
}
},
error: function(error){
console.log(error);
}
});
};
});
});
You can just add the new key, without saving and then return it in response.success. Something like this:
...
innerQuery.count({
success: function(count){
if(count == 0){
testItem.set("related",true);
}else{
testItem.set("related",false)
}
testItem.count = count;
console.log("Relacion conteo : " + count);
elementProcessed++;
if(elementProcessed == tests.length){
response.success(tests);
}
},
error: function(error){
console.log(error);
}
});
...

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.

Kendo UI Datasource onRequestEnd e.response.Data not found

i'm trying to intercept datetime value in kendo datasource to adjust UTC time offset but i can't find the e.response.Data property
code
var interceptDate = []; // List of intercept member
var onRequestEnd = function (e) {
setIntercept(e); // another function to fill interceptDate from schema
if (e.response.Data && e.response.Data.length) {
var rowsData = e.response.Data;
if (interceptDate.length > 0) {
if (this.group().length && e.type == "read") {
for (var i = 0; i < rowsData.length; i++) {
var gr = rowsData[i];
for (var j = 0; j < interceptDate.length; j++) {
if (gr.Member == interceptDate[j]) {
gr.Key = gr.Key.replace(/\d+/,
function (n) { return parseInt(n) + offsetMiliseconds; }
);
}
addOffset(gr.Items);
}
}
} else {
addOffset(rowsData);
}
}
}
};
in chrome devtools the e.response look like
_defaultPrevented: false
isDefaultPrevented: function (){return this._defaultPrevented===!0}
preventDefault: function (){this._defaultPrevented=!0}
response: Object
odata.count: "4"
odata.metadata: "http://localhost:7000/odata/$metadata#DateIntercept"
value: Array[4]
0: Object
1: Object
2: Object
3: Object
length: 4
__proto__: Array[0]
__proto__: Object
sender: lt.extend.init
type: "read"
__proto__: Object
If you want to modify the returned data, you should use the parse callback in the dataSource's schema. Leaving out irrelevant stuff it would look something like:
new kendo.ui.Grid({
dataSource: new kendo.data.DataSource({
schema: {
parse: function (results) {
for (var i = 0; i < results.length; i++) {
// MODIFY RESULTS HERE. FOR EXAMPLE
results[i].someField = results[i].someField + " Hello World";
}
return results;
}
}
});
});

Resources