Return created item key - google-app-maker

My app creates a new item, and I want to retrieve the key to use in a server script. The data variable returns null though. This is what I have:
function addItem(addButton) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function(key) {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
return newProjectItem;
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
var data = app.datasources.ProjectItems.item._key;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}

This is not neat by any means, but I fixed it by creating a new function:
function addItem(addButton, key) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function() {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
var key = newProjectItem._key;
value(key);
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
function value(record){
var data = record;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
}

Related

asp.net "put" method with angular js

im workin with my website and actually workin with 3 methods-put,post,delete. In my code i did two of them:delete and post and they are correct, but i have no idea how i can do put do edit my TODO list.
That's my code, if you can help me i'll be glad.
Have a nice day.
This is a service .js file
app.factory('reservationService', ReservationService);
function ReservationService($http) {
var CreateReservation = function (reservation) {
return $http.post("api/todo", reservation);
}
var EditReservation = function (id) {
return $http.put("api/todo/", + id);
}
var DeleteReservation = function (id) {
return $http.delete("api/todo/" + id);
}
var GetAll = function () {
return $http.get("api/todo");
}
return {
CreateReservation: CreateReservation,
EditReservation: EditReservation,
DeleteReservation: DeleteReservation,
GetAll: GetAll
}
}
this is a angular maincontroller code
app.controller('mainCtrl', mainCtrl);
function mainCtrl($scope, reservationService) {
$scope.list = [];
$scope.reservation = {};
getReservations();
InitDateTimePickers();
$scope.isSelected = function () {
return getSelectedItems().length > 0;
};
$scope.append = function (id) {
var editedItem = _.first(getSelectedItems());
$scope.reservation = editedItem;
reservationService.EditReservation(id).then(function (result) {
getReservations();
});
};
function getReservations() {
reservationService.GetAll().then(function (result) {
for (var i = 0; i < result.data.length; i++) {
result.data[i].timeFormatted = moment(result.data[i].Time, "HH:mm").format("hh:mm");
}
$scope.list = result.data;
});
}
function removeReservation(id) {
reservationService.DeleteReservation(id).then(function (result) {
getReservations();
});
}
$scope.add = function () {
reservationService.CreateReservation($scope.reservation).then(function (result) {
getReservations();
});
};
function InitDateTimePickers() {
$('#timepickerFrom').bootstrapMaterialDatePicker({ date: false, format: 'HH:mm' }).on('change', function (e, date) {
}); }
$scope.remain = function () {
var count = 0;
angular.forEach($scope.list, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
var getSelectedItems = function () {
return _.filter($scope.list, function (n) {
return n.done;
});
}
$scope.archive = function () {
var itemsToRemove = getSelectedItems();
_.each(itemsToRemove, function (item) {
removeReservation(item.id)
});
};
$scope.edit = function () {
var editedItem = _.first(getSelectedItems());
$scope.reservation = editedItem;
}
};
You can pass entire entity to the server to update it:
var EditReservation = function (reservation) {
return $http.put("api/todo/" + reservation.id, reservation);
}
Also it seems that this string contains typo: return $http.put("api/todo/", + id);

NIghtmare error in web scraping course details

Hi i am using nightmare for scrape data from website and also course details. I occur a issue :-
err: { message: 'navigation error',
code: 0,
details: 'OK',
url: 'https://www.myskills.gov.au/courses/details?Code=CHC14015' }
on each url traversal. Please suggest me to resolve this:
var Nightmare = require('nightmare')
var vo = require('vo')
var fs = require('fs')
var filesystem = require('file-system')
// var nightmare = Nightmare({show:true});
var sleep = require('sleep');
vo(run)(function(err, result) {
if (err) throw err
console.log("Hi");
})
function *run() {
var nightmare = Nightmare({show:true});
console.log("1st step *run");
yield nightmare
.goto('https://www.myskills.gov.au/courses/search/')
.wait(12000)
//.click('#select3 value="100")
.evaluate(function () {
var hrefs = [];
$('.search-result h4 a').each(function()
{
var course = new Object();
course.title = $(this).html();
course.link = $(this).attr('href');
course.code = $('.search-result .col-md-2.text-small
span').html();
hrefs.push(course);
});
return hrefs;
})
.then(function(str){
console.log("2nd step evaluate then on page load");
console.log(str);
for(var i=0; i< 8; i++)
{
console.log(i);
sleep.sleep(1);
var link = "https://www.myskills.gov.au";
var coursetitle = str[i].title
var courselink = link +str[i].link+"\n";
var coursesinglelink = link +str[i].link;
var courseData = coursetitle+"\n"+str[i].code+"\n"+courselink;
fs.appendFile('getcourselink.txt', courseData, function (err) {
if(err) console.log(err);
});
vo(run1)(function(err, result) {
if (err) console.log ("err: ",err);
console.log("Hi in run1");
//console.log(result);
});
function *run1() {
console.log("I 2nd time:-"+i);
console.log(coursesinglelink);
sleep.sleep(2);
var nightmare1 = Nightmare({show:true});
yield nightmare1
.goto(coursesinglelink)
.wait(9000)
.evaluate(function () {
var str="Hi";
var CourseDetails = $('#details #courseStructureDiv
#packagingrules').text();
str = str+"\n"+CourseDetails;
return str;
})
.then(function(str){
console.log("Run inner then",str);
fs.appendFile('getcourselink.txt', str, function (err) {
if(err) console.log(err);
});
// nightmare1.end();
});
}
//nightmare.end();
// nightmare.proc.disconnect();
// nightmare.proc.kill();
// nightmare.ended = true;
// nightmare = null;
}
});
}

How to return "then()" method in angularjs?

My case:
app.js:
let app = angular.module('myApp', []);
app.controller('login', function ($scope, $login) {
$scope.account = {};
$scope.loginForm_submit = function ($event, account) {
$event.preventDefault();
if ($login.isValid(account)) {
$login.submit(account);
// goal:
$login.submit(account).then(function () {
window.location = '/'
}, function (msg) {
console.log(msg)
});
}
};
});
login.js:
app.factory('$login', function () {
let o = {
isValid: function (x) {
let success = false;
// validating...
return success
},
submit: function (x) {
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();
// appending data to 'formData' via 'x'...
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);
if (data['Success']) {
// return then() with successCallback() function
} else {
let msg = data['ErrorMessage'];
// return then() with errorCallback() function
}
}
}
xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
}
}
return o
});
data is an object like:
let data = {
'Success': false,
'ErrorMessage': 'Invalid login attempt.'
};
I want to return then() method after submitting to access result. How can I do that?
UPDATE:
In controller:
[HttpPost]
public async Task<ObjectResult> Login(LoginViewModel model)
{
IDictionary<string, object> value = new Dictionary<string, object>();
value["Success"] = false;
if (ModelState.IsValid)
{
// login
value["Success"] = true;
}
return new ObjectResult(value);
}
First of all, you should avoid using $ for your own functions.
About your problem, you need to use $q. And you should use what angular offers to you.
Let me give you this :
app.factory('loginFactory', function($q, $http) {
var ret = {
isValid: isValid,
submit: submit
}
return ret;
function isValid(x) {
// Your code ...
return false;
}
function submit(x) {
// x is your form data, assuming it's a JSON object
var deferred = $q.defer();
// Assuming you're posting something
$http.post('yoururl', x,{yourConfigAsAnObject: ''})
.then(function(success){
console.log(success.data);
deferred.resolve(success.data);
}, function(error) {
console.log(error);
deferred.reject(error);
});
return deferred.promise;
}
});
Now, in your controller, you can use
loginFactory.submit(yourParam).then(function(success){
// Your code
}, function(error) {
// Your code
});
app.factory('$login', function ($q) {
let o = {
isValid: function (x) {
let success = false;
// validating...
return success
},
submit: function (x) {
var d = $q.defer();
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();
// appending data to 'formData' via 'x'...
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);
if (data['Success']) {
// return then() with successCallback() function
d.resolve('success');
} else {
let msg = data['ErrorMessage'];
d.reject(msg);
// return then() with errorCallback() function
}
}
}
xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
else {
d.reject('error');
}
return d.promise;
}
}
return o
});
dude,I made a sample function with promise
$q should be injected as dependency
class AppUserService {
constructor($http,CONFIG_CONSTANTS,$q, AuthService) {
this.API_URL = CONFIG_CONSTANTS.API_URL;
this.$http = $http;
this.$q = $q;
this.api_token = AuthService.api_token;
}
getAppUserList() {
const deferred = this.$q.defer();
this.$http.get(`${this.API_URL}/customer?api_token=${this.api_token}`)
.success(response => deferred.resolve(response))
.error(error => deferred.reject(error));
return deferred.promise;
}
}
its in ES6 form.
How to use:
AppUserService.getAppuserList().then(success => {
// code for success
},error => {
// code for error
})
submit: function (x) {
return $q(function (resolve, reject) {
// prevent to force submitting
if (this.isValid(x)) {
let formData = new FormData(), xhttp = new XMLHttpRequest();
// appending data to 'formData' via 'x'...
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
let data = JSON.parse(xhttp.responseText);
if (data['Success']) {
resolve(data);
// return then() with successCallback() function
} else {
let msg = data['ErrorMessage'];
reject(msg);
}
}
}
xhttp.open('POST', '/account/register');
xhttp.send(formData);
}
else
reject('x not valid');
}
}
}
But I recommended to use angular $http service.

YDN-DB - Delete DB then recreate and load when page is loaded/reloaded but not when refreshed

I'm converting some IndexedDB code to use YDN-DB and need some help in converting this. This code essentially deletes the DB if the page is loaded or reloaded but not when it is refreshed.
How would I accomplish that using YDN-DB?
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var db;
window.refreshing = false;
$(document).ready(function(){
if(window.performance) {
if(performance.navigation.type == 0 ) {
// The db already exists so delete it and re-create it so we don't have stale records.
deleteDB();
} else {
window.refreshing = true;
open();
}
}
});
function deleteDB() {
var request = indexedDB.deleteDatabase("DocsDB");
request.onsuccess = function() {
open();
}
request.onerror = function(event) {
throw "Error in deleteDB.";
}
}
function open() {
var request = indexedDB.open("DocsDB");
var upgraded = false;
request.onupgradeneeded = function(evt) {
upgraded = true;
var dbnew = evt.target.result;
dbnew.onerror = function(event) {
console.log("IndexedDB error: " + evt.target.error.code);
};
var objectStore = dbnew.createObjectStore(
"docs", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("docname", "DOC_NAME", { unique: false });
objectStore.createIndex("printdate", "PRINT_DATE", { unique: false });
}
request.onsuccess = function(evt) {
db = request.result;
if (!upgraded && !window.refreshing) {
throw "Not upgraded";
}
request.result.onversionchange = function(e) {
if (e.newVersion === null) { // An attempt is made to delete the db
e.target.close(); // Manually close our connection to the db
}
};
if(typeof db != 'undefined' && !window.refreshing) {
// We load the store with the records here, attempting to add records via ajax doesn't work
// looks like we'll ahve to load them via ajax before initialization?
var store = getObjectStore(db);
for (i=0; i<documents["Rows"].length-1;i++) {
store.add(documents["Rows"][i]);
}
}
}
request.onerror = function() {
throw "Error in open";
}
}
function getObjectStore(db, mode = 'readwrite') {
if(typeof db != 'undefined') {
var tx = db.transaction('docs', mode);
return tx.objectStore('docs');
} else {
return null;
}
}
To delete a database use, ydn.db.deleteDatabase("DocsDB").

Meteor data not inserting or displaying after removing insecure package

Data is not getting inserted into the database after i removed autopublish and insecure packages. Please let me know what i am missing.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (){
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name}
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
You don't have an insert statement.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (e){
e.preventDefault(); // to prevent default action of the button
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name};
Userdata.insert(doc); // actually inserting the document
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}

Resources