Adobe AIR - SQL statement against DB - sqlite

This is my javascript for Adobe Air:
$(document).ready(function(e) {
setupDB();
var tasks = getTasks();
$("#tasks").empty();
var numRecords = tasks.data.length;
for(i=0; i<numRecords; i++) {
$("<li/>").append('<span>'+ tasks.data[i].id +' - '+ tasks.data[i].task +'</span>').appendTo("#tasks");
}
});
var db = new air.SQLConnection();
function setupDB() {
var dbFile = air.File.applicationStorageDirectory.resolvePath("airTasks.db");
try {
db.open(dbFile);
} catch (error) {
alert("DB Error: "+ error.message);
alert("Details: "+ error.details);
air.trace("DB Error: "+ error.message);
air.trace("Details: "+ error.details);
}
}
function getTasks() {
var query = new air.SQLStatement();
query.sqlConnection = db;
query.text = "SELECT id, task FROM tasks";
try {
query.execute();
} catch(error) {
alert("Error getting tasks from DB: "+ error.message +", DETAILS: "+ error.details);
air.trace("Error getting tasks from DB: "+ error);
air.trace(error.message);
return;
}
return query.getResults();
}
Here is a screenshot of the Database Version 3 - airTasks.db
I keep getting:
ERROR: Table "tasks" not found.

Double check that your filepath being opened actually exists. If it doesn't, SQLite creates one for you.
Try this to troubleshoot before you call db.open():
alert(dbFile);
Is this the correct path to your db?

Related

How to Update relational Table in Asp.net core Web Api

I create two table Project or Member and i create relational table of project and member table named as project member i want to Update data of that relational table i use angularjs as frontend
This is put method to update the table
[Route("api/updateProjectData")]
[HttpPut]
public IActionResult UpdateProjectData(Project project, ProjectMember projectMember)
{
// query
if (project.ProjectId != project.ProjectId)
{
return BadRequest("Id Mismatched");
}
try
{
_context.Entry(project).State = EntityState.Modified;
_context.SaveChanges();
var memberDetails = _context.ProjectMembers.FirstOrDefault(e => e.ProjectId == project.ProjectId);
_context.Entry(projectMember).State = EntityState.Modified;
_context.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectExists(project.ProjectId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
private bool ProjectExists(int id)
{
return _context.Projects.Any(e => e.ProjectId == id);
}
This is My frontend Api
$scope.UpdateProjectInfo = (ProjectID) => {
console.log($scope.ProjectID);
console.log($scope.ProjectName);
console.log($scope.ProjectStartDate);
console.log($scope.ProjectEndDate);
console.log($scope.UserStartDate);
$http({
method: 'PUT',
url: 'https://localhost:44307/api/updateProjectData?ProjectId=' + $scope.ProjectID + "&ProjectName=" + $scope.ProjectName + "&Startdate=" + $scope.ProjectStartDate + "&Enddate=" + $scope.ProjectEndDate + "&Status=&UserId=" + $scope.ddlUser + "&RoleId=" + $scope.ddlRole + "&UserStartdate=" + $scope.UserStartDate + "",
// headers: {
// 'Content-type': 'application/json;charset=utf-8'
// }
})
.then(function (response) {
console.log('ResponseUpdated', response.data);
$scope.ProjectName = response.data[0].projectName;
$scope.ddlUser = response.data[0].firstName + " " + response.data[0].lastName;
$scope.ddlRole = response.data[0].roleName;
$scope.ProjectStartDate = response.data[0].startdate;
$scope.ProjectEndDate = response.data[0].enddate;
$scope.UserStartDate = response.data[0].userStartdate;
notify('success', 'Record Updated Successfully.', '');
$scope.closeAddProjectPopup();
}, function (rejection) {
notify('error', rejection.data, '');
});
I successfully update one table But i confused how i update the second one pls tell me how i update

Can't delete SQLite database using Qt with QML transaction

Trying to use localstorage example in Qt 5.14, the database is locked and can't be deleted.
on Qt documentation it's saying:
"Database connections are automatically closed during Javascript garbage collection."
but that is not the case...
function dbInit()
{
var db = LocalStorage.openDatabaseSync("Activity_Tracker_DB", "", "Track exercise", 1000000)
try {
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS trip_log (date text,trip_desc text,distance numeric)')
})
} catch (err) {
console.log("Error creating table in database: " + err)
};
}
function dbGetHandle()
{
try {
var db = LocalStorage.openDatabaseSync("Activity_Tracker_DB", "",
"Track exercise", 1000000)
} catch (err) {
console.log("Error opening database: " + err)
}
return db
}
function dbInsert(Pdate, Pdesc, Pdistance)
{
var db = dbGetHandle()
var rowid = 0;
db.transaction(function (tx) {
tx.executeSql('INSERT INTO trip_log VALUES(?, ?, ?)',
[Pdate, Pdesc, Pdistance])
var result = tx.executeSql('SELECT last_insert_rowid()')
rowid = result.insertId
})
return rowid;
}
function dbReadAll()
{
var db = dbGetHandle()
db.transaction(function (tx) {var results = tx.executeSql(
'SELECT rowid,date,trip_desc,distance FROM trip_log order by rowid desc')
for (var i = 0; i < results.rows.length; i++) {
listModel.append({
id: results.rows.item(i).rowid,
checked: " ",
date: results.rows.item(i).date,
trip_desc: results.rows.item(i).trip_desc,
distance: results.rows.item(i).distance
})
}
})
}
How can I unlock/close the database?

How to return an Observable of type any from firebase query

I am using firebase realtime database for chat feature in my application, I just need to return an Obserable of type any or type Message from firebase query,
Here is my code:
getMessageHistory(farmerId) {
let chatMessages = [];
var chats;
firebase.database().ref('/' + this.chatUrl + '/' + farmerId + '/').once('value', function (snapshot) {
chats = snapshot.val();
if (chats != null) {
Object.keys(chats).forEach(element => {
let chat = chats[element.toString()];
var Message = {
fromId: chat.from,
toId: chat.to,
message: chat.message
}
let mockedHistory: Array<Message>;
mockedHistory.push(Message)
});
}
else {
}
});
}`
How do I return Observable from above method. I have tried angularfire2 but throwing an error while compiling (Angular Version 4)
Got the solution but I don't know is it recommended or not!
let mockedHistory: Array<Message> = [];
let totalRecords = this.db.list('/' + this.chatUrl + '/' + userId + '/');
return totalRecords.valueChanges<any>().map((chat)=>{
var newChat = chat.map((message) => {
let msg = new Message();
msg.fromId = message.from;
msg.toId= message.to,
msg.message= message.message
return msg;
});
return newChat;
}
)

Cordova Android SQLLIteplugin.open exception

I am trying to use SQLLItePlugin for Android but its not working. I will list my steps:
1. I have installed cordova pjhonegap from phonegap. I am developing my mobile app Phonegap, html5, javascript, css3 using Netbeans as IDE.
2. Downloaded plugin from https://github.com/brodysoft/Cordova-SQLitePlugin.
3. Added SQLitePlugin.js to js folder of project.
4. Added com.brodysoft.sqlitePlugin.file=https://github.com/brodysoft/Cordova-SQLitePlugin.git in plugin.properties.
5. Am opening database on deviceready as
var app = {
initialize: function () {
this.bindEvents();
},
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function () {
app.receivedEvent('deviceready');
var db = window.sqlitePlugin.openDatabase('gdata.db');
console.log('ready');
db.transaction(function (tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
// demonstrate PRAGMA:
db.executeSql("pragma table_info (test_table);", [], function (res) {
console.log("PRAGMA res: " + JSON.stringify(res));
});
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function (tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
db.transaction(function (tx) {
tx.executeSql("select count(id) as cnt from test_table;", [], function (tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
});
}, function (e) {
console.log("ERROR: " + e.message);
});
});
},
// Update DOM on a Received Event
receivedEvent: function (id) {
var parentElement = document.getElementById(id);
console.log('Received Event: ' + id);
}
};
app.initialize();
Running the build on android devvice directly.
It keeps on throwing the error
Uncaught TypeError: Object # has no method 'exec'
(13:52:13:450 | error, javascript)
at SQLitePlugin.open (www/js/libs/SQLitePlugin.js:112:15)
at SQLitePlugin (www/js/libs/SQLitePlugin.js:54:10)
at (anonymous function) (www/js/libs/SQLitePlugin.js:425:14)
at (anonymous function) (www/js/libs/SQLitePlugin.js:30:20)
at createandpopulatedb (www/js/dborarray.js:30:30)
at onDeviceReady3 (www/dborarray.html:96:33)
at onload (www/dborarray.html:16:155) SQLitePlugin openargs: {"name":"gdataenter code here.db"} (13:52:19:609) at
www/js/libs/SQLitePlugin.js:39
Can somebody help.
try thhis
window.sqlitePlugin.openDatabase({name: "gdata.db"});
instead of this
window.sqlitePlugin.openDatabase('gdata.db');

Dealing with EventEmitter events in Meteor?

I am trying to use an Asterisk Manager NPM module in Meteor, but am having difficulties with processing emitted events.
This NPM module establishes a permanent connection to Asterisk Manager and emits whatever Events it receives from Asterisk. I've managed to patch the code so that it runs in Meteor. It connects to Asterisk, emits events and I can log them to console, but once I try to do something with the data, like insert it into a collection, I receive the following error:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
How do I overcome that? Thank you.
server side code:
var ami = new AsteriskManager( { username: 'meteor', password: '123456' } );
ami.on('ami_data', function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
});
ami.connect(function(){});//creates a socket connection and sends the login action
the patched npm module code:
var util = Npm.require('util');
var events = Npm.require('events').EventEmitter;
var net = Npm.require('net');
var AsteriskConstructor = function AsteriskManager(params){
params = params || {};
this.net = net;
this.CRLF = "\r\n";
this.END = "\r\n\r\n";
this.buffer = "";
this.port = params.port || 5038;
this.host = params.host || 'localhost';
this.username = params.username || 'username';
this.password = params.password || 'password';
this.enable_debug = params.debug || false;
this.reconnect = params.reconnect || false;
this.reconnect_after = params.reconnect_after || 3000;
this.events = (params.events != undefined ? params.events : true);
this.identifier = params.identifier || false;
this.ami_encoding = params.ami_encoding || 'ascii';
};
AsteriskManager = AsteriskConstructor;
util.inherits(AsteriskManager, events);
AsteriskManager.prototype.connect = function(connect_cb, data_cb){
var self = this;
self.debug('running ami connect');
self.socket = null;
self.socket = this.net.createConnection(this.port, this.host);//reopen it
self.socket.setEncoding(this.ami_encoding);
self.socket.setKeepAlive(true, 500);
self.socket.on('connect', function(){
self.debug('connected to Asterisk AMI');
//login to the manager interface
self.send({Action: 'login', Username : self.username, Secret : self.password, Events: (self.events ? 'on' : 'off')});
if(connect_cb && typeof connect_cb == 'function'){
connect_cb();
}
}).on('data', function(data){
if(data_cb && typeof data_cb == 'function'){
data_cb(data);
}
var all_events = self.processData(data);
for(var i in all_events){
var result = all_events[i];
if(result.response && result.message && /Authentication/gi.exec(result.message) == 'Authentication'){
self.emit('ami_login', ((result.response == 'Success') ? true : false) ,result);
}
self.emit('ami_data', result);
}
}).on('drain', function(){
self.debug('Asterisk Socket connection drained');
self.emit('ami_socket_drain');
}).on('error', function(error){
if(error){
self.debug('Asterisk Socket connection error, error was: ' + error);//prob lost connection to ami due to asterisk restarting so restart the connection
}
self.emit('ami_socket_error', error);
}).on('timeout',function(){
self.debug('Asterisk Socket connection has timed out');
self.emit('ami_socket_timeout');
}).on('end', function() {
self.debug('Asterisk Socket connection ran end event');
self.emit('ami_socket_end');
}).on('close', function(had_error){
self.debug('Asterisk Socket connection closed, error status - ' + had_error);
self.emit('ami_socket_close', had_error);
if(self.reconnect){
self.debug('Reconnecting to AMI in ' + self.reconnect_after);
setTimeout(function() {
self.connect(connect_cb, data_cb);
}, self.reconnect_after);
}
});
}
AsteriskManager.prototype.disconnect = function(){
this.reconnect = false;//just in case we wanted it to reconnect before, we've asked for it to be closed this time so make sure it doesnt reconnect
this.socket.end(this.generateSocketData({Action: 'Logoff'}));
}
AsteriskManager.prototype.destroy = function(){
this.socket.destroy();
}
AsteriskManager.prototype.processData = function(data, cb){
/*
Thanks to mscdex for this bit of code that takes many lots of data and sorts them out into one if needed!
https://github.com/mscdex/node-asterisk/blob/master/asterisk.js
*/
data = data.toString();
if (data.substr(0, 21) == "Asterisk Call Manager"){
data = data.substr(data.indexOf(this.CRLF)+2); // skip the server greeting when first connecting
}
this.buffer += data;
var iDelim, info, headers, kv, type, all_events = [];
while ((iDelim = this.buffer.indexOf(this.END)) > -1) {
info = this.buffer.substring(0, iDelim+2).split(this.CRLF);
this.buffer = this.buffer.substr(iDelim + 4);
result = {}; type = ""; kv = [];
for (var i=0,len=info.length; i<len; i++) {
if (info[i].indexOf(": ") == -1){
continue;
}
kv = info[i].split(": ", 2);
kv[0] = kv[0].toLowerCase().replace("-", "");
if (i==0){
type = kv[0];
}
result[kv[0]] = kv[1];
}
if(this.identifier){
result.identifier = this.identifier;
}
all_events.push(result);
}
return all_events;
}
AsteriskManager.prototype.debug = function(data){
if(this.enable_debug){
console.log(data);
}
}
AsteriskManager.prototype.generateRandom = function(){
return Math.floor(Math.random()*100000000000000000);
}
AsteriskManager.prototype.generateSocketData = function(obj){
var str = '';
for(var i in obj){
str += (i + ': ' + obj[i] + this.CRLF);
}
return str + this.CRLF;
}
AsteriskManager.prototype.send = function(obj, cb) {
//check state of connection here, if not up then bail out
if(!obj.ActionID){
obj.ActionID = this.generateRandom();
}
//maybe i should be checking if this socket is writeable
if(this.socket != null && this.socket.writable){
this.debug(obj);
this.socket.write(this.generateSocketData(obj), this.ami_encoding, cb);
}else{
this.debug('cannot write to Asterisk Socket');
this.emit('ami_socket_unwritable');
}
}
As the error message says "Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment"
ami.on('ami_data', Meteor.bindEnvironment( function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
}, function( error) { console.log( error);})
);
There are a lot of other examples around.
If the server code above is not in a Fiber you might get "Meteor code must always run within a Fiber" error.

Resources