I am trying to connect to postgres database instance in aws but I can't - database

I have the following code.
var express = require('express');
var app = express();
var path = require('path');
var pg = require('pg');
var conString = "postgres://user:password#endpoint:5432/StudentRecords";
//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 20 (also configurable)
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
else{
console.log("asdfaf")
}
});
client.connect();
It shows cannot connect to postgres. But when I try connecting from the terminal using
psql --host=endpoint --port=5432 --username xxxxx --password --dbname=StudentRecords
I can connect. Why is the code not working? Error I am getting is:
could not connect to postgres [Error: Connection terminated]

Related

How to use modern authentication to execute EXO V2 PowerShell commands through program in Asp.NET Core C#

We have register an application with permission Delegated permission: Exchange.Manage, Application permission: Exchange.ManageAsApp
When try to open Runspace using that token to execute Remote EXO V2 command but with that system returns error: Connecting to remote server outlook.office365.com failed with the following error message : For more information, see the about_Remote_Troubleshooting Help topic.
We use below code to connect:
PSCredential pSCredential = new PSCredential(inputUserName, new NetworkCredential("", inputPassword).SecurePassword);
string MailboxName = pSCredential.UserName;
string scope = "https://outlook.office365.com/.default";
string ClientId = Configuration.Client_Id;
string clientSecret = Configuration.ClientSecret;
HttpClient Client = new HttpClient();
var TenantId = ((dynamic)JsonConvert.DeserializeObject(Client.GetAsync("https://login.microsoftonline.com/" + MailboxName.Split('#')[1] + "/v2.0/.well-known/openid-configuration").Result.Content.ReadAsStringAsync().Result)).authorization_endpoint.ToString().Split('/')[3];
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(clientSecret)
.WithTenantId(TenantId)
.Build();
var TokenResult = app.AcquireTokenForClient(new[] { scope }).ExecuteAsync().Result;
System.Security.SecureString secureString = new System.Security.SecureString();
foreach (char c in ("bearer " + TokenResult.AccessToken))
secureString.AppendChar(c);
String WSManURIConnectionString = "https://outlook.office365.com/powershell-liveid?DelegatedOrg=" + MailboxName.Split('#')[1] + "&BasicAuthToOAuthConversion=true";
PSCredential credential = new PSCredential(MailboxName, secureString);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(WSManURIConnectionString), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 10;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
runspace.Close();
}
runspace.Open();
// Make a Get-EXOMailbox requst using the Server Argument
Command gmGetMailbox = new Command("Get-EXOMailbox");
gmGetMailbox.Parameters.Add("ResultSize", "Unlimited");
Pipeline plPileLine = runspace.CreatePipeline();
plPileLine.Commands.Add(gmGetMailbox);
Collection<PSObject> RsResultsresults = plPileLine.Invoke();
plPileLine.Stop();
plPileLine.Dispose();

Reactjs AWS RDS retrieve

I am unable to connect and retrieve my data from AWS RDS. I've used SQL Server Management Studio(SSMS) to do the manipulation of the data. I've stored my credentials in .env file. Below are my code:
.env
REACT_APP_API_KEY = 'my-secret-api-key'
RDS_HOSTNAME= 1001
RDS_USERNAME= Admi
RDS_PASSWORD = Password
RDS_PORT = 1041
dbConfig.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT
});
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();

How to fix this issue, when local account has been changed from your sql server and thrown file path be changed?

I have this error, on my project folder i have created _AppStart.mdf while the account on SQL Server from the Administration Service changed to local account on sql server. Now i am getting this exception each time i am trying to create new users to my database. What can i do to resolve this issue?
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
user.Email = model.Email;
user.ConfirmedEmail = false;
var result = await UserManager.CreateAsync(user, model.Password); ?/** This throws an error line 88, each time new user is created. **/
if (result.Succeeded)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(
new System.Net.Mail.MailAddress("ggcobani#gmail.com", "Web Registration"),
new System.Net.Mail.MailAddress(user.Email));
m.Subject = "Email confirmation";
m.Body = string.Format("Dear {0}<BR/>Thank you for your registration, please click on the below link to complete your registration: {1}", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.Email }, Request.Url.Scheme));
m.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.mydomain.com");
smtp.Credentials = new System.Net.NetworkCredential("ggcobani#gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(m);
return RedirectToAction("Confirm", "Account", new { Email = user.Email });
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
<connectionStrings>
<add name = "eNtsaOnlineRegistrationDB" connectionString = "Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\eNtsaOnlineRegistrationDB.mdf;Initial Catalog=eNtsaOnlineRegistration; Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
The issue was file was existing on the project folder. Under _AppStart.mdf
Re changed my connectionString as shown, the error is gone although its throwing a new one due to connected party.

Socket.io disconnecting

I have a chat done in nodejs, Express, socket.io and angular. It works well but disconnects sometimes and at random times. Generally the connection lasts no more than 2 minutes. I get several net :: ERR_CONNECTION_TIMED_OUT on the console.
PS.: I'm using apache 2.2 on CentOS with certified ssl.
Any tips?
My server.js header is below
#!/bin/env node
var express = require('express'),
path = require('path'),
app = express(),
logger = require('morgan'),
_m = require("./models/Message"),
Message = _m.m,
NewMessage = _m.n,
Group = _m.g,
Online = _m.o,
DeletedMessage = _m.d,
LastMessage = _m.l,
_mTASK = require("./models/Task"),
_Task = _mTASK.t,
TaskComment = _mTASK.c,
TaskLog = _mTASK.l,
TaskModel = _mTASK.m,
TaskNotification = _mTASK.n,
_d = require("./lib/Connection");
app.use(logger('dev'));
app.set('port', 3000);
app.set('ipaddr', "127.0.0.1");
var server = require('http').createServer(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
server.listen(app.get('port'), app.get('ipaddr'), function() {
console.log('Express server listening on IP: ' + app.get('ipaddr') + ' and port ' + app.get('port'));
});
var io = require("socket.io")(server);
io.set("origins", 'https://meusite.me:*');
io.set('transports', ['polling', 'websocket']);
A bit of socket.io background
Server sends a heartbeat to the client every X seconds where X == the
heartbeat interval configuration value.
If the client fails to respond, socket considers the connect dead
Client waits for a heartbeat from the server every N seconds where N == the heartbeat timeout configuration value.
Both of these values are set on the server with heartbeat timeout being sent to the client when an individual connection is opened.
Given the file above, you could set the heartbeat timeout with something like ...
//WARNING io.set() has been depricated
var io = require("socket.io")(server);
io.set('heartbeat interval', '30000');
io.set('heartbeat timeout', '45000');
io.set("origins", 'https://meusite.me:*');
io.set('transports', ['polling', 'websocket']);
//Setting your server configuration is now done via ..
var socket = require('socket.io')({
// options go here
'configOption': 'configValue';
});

Prerender.io throws socket error

I have been trying to make prerender.io working for a week now, I tried everything but nothing worked.
I have a node server:
'use strict';
var path = require('path');
var _ = require('lodash');
var express = require('express');
var app = module.exports = express();
var prerender = require('prerender-node')
.set('prerenderToken', 'My Key');
// These search engine bot do not adheres to google's _escaped_fragment_
// proposal, so we use user agent to detect them.
var moreCrawlerUserAgents = [
'Slurp!',
'MSNBot',
'YoudaoBot',
'JikeSpider',
'Sosospider',
'360Spider',
'Sogou web spider',
'Sogou inst spider',
'baiduspider',
'facebookexternalhit',
'twitterbot',
'rogerbot',
'linkedinbot',
'embedly',
'quora link preview',
'showyoubot',
'outbrain',
'pinterest',
'developers.google.com/+/web/snippet',
'slackbot',
'vkShare',
'W3C_Validator',
'redditbot'
];
prerender.set('crawlerUserAgents', _.union(
prerender.crawlerUserAgents, moreCrawlerUserAgents));
app.use(prerender);
var options = {
maxAge: '60d',
setHeaders: function(res, path, stat) {
// Webfonts need to have CORS * set in order to work.
if (path.match(/ttf|woff|woff2|eot|svg/ig)) {
res.set('Access-Control-Allow-Origin', '*');
}
}
};
var dist_path = '/client/dist/';
app.use(express.static(path.join(__dirname, dist_path), options));
app.use(function(req, res) {
res.sendFile(path.join(__dirname + dist_path + '/index.html'));
});
var port = process.env.PORT || 8000;
app.listen(port, '0.0.0.0');
console.log("Listening on port " + port);
It works fine until I pass _escaped_fragment_= as a query string parameter then it throws these two errors:
Error: getaddrinfo EMFILE
at Object.exports._errnoException (util.js:746:11)
at errnoException (dns.js:49:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:94:26)
OR
Error: socket hang up
at createHangUpError (_http_client.js:215:15)
at Socket.socketOnEnd (_http_client.js:300:23)
at Socket.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
I don't know what the problem is, please help!
Thanks.

Resources