retry sql connection using JavaScript - javascript

I know using javascript is not the best way to connect to a SQL server but this is for an in-house application. I connect using the following:
dbNSConnection = new ActiveXObject("ADODB.Connection") ;
var sNSConnectionString="Driver={SQL Server};TrustedConnection=Yes;Server=" + sNSServer + ";Database=" + sNSDatabase + ";UID=" + sNSUID + ";PWD=" + sNSPWD;
dbNSConnection.Open(sNSConnectionString);
How can I make sure connection has gone thru and how do I retry if not connected?

Isn't there any other way you could get this done on the codebehind, and pass the results to the javascript? This may be an example of what I'm talking about originally.
If not, can't you simply do the following?
try
{
dbNSConnection = new ActiveXObject("ADODB.Connection") ;
var sNSConnectionString="Driver={SQL Server};TrustedConnection=Yes;Server=" + sNSServer + ";Database=" + sNSDatabase + ";UID=" + sNSUID + ";PWD=" + sNSPWD;
dbNSConnection.Open(sNSConnectionString);
//Run rest of query here
}
catch(err)
{
var message = err.message;
//Finish building errors message here
}

Related

Event Stream data not showing in Chrome console

I have an EventSource listener on my frontend calling a complicated backend scheme. This code block is written in Typescript.
import * as EventSource from 'eventsource';
private streamData() {
let source = new EventSource('http://localhost:3000/websocket/server/stream');
source.onopen = (e) => {
};
source.onmessage = (e) => {
console.log('id: ' + (<any>e).lastEventId + '; type: ' + e.type + ' data: ' + e.data);
};
}
And I send back the following response to my server :
res.write('id: ' + this.messageId++ + '\n');
res.write('type: message\n');
res.write('data: ' + message + '\n\n');
res.flush();
Now, on the Chrome console, I get all the data needed.
However, on the xhr monitor, I cannot see the EventStream data.
I get the info on my frontend, so this is not a blocking issue for me, but may pose some problems later in debugging.
I had the same issue. The data does not show up when you are using the eventsource polyfill only when you use the built in browser implementation of the EventSource class.

Can't send sms with Twilio, Node.js and Sequelize

I have a program which respond automatically a sms when receive an income message.
It works when I don't use Sequelize to save data to the database. But when I add the code below, the twiml.message(msg) is never executed.
The problem is when call twiml.message(msg) inside the then it doesn't work. So how to resolve this problem? Thanks
Info.create(param)
.then(info => {
var msg = 'Numero: ' + info.id +
' Nom:' + info.nom +
' Date: ' + info.datesms);
var twiml = new MessagingResponse();
twiml.message(msg);
});

How to send data to specific sockets created using net.createServer() connection event?

I am used to perl and POE programming when it comes to sockets, and I am looking at using node.js for an application server that is not web based. I have JavaScript knowledge from writing webpage user interfaces.
I have been working with the net module and have successfully been able to connect to it from multiple clients at the same time.
var net = require('net');
var port = 63146;
var socketNum = 0;
var adminServer = net.createServer(function(socket){
//add connection count
socketNum++;
socket.nickname = "Con# " + socketNum;
var clientName = socket.nickname;
console.log(clientName + "connected from " + socket.remoteAddress);
socket.write("You have been given the client name of " + clientName);
});
adminServer.listen(port, function() {
console.log("Server listening at" + port);
});
So the issue I am having is if I have another function created that needs to send data to a specific client, not a broadcast to all of them, I can't figure out how to do it.
I have done extensive searching here and Google. Lots of examples of simple tcp servers and echo servers to a single client, but nothing for multiple clients.
I am trying to do this WITHOUT socket.io as not all the clients are going to be web based.
Any help would be appreciated,
Z
You have to store them yourself somehow, whether that's simply adding to an array or adding to an object keyed on some unique identifier for example.
Here's using an object:
var net = require('net');
var port = 63146;
var socketNum = 0;
var sockets = Object.create(null);
var adminServer = net.createServer(function(socket){
//add connection count
socketNum++;
socket.nickname = "Con# " + socketNum;
var clientName = socket.nickname;
sockets[clientName] = socket;
socket.on('close', function() {
delete sockets[clientName];
});
console.log(clientName + " connected from " + socket.remoteAddress);
socket.write("You have been given the client name of " + clientName);
});
adminServer.listen(port, function() {
console.log("Server listening at" + port);
});
Then you can find a particular socket by its assigned nickname.
Here is the example working code. Hopefully this will be useful to others!
var net = require('net');
var port = 63146;
var conSeen = Object.create(null);
var socketNum = 0;
var adminServer = net.createServer(function(socket){
//add connection count
socketNum++;
socket.nickname = "Con" + socketNum;
var clientName = socket.nickname;
//console.log(socket);
conSeen[clientName] = socket;
socket.on('close', function() {
delete sockets[clientName];
});
console.log(clientName + " has connected from " + socket.remoteAddress);
socket.write("You have been given the client name of " + clientName + "\r\n");
socket.on('data', function(inputSeen) {
var clientName = socket.nickname;
var input = inputSeen.toString('utf8');
input = input.replace(/(\r\n|\n|\r)/gm,"");
console.log("Saw : " + input + " from " + clientName + "\r\n");
if (input === 'sendTest') {
conSeen[clientName].write('test 123\r\n');
}
});
});
adminServer.listen(port, function() {
console.log("Server listening on " + port);
});

Node JS application using 100% CPU

We are making a back-end application in Node.JS for an iPhone app.
We deployed our back-end application (Node) on EC2 instance (t2.medium) which is using MySQL server installed on another EC2 instance (t2.small). While doing load testing we saw CPU is using 100 %. We tried to find out reason but as far did not find it.
We are using following modules in our server.js.
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var log = require('./utils/logger');
var userRequestHandler = require("./requestHandlers/userRequestHandler");
var authenticationHandler = require("./requestHandlers/authenticationHandler");
var verificationHandler = require("./twilioVerification/verificationHandler");
var eventRequestHandler = require("./requestHandlers/eventRequestHandler");
var urls = require('config').get('urls');
var sessionParameters = require('config').get('sessionParameters');
var app = express();
We are using JMeter to do our load testing. With JMeter we could run 450 requests only (450 requests using single instance or 150 request with 3 instances). If we tried with more than 450, we got following error in JMeter.
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:166)
at org.apache.http.impl.io.SocketInputBuffer.fillBuffer(SocketInputBuffer.java:90)
at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:281)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:92)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:61)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
In case of 450 or less number of requests, our CPU usage reached 100%. We are new to Node JS, but as per our understanding our code is non-blocking but not sure though. Code of main method is given below, please let us know how to make it non-blocking if it is blocking code.
When we are calling first method, following code is being executed.
exports.authenticate = function(req, res) {
log.debug(req.headers['deviceID'] + messages.enterMethod + new Date());
var deviceId = req.headers['deviceID'];
if(deviceId != undefined){
log.debug(deviceId + messages.fetchFromDB + new Date());
authentication.find({where: {deviceID: deviceId}}).success(function(authObj){
log.debug(deviceId + messages.fetchedFromDB + new Date());
var validationString = "<customData>";
if(authObj != null){
if(timeStamp > authObj.timeStamp){
log.debug(deviceId + messages.validateUser + new Date());
if(isValidUser(validationString, deviceId)){
log.debug(deviceId + messages.updateUserTime + new Date());
authObj.updateAttributes({timeStamp: timeStamp}).success(function() {
log.debug(deviceId + messages.updatedUserTime + new Date());
generateSession(deviceId, req, res);
}).error(function(err){
res.status(500).json({status: err});
});
}else{
log.debug(deviceId + messages.InvalidUser + new Date());
res.status(401).json(messages.authenticationFailed);
}
}else{
log.debug(deviceId + messages.wrongTime + new Date());
res.status(401).json(messages.authenticationFailed);
}
}else{
log.debug(deviceId + messages.validateUser + new Date());
if(isValidUser(validationString, deviceId)){
log.debug(deviceId + messages.createUserTime + new Date());
authentication.create({deviceID: deviceId, timeStamp: timeStamp}).success(function(authentication){
log.debug(deviceId + messages.createdUserTime + new Date());
generateSession(deviceId, req, res);
}).error(function(err){
res.status(500).json({status: err});
});;
}else{
log.debug(deviceId + messages.InvalidUser + new Date());
res.status(401).json(messages.authenticationFailed);
}
}
});
}else{
res.status(401).json(messages.authenticationFailed);
}
};
Please help us to find out the reason of CPU 100% usage and how to test our application for 2000 or more users?
Let me know in case you need something else.
Regards,
Krishan

Read email headers in Outlook Web Access (OWA)

I am developing a outlook Web App (Office 365 Developer). Regarding that, is there a way to read the headers of the selected mail which lays on inbox?. I am using Exchange server 2013. I would like to use Jquery or Javascript for write the code.
I tried to add "Message Header Analyzer" from Microsoft ( link:- 'https://store.office.com/message-header-analyzer-WA104005406.aspx?assetid=WA104005406'). Now it is working properly and it can read headers. But I need to implement the same functionality using my own codes.
If anyone can provide a good reference as a start, I would greatly appreciated that. (because, I got a great effort in searching google. But.. still no luck)
thanks in advance.
First of all, I would like to thank all the persons who responded to me to develop a solution to this. Special thanks should go to #FreeAsInBeer and MrPiao. After spending several days I was able to develop the following solution for getting mail headers. I removed all the unnecessary business logic from the code and finally came up with the following code. It can be used for reading the headers of inbox emails using JQuery.
I am making an EWS request outside to get the headers. From its callback method, I can retrieve the expected result. Afterwards, it is better to use jQuery.parseXML to read and manipulate the response (which is not included in the code)
I hope this explanation will help you.
var _mailbox;
var _ItemId1
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
_mailbox = Office.context.mailbox;
_ItemId1 = _mailbox.item.itemId;
});
};
})();
function getSelectedEmailHeaders() {
// Wrap an Exchange Web Services request in a SOAP envelope.
var var1 = '<?xml version="1.0" encoding="utf-8"?>';
var var2 = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
var var3 = ' <soap:Header>';
var var4 = ' <t:RequestServerVersion Version="Exchange2010" />';
var var5 = ' </soap:Header>';
var var6 = ' <soap:Body>';
var var7 = ' <m:GetItem>';
var var8 = ' <m:ItemShape>';
var var9 = ' <t:BaseShape>IdOnly</t:BaseShape>';
var var10 = ' <t:AdditionalProperties>';
var var11 = ' <t:FieldURI FieldURI="item:Subject" />';
var var12 = ' <t:FieldURI FieldURI="item:MimeContent" />';
var var13 = ' </t:AdditionalProperties>';
var var14 = ' </m:ItemShape>';
var var15 = ' <m:ItemIds>';
var var16 = ' <t:ItemId Id="' + _ItemId1 + '" />';
var var17 = ' </m:ItemIds>';
var var18 = ' </m:GetItem>';
var var19 = ' </soap:Body>';
var var20 = '</soap:Envelope>';
var envelopeForHeaders = var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20;
//Calling EWS
_mailbox.makeEwsRequestAsync(envelopeForHeaders, callbackForHeaders);
}
//This Function called when the EWS request is complete.
function callbackForHeaders(asyncResult) {
//Write the content of the asyncResult on console
console.log(asyncResult);
}
Thank You. Kushan Randima

Categories

Resources