I'm developing a game for web(html5) which connects to a SQLite database to access the game's questions (which I learned in here: http://answers.unity3d.com/questions/743400/database-sqlite-setup-for-unity.html). the database in question is located in a .db file located inside the Assets folder of my project.
When I run it in unity, it connects to the database just right and exctracts the questions. When I build the game, it doesn't. Can anyone help me with this problem? Where should I put my .db file?
because You database file is not True Location
Db file would on data folder After The Make Build
Here is an answer on Reddit:
"Other options you might want to consider are to build a JavaScript
bridge to something like the browser IndexedDB or WebSQL APIs."
Personally, how I would approach this is with my WebGL build communicating to a React App it is embedded in. You can use npm package "React Unity WebGL" then have functions that access WebSQL database.
const db = openDatabase("my.db", '1.0', "My WebSQL Database", 2 * 1024 * 1024);
useEffect(function () {
unityContext.on("Create", function (sqlcommand) {
db.transaction(function (tx) {
tx.executeSql("data");
});
});
unityContext.on("InsertData", function (sqlcommand, data) {
db.transaction(function (tx) {
tx.executeSql(sqlcommand, data);
});
});
unityContext.on("SelectData", function (sqlcommand, callback) {
db.transaction(function (tx) {
tx.executeSql(sqlcommand, [], function(tx, results) {
if(results.rows.length > 0) {
for(var i = 0; i < results.rows.length; i++) {
console.log("Result -> " + results.rows.item(i).firstname + " " + results.rows.item(i).lastname);
}
unityContext.send("GameController", callback, results);
}
});
});
});
}, []);
Now you can start using SQL in your WebGL applications.
Related
I have a react app, which must perform a weekly task every Monday #7:58 am. The task is setup as a separate function "notification()". And I want to use the 'CRON' package from NPM to call notification() at the appropriate time.
I have CRON wrapped inside of a function like this:
let mondayNotif = () => {
new CronJob('* 58 7 * * 2', function() {
notification()
}, null, true, 'America/Los_Angeles');
};
My question: where should I call the function mondayNotif(), to make sure that the CronJob is initiated correctly? I thought at first it must be on the backend, but the NPM package doesn't seem to support server-side. But if I call mondayNotif() on the client side, will the CronJob still happen if the site is inactive?
From what I know React JS is front end - it runs on client side. You need a server. In this case a node.js based server. Theroetically if nobody opens the website nothing will be fired up in react js. Look up how to schedule cron jobs on node.js
enter link description here
I found my own answer. But first, a few insights on CronJobs that would have helped me:
CronJobs are essentially a third-party function with an embedded clock. Once they are "initiated", you don't have to call them. The third-party calls them remotely, based on the time that you scheduled in the parameters (ie: "30 6 * * 5").
There is some discrepancy in different blogs about the CRON time. For instance some blogs insisted there are 6 time variables, but I found it worked with 5.
CronJobs should be in a separate file from the body of your main code, typically at the top of your folder structure near your "package.json" & "server.js" files.
It seems to be cleanest to setup all of your CronJob utilities directly inside the cronjob.js file. For instance: I used a separate database connection directly in cronjob.js and by-passed the api routes completely.
CronJobs should be initiated exactly once, at the beginning of the app launch. There are a few ways to do this: package.json or server.js are the most obvious choices.
Here is the file structure I ended up using:
-App
--package.json
--server.js
--cronjob.js
--/routes
--/src
--/models
--/public
...And then I imported the cronjob.js into "server.js". This way the cronjob function is initiated one time, when the server.js file is loaded during "dev" or "build".
For reference, here's the raw cronjob.js file (this is for an email notification):
const CronJob = require('cron').CronJob;
const Department = require('./models/department.js');
const template_remind = require('./config/remindEmailTemplate.js');
const SparkPost = require('sparkpost');
const client = new SparkPost('#############################');
const mongoose = require("mongoose");
const MONGODB_URI =
process.env.MONGODB_URI || "mongodb://localhost:27017/app";
mongoose.Promise = Promise;
// -------------------------- MongoDB -----------------------------
// Connect to the Mongo DB
mongoose.connect(MONGODB_URI, { useNewUrlParser: true }, (err, db) => {
if (err) {
console.log("Unable to connect to the mongoDB server. Error:", err);
} else {
console.log("Connection established to", MONGODB_URI);
}
});
const db = mongoose.connection;
// Show any mongoose errors
db.on("error", error => {
console.log("Mongoose Error: ", error);
});
// Once logged in to the db through mongoose, log a success message
db.once("open", () => {
console.log("Mongoose CRON connection successful.");
});
// ------------------------ Business Logic --------------------------
function weekday(notifications) {
Department.find({"active": true, "reminders": notifications, "week": {$lt: 13}}).distinct('participants', function(err, doc) {
if(err){
// console.log("The error: "+err)
} else {
console.log("received from database... "+JSON.stringify(doc))
for(let i=0; i<doc.length; i++){
client.transmissions.send({
recipients: [{address: doc[i]}],
content: {
from: 'name#sparkmail.email.com',
subject: 'Your email notification',
html: template_remind()
},
options: {sandbox: false}
}).then(data => {})
}
}
})
}
function weeklyNotif() {
new CronJob('45 7 * * 1', function() {weekday(1)}, null, true, 'America/New_York');
new CronJob('25 15 * * 3', function() {weekday(2)}, null, true, 'America/New_York');
new CronJob('15 11 * * 5', function() {weekday(3)}, null, true, 'America/New_York');
}
module.exports = weeklyNotif()
As you can see, I setup a unique DB connection and email server connection (separate from my API file), and ran all of the logic inside this one file, and then exported the initiation function.
Here's what appears in server.js:
const cronjob = require("./cronjob.js");
All you have to do here is require the file, and because it is exported as a function, this automatically initiates the cronjob.
Thanks for reading. If you have feedback, please share.
Noway, do call CronJob from client-side, because if there are 100 users, CronJob will be triggered 100 times. You need to have it on Server-Side for sure
I need to download the pdf/word/excel file from external server in to my ionic application. Sample code below
const fileTransfer: FileTransferObject = this.transfer.create();
const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
console.log("error : " +error);
});
I need to store all the files in my application itself not an external storage or an internal storage. Would this be possible?
By the way if we keep on store the files in the application itself then there is any application performance issue came?
Thanks
AK
I am working on ionic project which needs to work offline. My issue is, how to save uploaded image offline in sqlite database, and when track any wifi connection, synch to online.
Image uploading online is working fine, using cordova camera plugin and filetransfer plugin.
You can use cordova file plugin's copyfile method to store the image locally, and then save its link in the database for further use. When the wifi is detected, just use that link to upload file to server with same cordovafile plugin.
$cordovaCamera.getPicture(options).then(function(sourcePath) { //for capturing image
console.log(sourcePath);
var sourceDirectory = sourcePath.substring(0, sourcePath.lastIndexOf('/') + 1); //image file with path url
var sourceFileName = sourcePath.substring(sourcePath.lastIndexOf('/') + 1, sourcePath.length); //image name
console.log("Copying from : " + sourceDirectory + sourceFileName);
console.log("Copying to : " + cordova.file.dataDirectory + sourceFileName);
//used to store file locally
$cordovaFile.copyFile(sourceDirectory, sourceFileName,
cordova.file.dataDirectory, sourceFileName).then(function(success) {
$scope.fileName = cordova.file.dataDirectory + sourceFileName;
console.log($scope.fileName, success);
$scope.propic = $scope.fileName;
}, function(error) {
console.log(error);
});
}, function(err) {
console.log(err);
});
i am very new to pouchdb, meaning i have not yet been successfully able to implement an app that uses it.
This is my issue now, in my controller i have two functions:
var init = function() {
vm.getInvoicesRemote(); // Get Data from server and update pouchDB
vm.getInvoicesLocal(); // Get Data from pouchDB and load in view
}
init();
Basically in my app i have a view that shows customer invoices, now i want customers to be able to still see those invoices when they're offline. I have seen several examples of pouchdb and couchdb but all use the "todo" example which does not really give much information.
Now i'm just confused about what the point was in me spending hours understanding couchdb and installing it if in the end i'm just going to be retrieving the data from my server using my API.
Also when the data is returned how does pouchdb identify which records are new and which records are old when appending.
well, i m working on same kind..!this is how i m making it work..!
$scope.Lists = function () {
if(!$rootScope.connectionFlag){
OfflineService.getLocalOrdersList(function (localList) {
if(localList.length > 0) {
$scope.List = localList;
}
});
}else{
if(!$scope.user){
}else {
Common.callAPI("post", '***/*************', $scope.listParams, function (data) {
if (data !== null) {
$scope.List = data.result;
OfflineService.bulkOrdersAdd_updateLocalDB($scope.List);
}
});
}
}
};
so,$scope.List will be filled if online as well as offline based on connectionFlag
note : OfflineService and Common are services.
call method:
$ionicPlatform.ready(function () {
OfflineService.configDbsCallback(function(res) {
if(res) {
$scope.Lists();
}
});
});
u can try calling $scope.Lists(); directly..!
hope this helps u..!
The question duplicates some older questions, but the things may have changed since then.
Is there some official support for connecting to SQL Server from Node.js (e.g. official library from MS)? Or at least some well-maintained third-party library appropriate for a production-grade application?
We usually use ASP.NET MVC/SQL Server combination, but currently I have a task for which express/Node.js seems to be more appropriate (and I'd like to play with something new), so the question is whether we can rely on a Node.js and SQL Server interaction.
UPD: It seems that Microsoft has, at last, released the official driver: https://github.com/WindowsAzure/node-sqlserver
This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.
At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.
"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.
On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.
If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE
Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js
Just in case, if the above links are not working, I am including the source code here:
var sql = require("mssql");
var dbConfig = {
server: "localhost\\SQL2K14",
database: "SampleDb",
user: "sa",
password: "sql2014",
port: 1433
};
function getEmp() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM emp").then(function (recordset) {
console.log(recordset);
conn.close();
})
.catch(function (err) {
console.log(err);
conn.close();
});
})
.catch(function (err) {
console.log(err);
});
//--> another way
//var req = new sql.Request(conn);
//conn.connect(function (err) {
// if (err) {
// console.log(err);
// return;
// }
// req.query("SELECT * FROM emp", function (err, recordset) {
// if (err) {
// console.log(err);
// }
// else {
// console.log(recordset);
// }
// conn.close();
// });
//});
}
getEmp();
The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.
The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql
UPDATE:
There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
We just released preview driver for Node.JS for SQL Server connectivity. You can find it here:
Introducing the Microsoft Driver for Node.JS for SQL Server.
The driver supports callbacks (here, we're connecting to a local SQL Server instance):
// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
if (err) {
console.log("Error running query!");
return;
}
for (var i = 0; i < results.rows.length; i++) {
console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
}
});
});
Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):
// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";
var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });
If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues
There is a module on npm called mssqlhelper
You can install it to your project by npm i mssqlhelper
Example of connecting and performing a query:
var db = require('./index');
db.config({
host: '192.168.1.100'
,port: 1433
,userName: 'sa'
,password: '123'
,database:'testdb'
});
db.query(
'select #Param1 Param1,#Param2 Param2'
,{
Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
,Param2: { type : 'Int',value : 321 }
}
,function(res){
if(res.err)throw new Error('database error:'+res.err.msg);
var rows = res.tables[0].rows;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
}
}
);
You can read more about it here: https://github.com/play175/mssqlhelper
:o)
msnodesql is working out great for me. Here is a sample:
var mssql = require('msnodesql'),
express = require('express'),
app = express(),
nconf = require('nconf')
nconf.env()
.file({ file: 'config.json' });
var conn = nconf.get("SQL_CONN");
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";
app.get('/api/brands', function(req, res){
var data = [];
var jsonObject = {};
mssql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("dbo.storedproc", function (err, results) {
if(err) {
console.log(err);
res.send(500, "Cannot retrieve records.");
}
else {
//res.json(results);
for (var i = 0; i < results.rows.length; i++) {
var jsonObject = new Object()
for (var j = 0; j < results.meta.length; j++) {
paramName = results.meta[j].name;
paramValue = results.rows[i][j];
jsonObject[paramName] = paramValue;
}
data.push(jsonObject); //This is a js object we are jsonizing not real json until res.send
}
res.send(data);
}
});
});
});
//start the program
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'datapullman',
password: 'system',
server: 'localhost',
database: 'chat6'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * From emp", function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
//create a table as emp in a database (i have created as chat6)
// programs ends here
//save it as app.js and run as node app.js
//open in you browser as localhost:5000