Npgsql : is the server down or a bad password? - c#

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:
server ip /port number is wrong
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?

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.

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.

Related

Connection error SASL error with QPID and AmqNetLite

I am not familiar with AMQP.
I try to connect a AmqpNetLite program to a Qpid server and I get the following exception :
Amqp.AmqpException: sasl-mechanisms(sasl-server-mechanisms:[CRAM-MD5,SCRAM-SHA-1,SCRAM-SHA-256])
Note : I am able to connect to a basic AMQP server, but not QPID.
Here is the code to create the connection:
Please tell where to start to fix my problem.
void Main(string[] args)
{
try
{
Address address = new Address("amqp://guest:guest#localhost:5672");
Connection connection = new Connection(address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-link", "queue");
Message message = receiver.Receive();
receiver.Accept(message);
receiver.Close();
session.Close();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
The error would seem to indicate that the broker is not able to provide the client with a SASL mechanism that it supports. I think that AmqpNetLite only does ANONYMOUS, PLAIN and EXTERNAL but perhaps that's changed. You could look into your broker configuration and make one of those mechanisms available to the client and that will probably allow for a match and successful authentication. Or you could use an SSL connection which would then allow those SASL mechanisms to work and provide a bit of extra security for you connection.
The security section of the Broker-J documentation site should shed some light on this for you.

C# SQL Server connection using server Login

I have a problem with connecting to my SQL server. I keep getting "Login failed for user" error messages, but the user I am trying to login as exists as a login on the server. The connection string I use looks like this:
Data Source=[server name];Initial Catalog=[database];User ID=[login name];Password=[login password];
Is it because the login exists on the server, but not as a user on the database that I can't use it to login?
If so is it not possible for me to connect to the server using a server login?
Thanks in advance.
It may be that there is something else wrong with your connection string. I know if I have the wrong database or server in the string it will be give me an "unable to login with user..." message.
Data Source=[server name];Initial Catalog=[database];User ID=[login name];Password=[login password];
Use this code to connect SQL Server (preferrd Language is C#)
Public Sub Start_DB_Connection(servername As String,user As String,password As String,dbname As String)
Try
db_con As New SqlConnection
If Not db_con Is Nothing Then db_con.Close()
db_con.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; connection timeout=1;", servername, user, password, dbname)
db_con.Open()
Catch ex As Exception
// show error
End Try
End Sub

How do you connect from ODP.NET to Oracle (12G+) by proxy user with no password

There seems to be no answer online as to how you can use Oracle Data Provider for .NET (ODP.NET) to connect to Oracle (12G and later) in a very specific scenario:
User is identified externally on a database
User is granted access to another schema (application user) by proxy connect
User has been set up like this:
CREATE USER user_in_question
IDENTIFIED EXTERNALLY
-- etc.
And connect by proxy has been set up like this:
ALTER USER specified_app_user GRANT CONNECT THROUGH user_in_question
The logical approach when creating the ODP.NET OracleConnection string would be something like this (using the user friendly OracleConnectionStringBuilder):
var connBuilder = new OracleConnectionStringBuilder
{
UserID = "/", // External login using the user running the program
ProxyUserId = "specified_app_user",
DataSource = "database",
};
This does not work. Nor does providing blank "Password" or blank "Proxy Password". Nor does removing the UserId.
So how do you connect using ODP.NET in these circumstances?
The answer (which I spend an hour searching for without any luck) is actually really simple, yet not very user friendly:
var connBuilder = new OracleConnectionStringBuilder
{
UserID = "[specified_app_user]",
DataSource = "database",
};
//connBuilder.ToString() output:
//"USER ID=[specified_app_user];DATA SOURCE=database"
This works in .NET 4.5+ on Oracle 12G+, but probably also on earlier platforms of .NET/Oracle/ODP.NET. I did not test it in ASP.NET, but it should work there too.
This way the UserId actually functions just like the ProxyUserId, just enclosed within brackets, just as you would normally log in on the Oracle Database using, say, Toad or SQlPlus.
It might also be possible using this format (but in my case the connection string had to be compatible with the OraOLEDB format so that did not work):
//Without the use of the conn string builder class, just for the fun of it...
var connString = "User Id=specified_app_user;Data Source=database;Proxy User Id=/";
EDITED 2nd March 2017: The line above does not seem to work in certain cases. Added comment about it and here is the code that IS working:
USER ID=[specified_app_user];DATA SOURCE=database
This info does not seem to exist anywhere - else I overlooked it, and in that case PLEASE do correct me.

Getting "TimeoutException" when trying to retrieve data from MongoDB

I'm using C# to connect to a MongoDB server using the official MongoDB.Driver with version 2.2.24.26
My code looks like this:
internal BsonArray Find(string ConnectionString, string collection, string filter)
{
Uri u = new Uri(ConnectionString);
string database = u.LocalPath.Trim(new char[] { '/' });
IMongoDatabase _db = new MongoClient(ConnectionString).GetDatabase(database);
IMongoCollection<BsonDocument> col = _db.GetCollection<BsonDocument>(collection);
return BsonArray.Create(col.Find(BsonDocument.Parse(filter)).ToList());
}
It works like charm (it finishes within less than 0.5 seconds) if the connection string is like
mongodb://localhost:27017/my_db
As soon as I want to use authentication, I always encounter a timeout.
mongodb://user:password#localhost:27017/my_db
The operation consuming all the time is the "ToList()". The list in my tests does have 136 entries. Am I missing something?
Edit: Sorry for the wrong topic in the first place. I don't know how a topic from a totally unrelated issue did appear here...
I found the problem. MongoDB seems to give back an TimeoutException if the credentials are invalid. I accidentally added the user I wanted to use to the wrong database and hence I could not log into the original database with it. The exception made me search for the issue in a totally wrong direction :/
Looks like a strange behavior when using wrong credentials, but that is just my opinion.

SQLConnection connection error "Login failed for user server/guest"

I keep receiving a connection error. I know that the information is right, as I tried them out with SSMS now several times in the last few minutes, so the problem is in the C# connection string. According to various Google searches, the syntax is right, just it does not work.
try
{
// Get the connection information.
GetSQLConnectInfo(ref sConnect);
// Formulate the connection string.
String strConnect = String.Format("Server=myserver;Database=mydb;User Id=myusername;Password=mypassword;Trusted_Connection=yes;connection timeout=30");
// DATABASE: Create the connection.
SqlConnection oConnection = new SqlConnection(strConnect);
oConnection.Open();
if (ConnectionState.Open != oConnection.State)
return false;
return true;
}
catch
{
}
Error comes back with: Login failed for user 'myserver\Guest'.
Error Code: -2146232060
Error Number: 18456
It would seem that judging by the error message, the Open method does not recognize the user name, as Open tries to use a guest account, which obviusly will not work.
Am I missing something? I am using SQL Server authentication.
Remove Trusted_Connection=yes. That will override your SQL Authentication (username/password) settings and try to log in as the user running the app.

Categories