I want to use use tedious in my Azure web app to follow this tutorial https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-nodejs I get the error "Uncaught Error: Module name "tedious" has not been loaded yet" with require('tedious').Connection. How do I load this module in Azure?
The javascript code:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
// Create connection to database
var config = {
userName: '******', // update me
password: '*****', // update me
server: '*******', // update me
options: {
database: 'signals' //update me
}
}
var connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on('connect', function(err) {
if (err) {
console.log(err)
}
else{
queryDatabase()
}
});
function queryDatabase(){
console.log("test");
console.log("test");
console.log('Reading rows from the Table...');
// Read all rows from table
request = new Request(
"SELECT * FROM signals",
function(err, rowCount, rows) {
console.log(rowCount + ' row(s) returned');
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
How do I load this module in Azure?
In Azure, you can install Node.js module through Kudu Debug Console which could be accessed via https://<your-web-app-name>.scm.azurewebsites.net/DebugConsole
cd to D:\home\site\wwwroot in the console.
run the following command inside the wwwroot directory: npm install tedious
Related
I have a AWS Lambda (Node.js) talking to an Aurora database. Both belong to the same VPC, with internet access enabled via subnet. The RDS cluster also has a inbound rule that allows traffic from the VPC, used for the Lambda (which should be the same VPC). To my surprise, I found that the RDSDataService from AWS-SDK fails to connect to the database, whereas when I use mysql pacakge, it works. Following are the 2 code snippets.
I would like it very much to use AWS-SDK, as that will reduce the deployment bundle size, as I don't have to include that in the bundle that at all. Is there anyway to achieve that?
Failed attempt to use RDSDataService
const AWS = require("aws-sdk");
const rdsData = new AWS.RDSDataService({
params: {
dbClusterOrInstanceArn: 'rds.cluster.arn',
awsSecretStoreArn: 'rds.cluster.secret.arn',
database: 'mydb'
},
endpoint: 'mydb.endpoint'
});
return new Promise((resolve, reject) => {
try {
rdsData.executeSql({
dbClusterOrInstanceArn: 'rds.cluster.arn',
awsSecretStoreArn: 'rds.cluster.secret.arn',
database: 'mydb',
sqlStatements: "select 1 + 1 as result;"
}, (err, data) => {
if (err) {
reject(err);
}
const response = {
statusCode: 200,
body: JSON.stringify(data),
};
resolve(response);
});
} catch (er) {
reject(er);
}
});
Working implementation using mysql
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'mydb.endpoint',
user: 'user',
password: 'password',
port: 3306,
database: 'mydb',
debug: false
});
connection.connect(function (err) {
if (err) context.fail();
else {
connection.query('select 1 + 1 as result', function (error, results, fields) {
if (error) throw error;
resolve('The solution is: ' + JSON.stringify(results, undefined, 2));
});
}
});
connection.end();
As it turned out, Data API is not yet available for my region. The supported regions are listed here: https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html#data-api.regions
I have to authenticate to Bitmex API using my Api key but I got this error
Unable to connect: TypeError: Cannot read property 'add' of undefined
'use strict';
var SwaggerClient = require("swagger-client");
var _ = require('lodash');
var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization');
require('dotenv').config();
new SwaggerClient({
// Switch this to `www.bitmex.com` when you're ready to try it out for real.
// Don't forget the `www`!
url: 'https://testnet.bitmex.com/api/explorer/swagger.json',
usePromise: true
})
.then(function(client) {
//console.log(client);
// Comment out if you're not requesting any user data.
client.clientAuthorizations.add("apiKey", new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET));
// Print client capabilities
//
})
.catch(function(e) {
console.error("Unable to connect:", e);
})
Nodejs connector: https://github.com/BitMEX/api-connectors
You're using the latest version of the client, which doesn't do authorizations that way: https://github.com/swagger-api/swagger-js/blob/903569948d5a5c718d7b87d6832a672de4e76afc/docs/MIGRATION_2_X.md#authorizations
new SwaggerClient({
// Switch this to `www.bitmex.com` when you're ready to try it out for real.
// Don't forget the `www`!
url: 'https://testnet.bitmex.com/api/explorer/swagger.json',
usePromise: true,
authorizations: {
apiKey: new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET)
}
})
.then(client => {
// Do whatever with client
})
.catch(function(e) {
console.error("Unable to connect:", e);
})
Steps:
Create Azure mobile app with node.js backend. (server)
Create NotificationHub associated to the new mobile app. (server)
Create WinJS App (Universal Windows) in Visual Studio (client)
Associate app with App Store VS > Project > Store > Associate App with Store (client)
Include Mobile Services MobileServices.Web.js to connect with mobile services backend (client)
Connect to mobile service backend (client = new WindowsAzure.MobileServiceClient('https://.azurewebsites.net') (client)
I am having a problem trying to get the tags for push notification hub that is tied to my azure mobile service node.js backend.
I am following this blog post:
https://blogs.msdn.microsoft.com/writingdata_services/2016/04/14/adding-push-notification-tags-from-a-node-js-backend/
on how to create tags on the node.js backend.
When I call the createTags API I am presuming the tag is being created because there is no error being returned.
But when I call getTags API my error routine is firing with the error
An error occurred when retrieving installation
Error: 404 - Installation not found.TrackingId:0615f100-35fe-496e-b63d-53d39d7e1cf9_G1,TimeStamp:10/27/2016 9:46:25 PM
I can't figure out why I am getting this error?
Can anyone see what I am missing or need to do to fix this problem?
Any help would be appreciated.
createTags.js
module.exports = {
"post": function (req, res, next) {
// Get the notification hub used by the mobile app.
var push = req.azureMobile.push;
console.log('create tags installationId ' + req.body.installationId);
console.log('tags ' + req.body.tags.toString());
// Validate for and block any SID tags.
for (var i = 0; i < req.body.tags.length; i++) {
if (req.body.tags[i].search("sid:") !== -1) {
res.status(403)
.send("You cannot set '" + req.body.tags[i] + "' as a tag.");
return;
}
}
// Define an update tags operation.
var updateOperation = [{
"op": "add",
"path": "/tags",
"value": req.body.tags.toString()
}];
// Update the installation to add the new tags.
push.patchInstallation(req.body.installationId, updateOperation, function(error, response){
if(error){
console.log('An error occurred when adding tags\n\n' + error);
res.status(error.statusCode).send(error.detail);
}
else res.status(200).send();
});
}
};
getTags.js
module.exports = {
"post": function (req, res, next) {
// Get the notification hub used by the mobile app.
var push = req.azureMobile.push;
console.log('getting tags');
if (typeof req.body.installationId !== "undefined"){
push.getInstallation(req.body.installationId, function (error, response) {
if (error) {
console.log('An error occurred when retrieving installation\n\n' + error);
res.status(error.statusCode).send(error);
}
else {
console.log("got installation " + req.body.installationId + '\n\n' + JSON.stringify(response));
res.status(200).send(response);
}
});
}
else res.status(200).send();
}
};
main.js - here is my winjs app to create the tag and then check that it was created
client = new WindowsAzure.MobileServiceClient('https://<sitename>.azurewebsites.net');
client.invokeApi("createTags", {
body: {
installationId: client.push.installationId,
tags: ['public']
},
method: "post"
}).then(function (result) {
client.invokeApi("getTags", {
body: {
installationId: client.push.installationId,
},
method: "post"
}).then(function (result) {
WinJS.log(result);
completeDispatcher();
}, function (error) {
WinJS.log(error);
completeDispatcher();
});
}, function (error) {
WinJS.log(error);
completeDispatcher();
});
Update now trying to use this to create a channel first. Then register a listener.
// Request a push notification channel.
Windows.Networking.PushNotifications
.PushNotificationChannelManager
.createPushNotificationChannelForApplicationAsync()
.then(function (newChannel) {
channel = newChannel;
// Register for notifications using the new channel
Machine.Client.push.register('wns', channel.uri, ['public']).done(function (error, response) {
// store the channel
channel.removeEventListener("pushnotificationreceived", pushNotificationReceivedHandler);
channel.addEventListener("pushnotificationreceived", pushNotificationReceivedHandler);
completeDispatcher();
});
}, function (error) {
var dialog = new Windows.UI.Popups.MessageDialog(error, "Error");
dialog.showAsync().then(function () {
completeDispatcher();
});
});
For these type of issues, usually going through Notification Hubs Diagnosis guidelines should give you an idea where the problem is. The 'Verify registrations' section there might be helpful in your case.
If nothing there helps, could update the question with what you've learned?
I have installed the node-oracle module and have connected to an oracle database successfully. But, I have a problem when I execute a select query. My code is below (the file name is tests-connection.js):
var oracle = require('./');
var connectData = {
hostname: "myhost",
port: 1521,
database: "mydb", // System ID (SID)
user: "usertest",
password: "mypass"
}
oracle.connect(connectData, function(err, connection) {
if (err) { console.log("Error connecting to db:", err); return; }
connection.execute("SELECT systimestamp FROM DUAL", [], function(err, results) {
if (err) { console.log("Error executing query:", err); return; }
console.log(results); //This statement's not working
connection.close(); // call only when query is finished executing
});
});
The output in Node.js command prompt (nothing):
C:\xampp\htdocs\motcua.dev\public\socket.io\node_modules\oracle>node tests-connection
C:\xampp\htdocs\motcua.dev\public\socket.io\node_modules\oracle>
I have tried to update a record and it works, but when I execute a select query I do not see any output in the console log statement. The terminal is empty until the code that is executing is finished.
How can one fix this problem?
Thanks
I am trying to connect to hbase via. nodejs hbase module.
I have used
https://github.com/wdavidw/node-hbase
to download hbase module for nodejs and trying to run the below code in my nodejs script which uses express and handles the incoming request :-
.......
app.post('/upload', function(req, res,next){
var read_stream = fs.createReadStream(req.files.upload_file.path, {encoding: 'base64'});
read_stream.on("data", function(data){
// process.stdout.write(data);
dataload(data);
});
read_stream.on("error", function(err){
console.error("An error occurred: %s", err)
});
read_stream.on("close", function(){
console.log("File closed.")
});
}
function dataload(data){
var hbase = require('hbase');
var tableobj=hbase({ host: "{my server ip}", port: "8080" }).getTable('my_table1');
sys.debug(tableobj);
tableobj.create("my_column_family", function(err, success){
if(err)
{
sys.debug("error1");
}
else
{
this.getRow('my_row')
.put('my_column_family:my_column', data, function(err, success){
if(err)
{
sys.debug("error");
}
else
{
sys.debug("success");
}
});
}
});
}
Problem faced :- when i restart the server[i.e the server created by this script by again giving "node {script js file name}" on cygwin command prompt] , then the hbase table is re-created and all the rows previously inserted are removed.