i need check if exists an database creating in my application with phonegap.
Searching lot but i dont nothing found.
I found content just talking about tables that already exist but nothing talking about how to verify that the database created exists.
Thanks!
I followed a path as follows.
var db;
function createDataBase(fn){
try{
db = window.openDatabase('example.db','1','Example Database',-1, function(){
/**
* database first created ...
*
* */
createTables(fn);
});
}catch(e){
/**
* database already created!!
* */
db = window.openDatabase('readyVehicle.db','','',-1);
if(typeof(fn) == 'function'){
fn.call(null, db);
}
}
}
function createTables(fn){
....
....
if(typeof(fn)=='function'){
fn.call(null, db);
}
}
createDataBase(function(db){
// dosomething();
})
Related
This same method has worked before to validate line level memo on an Inventory Adjustment, but for some reason this is not working. I do not believe it is initializing at all.
My goal is to validate the quantity on the line of a Transfer Order to check if the quantity is 1. If the quantity is 1, show the message (and do not let the user proceed).
Maybe it has something to do with Line Type on Transfer Orders?
/**
#NApiVersion 2.0
#NScriptType ClientScript
#NModuleScope Public
*/
define([], function () {
function showMessage(context){
var message = "ERROR: Do not order single units"
var quant = context.currentRecord.getCurrentSublistValue({
sublistId:'item',
fieldId:'quantity',
});
if (quant == 1) {
alert(message);
}
else {
return true;
}
}
return {
validateLine: showMessage
};
});
It's perfectly fine. Try checking your deployment record to see whether its been deployed properly (like checking role etc.)
Also, try returning false after the alert.
if (quant == 1) {
alert(message);
return false;
}
I have multiple files that start with comments like:
/*
* #title Force email verification
* #overview Only allow access to users with verified emails.
* #gallery true
* #category access control
*
* This rule will only allow access users that have verified their emails.
*
* > Note: It might be a better UX to make this verification from your application.
*
* If you are using [Lock](https://auth0.com/docs/lock), the default behavior is to log in a user immediately after they have signed up.
* To prevent this from immediately displaying an error to the user, you can pass the following option to `lock.show()` or similar: `loginAfterSignup: false`.
*
* If you are using [auth0.js](https://auth0.com/docs/libraries/auth0js), the equivalent option is `auto_login: false`.
*
*/
//jshint -W025
function (user, context, callback) {
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}
All files contains two types of comments i.e /**/ and // Now I am reading this file in my javascript code and want to remove comments and get the actual code in the variable e.g
function (user, context, callback) {
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}
I have tried using strip-comments and parse-comments npm but none of these work. Here is the code:
const fs = require('fs');
const path = require('path');
const strip = require('strip-comments');
module.exports = function (ruleFileName, globals, stubs) {
globals = globals || {};
stubs = stubs || {};
const fileName = path.join(__dirname, '../src/rules', ruleFileName + '.js');
const data = fs.readFileSync(fileName, 'utf8');
const code = strip(data);
console.log(code);
return compile(code, globals, stubs);
}
and with parse-comments I tried like:
const parsed = parseComments(data)[0];
const code = data.split('\n').slice(parsed.comment.end).join('\n').trim();
I think strip comment is not working because it takes string as an argument but fs.readFileSync doesn't return string. I have also tried data.toString()but that also didn't work. So how can I strip comments from the content? Is there any other solution?
try use regx to replace /\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm
var Text = `/*
* #title Force email verification
* #overview Only allow access to users with verified emails.
* #gallery true
* #category access control
*
* This rule will only allow access users that have verified their emails.
*
* > Note: It might be a better UX to make this verification from your application.
*
* If you are using [Lock](https://auth0.com/docs/lock), the default behavior is to log in a user immediately after they have signed up.
* To prevent this from immediately displaying an error to the user, you can pass the following option to "lock.show()" or similar: "loginAfterSignup: false".
*
* If you are using [auth0.js](https://auth0.com/docs/libraries/auth0js), the equivalent option is "auto_login: false".
*
*/
//jshint -W025
function (user, context, callback) {
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}`
console.log(Text.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm,''))
like this
https://codepen.io/anon/pen/eQKrWP
So I'm trying to use nodejs mysql to access my locally running database that I am using for development. Everything is running correctly and I am able to make successful queries to the server and get the data back.
I have the function I created below which I am module.exports so that it is accessible from within my server where it is invoked and the loadExp() method is called.
var dataStore = function (connection) {
this.con = connection;
this.clientArr = new Map();
/**
* Loads all of the user experiences into the array.
*/
this.loadExp = function () {
var output = 'err';
loadData(this.con, function (err, result) {
console.log(err || result);
output = result.uuid;
});
console.log(output);
};
function loadData(con, callback) {
con.query('SELECT * FROM exp', function (err, rows, fields) {
if (err) throw err;
callback(null, rows);
});
}
/**
* Returns the value of a client from within the hash map.
* #param id
* #returns {*|String}
*/
this.getClient = function (id) {
var value = this.clients.get(id);
if (value != null) {
return value;
} else {
return 'err';
}
};
/**
* Returns a full list of clients.
* #returns {Map}
*/
this.getClientList = function () {
return this.clientArr;
};
/**
* Creates a new instance of a client within the database and also within our datastore.
* #param id
* #param client
*/
this.addClient = function (id, client) {
this.clientArr.set(id, client);
};
};
module.exports = dataStore;
Now I would like to make use of my this.addClient function outlined at the bottom of this function but I can never get my data in scope to make this possible and I'm stuck for how I would get this data in scope so that it is usable.
This is a problem with lexical scoping in JavaScript (ES5). You need to make sure the this is what you think it is when called. this is bound to the object the function was called within.
Look into setting var self = this at the top of your parent function and using that as a reference. Or, even better, using .bind(this).
I have an array of clients with their _id's from mongo, I wanted to know how can I route all of them (at once) to a page using router?
example: 3 users are landing on a page named "game", when there are 3 people I have an array which saves their userID, all the users with their ID's saved in the array should be routed to another page (for examle: "page2"). I understand that this should be done from server side perspective but im having a hard time to figure this one out.
//client
Template.GameLayout.onRendered(function () {
var ses = Session.get("loggedIn");
Meteor.call('userCounter', ses, function(error, fullArray){
if(error && error.error === "noArray"){
console.log(error);
console.log("I have error");
} else {
if(fullArray){
var usersArray = fullArray[1];
var randomGen = fullArray[0];
console.log(randomGen);
}
}
})
//server
userCounter: function(sessions){
usersArray.push(sessions);
var usersConnected = usersArray.length;
if(!usersConnected){
throw new Meteor.Error("noArray");
console.log("oops heres the problem");
} else {
if(usersConnected > 2){
var randomGen = Math.floor(Math.random() * 9999999) + 1;
var fullArray = [randomGen, usersArray];
console.log(fullArray);
return fullArray;
usersArray =[];
}
}
}
Personally I would just do this in a Tracker.autorun() on the client-side, ex:
Tracker.autorun(function(){
if ( ... condition that you want to re-route on ... ){
Router.go('page2');
}
});
Your array would have to be published in a collection of some kind, say active games so that the client could do its logic and route accordingly.
I am developing a mobile application using phonegap that store some data into the local database (sqlite DB).
I need to know if the database exist or not, and that to determine which process need to execute.
var database = window.openDatabase("my_db", "1.0", "sample DB", 30000);
if (check_db_exist()) {
process_1();
}
else
{
process_2();
}
I needed to do something similar, I needed to check if the application had a db already created (legacy DB) and if so export all the data to the new db (new and improved DB) and then delete this DB.
Background Info: I was moving from simple keyvalue tables to complex relational DB with cascades etc.
function onDeviceReady() {
// CHECK IF LEGACY DATABASE EXISTS. IF DOES EXPORT EXISTING DATA TO NEW DB THEN DELETE LEGACY
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "/databases/<DatabaseName>.db", exportToNewDB, setupDB);
}
Note: If file exists (success), then we need to do our export code in here, then delete file so this method will always fail. If file doesn't exist - user has already exported to new DB or they our new user and never had legacy DB.
// Fail Method
function setupDB() {
newDB = window.sqlitePlugin.openDatabase({ name: "<NewImprovedDBName>.db" });
newDB.transaction(sql.initDB, sql.errorCallback, sql.successCallBack);
}
// Success Method
function exportToNewDB() {
db = window.sqlitePlugin.openDatabase({ name: "<LegacyDBName>.db" });
db.transaction(function (tx) {
setupDB();
// Insert Export code Here
// Delete DB
window.sqlitePlugin.deleteDatabase("<LegacyDBName>.db", sqlSuccess, sqlFail);
}, sqlFail);
}
Answer to your Question:
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "/databases/my_db.db", process_1, process_2);
The best way for determining if the DB exists or not is to check if the file that represents it exists. This is a simple IO operation, like the following example:
string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, databaseName);
if (File.Exists(path))
{
//your code here
}
I don't think that you can check for the existence of the DB directly. I've researched and haven't found a way to do it using a simple function call. However, this seems to be a popular request, and here's a workaround:
var db = window.openDatabase("my.db", "1", "Demo", -1);
db.transaction(function (tx) {
/*I don't think that there is a way to check if a database exists.
As I think that the openDatabase call above will just create
a missing DB. Here is a second-best way to do it - there
is a way to check to see if a table exists. Just pick a table that
your DB should have and query it. If you get an ERROR, then you
can assume your DB is missing and you will need to create it. */
console.log("Trying to get the test data");
tx.executeSql("select * from test_table", [], function (tx, res) {
var len = res.rows.length, i;
for (i = 0; i < len; i++) {
console.log(res.rows.item(i).data);
}
}, function (err) {
console.log("Error selecting: " + err);
//NOW we need to create the DB and populate it
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text)');
tx.executeSql('INSERT INTO test_table (data) VALUES("test data one")');
tx.executeSql('INSERT INTO test_table (data) VALUES("test data two")');
//now test select
tx.executeSql("select * from test_table", [], function (tx, res) {
var len = res.rows.length, i;
for (i = 0; i < len; i++) {
console.log(res.rows.item(i).data);
}
});
//now clean up so we can test this again
tx.executeSql('DROP TABLE IF EXISTS test_table', [], function (tx, res) {
console.log("dropped table");
}, function (err) {
console.log("Error dropping table: " + err);
});
});
});
As you can see, the error function during the first query will create and populate the DB. It's using exception handling for program logic flow, but it works!