Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Npgsql : is the server down or a bad password?

I am trying to connect to PostgreSQL database from my c# application like so:

NpgsqlConnection MyConnection = new           
NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=mypassword;Database=mydatabase;");
try
{
    MyConnection.Open();
}
catch (NpgsqlException pe)
{              
    //Code "28P01" = user name or password is wrong 
    // server ip or port  is wrong
}

the question is : NpgsqlException.code does not differentiate between the following conditions:

  1. server ip /port number is wrong
  2. user name and password combination is wrong

Code "28P01" is returned in both cases. obviously Npgsql can see that the server is there and responding with some data indicating bad user name or password (condition #2 above) or nobody seem to be there (condition #1 above)

how can i differentiate between those 2 cases in my code?

like image 922
Esam A Kanadily Avatar asked Sep 05 '15 00:09

Esam A Kanadily


Video Answer


2 Answers

with Npgsql v 3.0.2.0 (not sure about older versions) if the IP/hostname is wrong an Exception with code =-2146233083 with be thrown. if however the IP/hostname is correct but the port number is wrong Exception with code= -2147467259 with be thrown. if the IP/port is correct but username /password is wrong a NpgsqlException with code = "28P01" will be thrown.

like image 137
EKanadily Avatar answered Sep 23 '22 10:09

EKanadily


You're probably using Npgsql 2.x; the new Npgsql 3.x throws NpgsqlException only when errors are received from a PostgreSQL server. Network connection errors are raised as SocketException etc. You're encouraged to upgrade.

By the way: I couldn't reproduce your exact findings even with Npgql 2.x, connecting to a wrong port or a wrong IP resulted in an NpgsqlException with Code being an empty string, not 28P01.

like image 44
Shay Rojansky Avatar answered Sep 21 '22 10:09

Shay Rojansky